Could not contact DNS servers (fluent bit)

Question: I am configuring the fluent bit connection with elasticsearch, I have 3 elasticsearch nodes and I want to have high availability, according to the following documentation it is done like this text, but it is not connecting.
version: fluent-bit:2.1

error in the log is the following [2023/10/06 16:11:06] [ warn] [engine] failed to flush chunk '1-1696602761.424989.flb', retry in 1007 seconds: task_id=401, input=tail.0 > output=es.0 (out_id=0) [2023/10/06 16:11:06] [ warn] [net] getaddrinfo(host='forward-balancing', err=11): Could not contact DNS servers [2023/10/06 16:11:06] [ warn] [engine] failed to flush chunk '1-1696603081.377993729.flb', retry in 1935 seconds: task_id=482, input=tail.0 > output=es.0 (out_id=0) [2023/10/06 16:11:07] [ warn] [net] getaddrinfo(host='forward-balancing', err=11): Could not contact DNS servers

<code>    fluent-bit.conf: |
[UPSTREAM]
    name    forward-balancing

[NODE]
    name    node-1
    host    server1
    Port    9200

[NODE]
    name    node-2
    host    server2
    Port    9200

[NODE]
    name    node-3
    host    server3
    Port    9200

[SERVICE]
    Flush         1
    Log_Level     info
    Daemon        off
    Parsers_File  parsers.conf
    HTTP_Server   On
    HTTP_Listen   0.0.0.0
    HTTP_Port     2020

[INPUT]
    Name                tail
    Tag                 kube.*
    Path                /var/log/containers/*.log
    Parser              json
    DB                  /var/log/flb_kube.db
    Mem_Buf_Limit       5MB
    Skip_Long_Lines     On
    Refresh_Interval    10

[OUTPUT]
    Name            es
    Match           *
    Index           index-v1
    Host            forward-balancing
    Port            9200
    HTTP_User       user
    HTTP_Passwd     password
    Logstash_Format Off
    Type            _doc
    Replace_Dots    On
    Retry_Limit     False
    tls             On
    tls.verify      Off
    Suppress_Type_Name On
</code>
Answer: For me the issue was that using the kubeDNS do not resolved the domain if it was not found in the cluster. I've changed the dnsPolicy to "Default" and it solved the problem.
I hope this helps you in some way.


Cauchy's theorem or Frobenius' lemma

Question: A textbook exercises asks:

The goal of this exercise is to prove Frobenius's lemma, which asserts that if the order of the group $G$ is divisible by the prime $p$, then $G$ contains an element of order $p$.

The proof sketch given in the exercise is to consider the set of all ordered $p$-tuples of elements in $G$ whose components have a product equal to identity, and to show that a cyclic permutation that acts on the set of these $p$-tuples has at least $p$ fixed points. (I believe this proof is originally due to McKay, 1959).
I can solve this exercise, but my question here is just of historical curiosity - have you heard of this lemma before as being called Frobenius' lemma? It's usually only called Cauchy's theorem.
Comment: What textbook is that?
Comment: @DonAntonio: This is from Godsil and Royle's Algebraic Graph Theory text, Exercise 2.5.
Answer: It seems that part of the history can be found in the Wikipedia page on Burnside's lemma. Burnside's lemma is also called the Cauchy-Frobenius lemma or the orbit-counting theorem. This relates the number of orbits of a group action to the cardinal of the stabilizers. This is a basic result in the theory of group actions, as the orbit-stabilizer theorem.
According to Wikipedia, Burnside attributed this lemma to an article of Frobenius of 1887, in his book "On the theory of groups of finite order", published in 1897. But it seems that this result was well-known at this time and appears in a work of Cauchy in 1845 and Burnside's lemma is also known as the "lemma that is not Burnside's".
Concerning the exact result you are talking about, I've always heard of Cauchy's lemma or theorem. I wouldn't be surprised that Cauchy proved it in its work of 1845 (but what is it ?) and I imagine that there has been some confusion, related to Burnside's lemma, since in all proofs of Cauchy's theorem that I know, Burnside's lemma is used in some way.
The complete works of Cauchy can be found in http://portail.mathdoc.fr/cgi-bin/oetoc?id=OE_CAUCHY_1_9. I guess that Cauchy's theorem appears in "Mémoire sur diverses propriétés remarquables des substitutions régulières ou irrégulières, et des systèmes de substitutions conjuguées" but it would take some time to find where since the terminology is very different from the today one. Just remember that they don't speak of groups but of systems of substitutions...
Comment: I suppose if many of the proofs of Cauchy's theorem use Burnside's lemma in some way, that could have led to some  confusion.  The proof outlined in the exercise above doesn't require counting the number of orbits.

Cauchy's theorem or Frobenius' lemma


Stop sysstat sar

Question: How to stop sar collecting system activity without uninstalling sysstat? I have used systemctl stop sysstat but as I understand from running sar it continues collecting system activity.
Answer: Sar is ofttimes installed as a cron job. I would look for /usr/lib/sa/sa1 in /etc/cron* and /var/spool/cron/crontabs/* and comment it out or something to disable it.

Stop sysstat sar


Android GCM: Can we get data as a complete JSON structure?

Question: I am sending a message (POST) to Google GCM server https://android.googleapis.com/gcm/send for sending a push notification to a registered android device. The POST body looks something like this:
{
    "registration_ids" : [android_registration_id],
    "data" : {
        "message" : "Hello World!",
        "update" : "You've got a new update",
        "info" : "You've got new information updates too!"
    }
}

Suppose that I don't know what all key-value pairs are being sent to me (gcm registered android app) in the "data" field and I want to enumerate and print them, can I extract the fields in "data" as a JSON structure?
For e.g. In the above example, I need the following as a JSON object:
{
    "message" : "Hello World!",
    "update" : "You've got a new update",
    "info" : "You've got new information updates too!"
}

Comment: as i know GCM is sending the data capsulated in Bundle object, but you can try to send key - value structured data and as value put your json. not really sure if it will do the trick.
Comment: I can send the entire JSON as a value to suppose "json_structure" as you said, but I want to make it completely independent for the user, whatever the user passes, I'll make a JSON structure and display key-value pair.
Comment: what role is playing the user in the whole game? you are going to take the response and show it to the user.
Comment: sorry, let me rephrase it, the server passes arbitrary data, the user has to view that data. I just need to know if there is a way to dump the entire "data" value in a JSON structure, I'll iterate over key value pairs and display them.
Comment: you need to show the user the single parts of the whole json string as i understand like only Hello World from your example. So as I know from server side if you send a json string via GCM, android device will receive it as Bundle and you have to know the key to get the value. You can try to send a json within a json as value, not sure if it will work, but that's the only idea which I have, in case you don't know the keys.
Answer: Bundle data = intent.getExtras();
Iterator<String> it = data.keySet().iterator();
String key;
String value;
while(it.hasNext()) {
    key = it.next();
    value = data.getString(key);
}

Try this. Using key and value you can construct initial json.
Answer: JSONArray array = new JSONArray(jsonBodyOfTheResponse);

for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    .
    .
    . }


Simular click em Jq ou JS

Question: Pessoal precisava fazer 4 botões (cima,baixo,direita e esquerda) que chama-se uma função que simulasse o keybord up,down,left e right alguém pode me ajudar.
Simular as teclas pressionadas no teclado.
ou então como fazer uma função usando este js
https://github.com/wwwtyro/Astray/blob/master/keyboard.js
Em resumo quero fazer 4 botões para este jogo que ai clicar faz o mesmo do teclado
http://wwwtyro.github.io/Astray/
Comment: quero simular neste jogo http://wwwtyro.github.io/Astray/
Comment: Podes explicar o que entendes por _"simulasse o keyboard"_? queres que dispare eventos que o browser use?
Comment: quero simular como se eu tivesse pressionado no teclado a tecla up
Comment: sim o código eu sei, quero fazer um botão que ao clicar simule a tecla 38 ou keyup usando js ou jq.
Answer: Você tem que criar um evento do keydown e disparar ele no click do botão, fiz um exemplo que retorna um alerta da tecla pressionada, já pegando a partir do evento keydown:

<button type="button" id="up">Pra Cima</button>
<button type="button" id="down">Pra baixo</button>
<button type="button" id="left">Pra esquerda</button>
<button type="button" id="right">Pra direita</button>

Tive que fazer isso para meu jogo e funcionou perfeitamente
Comment: estou quebrando a cabeça com isso amigo veja o valor do  e.keyCode = 38 vem indefinido, e quando eu clico em algo no teclado ele dispara tudo de uma vez.
Comment: Testou pelo código aqui no stack? aqui funcionou normal
Comment: Posso afirmar para você que essa é a solução, eu uso e funciona normalmente. agora temos que ver o que você faz dai para frente com as teclas, se quiser poste seu código.
Comment: vou postar perai :D
Comment: Aqui amigo https://bitbucket.org/adilmar/game/src
Comment: Tranquilo, vou dar uma olhada, já dou um feedback
Comment: muito obrigado.
Comment: Realmente tem alguma coisa gerando conflito aqui, vou tentar arrumar para você
Comment: obrigado, pois é rsrsrs menos mal eu não sou tão noob assim kkkk.
Comment: Então, não consegui aqui e não vou ter tempo agora, mas descobri o que é, ele pega um KeyboardEvent então teria que trabalhar com essa API para setar o KeyboardEvent na DOM  e depois disparar o evento. https://developer.mozilla.org/pt-BR/docs/Web/API/KeyboardEvent
Comment: Se fosse para implementar em algo que você estivesse criando a resposta simularia as teclas, agora esse game trabalha de forma diferente, desculpa não poder ajudar no momento
Comment: vou tentar aqui muito obrigado mesmo.
Comment: sim vou tentar fazer algo do zero :D
Comment: Por nada, se a resposta foi útil pra você e puder votar agradeço ;)
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/69941/discussion-between-arllondias-and-adilmar).
Answer: Esse script, não simula... ele dispara o evento como se a tecla tivesse sido pressionada.

var direcionar = function(keycode){
    var e = jQuery.Event("keydown");
        e.which = keycode;
    $(window).trigger(e);

}

      <input type="button" value="Acima" onclick="direcionar(38)" />

      <input type="button" value="Esquerda" onclick="direcionar(37)"/>

      <input type="button" value="Direita" onclick="direcionar(39)"/>

      <input type="button" value="Abaixo" onclick="direcionar(40)"/>

Comment: estou quebrando a cabeça com isso amigo veja o valor do  e.keyCode = 38 vem indefinido, e quando eu clico em algo no teclado ele dispara tudo de uma vez.
Comment: pera, você quer disparar o evento quando a pessoa clica no botão ou quer que ao teclar as setas os botões sejam pressionados?
Comment: quando clicar no botão veja https://bitbucket.org/adilmar/game/src
Comment: substitua o alert por um console.log(e) que você verá.
Answer: Se entendi bem, você quer mover um objeto na tela como se estivesse pressionando as setas do teclado. Com este código você simula algo parecido:

var alvo = $('#bola'); // objeto que será movido
var incremento = 2; // números de pixels a se mover
var continua;

$('.btn').mousedown(function(){
   var idx = $('.btn').index(this);
   continua = setInterval(function(){
      moveObj(idx);
   }, 50);
}).on('mouseup mouseleave', function() {
   clearInterval(continua);
});

function moveObj(idx){

   if (idx == 0 || idx == 2){ // botão UP e DOWN
      var dir = 'top';
      var inc = idx == 0 ? -Math.abs(incremento) : incremento;
      var mover = alvo.offset().top+inc;
   }

   if (idx == 1 || idx == 3){ // botão LEFT e RIGHT
      var dir = 'left';
      var inc = idx == 1 ? -Math.abs(incremento) : incremento;
      var mover = alvo.offset().left+inc;
   }

   alvo.css(dir, (mover+inc)+'px');

}

   <input type="button" value="↑" class="btn" />

   <input type="button" value="←" class="btn" />
   <input type="button" value="↓" class="btn" />
   <input type="button" value="→" class="btn" />

Simular click em Jq ou JS


Motivation of Functional Analysis

Question: What is the motivation of functional analysis? What originally motivated its study? By functional analysis, I mean the study of Banach and Hilbert spaces.
Comment: I believe it was the possible (and actual power) of being able to extend real and complex analysis to functions themselves, where one had a strong intuition where it would lead.  One thing it gets you quickly is Laplace and Fourier transforms, so I suspect it arose also as a practical need to prove functional theory, where functions could be represented by infinite series of other functions, which made it possible to solve a whole bunch of differential equations that were current and relevant at the time, but that is just a hunch.
Answer: The original motivation was the work of Fourier. Fourier's principle of superposition in formulating and solving the heat equation was an abstract definition of linearity and linear operator, and it came well before concrete notions had been formalized. Fourier argued that if you superimposed heat sources, the individual solutions would be superimposed, and if you magnified the source, the result would be likewise scaled. The general concepts of linear space and linear operator were thus defined in this infinite-dimensional context of the heat equation long before the definition of a finite-dimensional vector space, finite-dimensional linear operator, or eigenvalue/eigenvector analysis was conceived. The finite-dimensional grew out of the infinite-dimensional, which is particularly strange.
Fourier then devised his method of separation of variables to solve his heat equation in different coordinate systems. This lead to the study of symmetric differential operators, eigenvalue problems, and orthogonal expansions; as mentioned, this came before such things had even been defined in finite dimension linear space. Fourier conjectured that general functions of his time (which were basically piecewise explicitly given by concrete functions,) could be expanded in these orthogonal functions. These ideas caused those in power at the time to ban his original manuscript from being published for over a decade, until Fourier came to power in the Math community, and forced its publication in basically its original form. Analysis was in its infancy during that period of time, crippled by the fact that 20+ centuries of thought had not yet produced a rigorous definition of a real number. Cauchy had defined a sequence that he described as "converging on itself" (now called a Cauchy sequence) without any means of finding a limit. General functions of that time were explicit, but did allow for piecewise defined functions. There was no Set Theory, or general rigor. Mathematical Analysis was driven a lot by opinion, intuition and consensus. And there was no definite integral, which really complicated an understanding of the Fourier series.
Several decades later, Riemann defined his integral with the stated intent of studying Fourier expansions. Later Lebesgue refined Riemann's work, also with the stated intent of studying Fourier expansions. During these times, Cantor came up with set theory, and with the first definition of a real number, which made it possible to address serious questions of convergence. Fourier Analysis gave rise to the Cauchy-Schwarz inequality in Schwarz' paper on integral equations, and the stage was set for dealing with functions as points in a space, with a distance metric to study convergence, which could be used to complete the space a few decades later. Methods of completing the rationals to the reals were borrowed to study spaces where functions were points, and an abstract distance was defined. Frechet defined a metric space in his Master's thesis. An abstract metric was defined, and General Topology grew out of the abstract notion of a neighborhood of Hausdorff. All of this had a rigorous foundation because of Cantor's Set Theory.
In the midst of all of this, Hilbert defined his infinite-dimensional extension of Euclidean space, $\ell^2$, and it was built to order to study Fourier series and other orthogonal expansions. Part of this was driven by the need to be able to digest the deep work of Fredholm on integral equations, which eventually happened because of Riesz' abstractions leading to the notion of a compact operator. Compactness had come into existence and study not long before that after having a rigorous definition of a real number. Riesz was one of the first to look at a continuous linear functional on continuous functions on $[a,b]$, and he was able to prove that such a thing was a Riemann-Stieltjes integral. Others began looking at continuous functionals, and $L^p$ arose in the context of understanding dual problems, eventually leading to the understanding that a continuous dual could not be identified with the original space, which was quite a surprise after studying finite-dimensional Linear Algebra.
General spectral theory emerged because of trying to understand the orthogonal function expansions of Fourier, many of which were very non-trivial. Operator theory grew out of von Neumann's work, who was a student of Hilbert. General notions of distance and Frechet metric led to Hausdorff's neighborhood axioms of General Topology. General linearity and linear operator came out of Fredholm's work, and was promoted by von Neumann. Operator theory and abstract linear space were borrowed by Dirac for Quantum Mechanics. von Neumann looked at Quantum foundations, proved a general Spectral Theorem for unbounded selfadjoint linear operators. And he studied Operator Algebras.
That's a basic outline of the development leading to the modern setting of Functional Analysis.
Comment: I had no idea that Fourier had introduced these ideas (linear operator, eigenvalue/eigenvector, orthogonal expansion) in function spaces before they were even defined in finite-dimensional contexts. Too often I forget that the order in which we learn things today is not the order in which ideas were discovered...
Comment: @angryavian : The really strange part for me was how infinite-dimensional spaces, integral orthogonality conditions, and unbounded operators came before finite-dimensional spaces. And symmetric operators with respect to integral inner products came first, before studying symmetric matrices. It's really remarkable.
Comment: Why does the abstraction of functional analysis help for such a small number of questions? But either way, do you know of any source that helps with studying functional analysis with this motivation?
Comment: @user109871 : I would recommend J. Dieudonne's book "History of Functional Analysis".

Motivation of Functional Analysis


How do you extract multiple email addresses from an RFC 2822 mail header in python?

Question: Python's email module is great for parsing headers.  However, the To: header can have multiple recipients, and there may be multiple To: headers. So how do I split out each of the email addresses? I can't split on the comma, since the comma can be quoted. Is there a way to do this?
Demo code:
msg="""To: email@example.com, "User Two" <email@example.com", "Three, User <firstname.lastname@example.com>
From: email@example.com
Subject: This is a subject

This is the message.
"""

import email

msg822 = email.message_from_string(msg)
for to in msg822.get_all("To"):
    print("To:",to)

Current output:
$ python x.py
To: firstname.lastname@example.com, "User Two" <email@example.com", "Three, User <firstname.lastname@example.com>
$

Comment: Likely you ought to go with `shlex` & Co.. MDAs split address lines by (unquoted) commas
Comment: related: https://docs.python.org/2/library/email.util.html#email.utils.getaddresses
Comment: What output do you want?
Answer: Pass all of the To lines through email.utils.getaddresses():
msg="""To: email@example.com, John Doe <email@example.com>, "Public, John Q." <email@example.com>
From: firstname.lastname@example.com
Subject: This is a subject

This is the message.
"""

import email

msg822 = email.message_from_string(msg)
for to in email.utils.getaddresses(msg822.get_all("To", [])):
    print("To:",to)

Note that I rewrote your To line. I believe your example wasn't a valid format.
Reference: https://docs.python.org/3/library/email.utils.html#email.utils.getaddresses
Comment: Perfect. I read the docs, but I just couldn't find what I was looking for. Thanks!
Comment: Link for python 3: https://docs.python.org/3/library/email.utils.html#email.utils.getaddresses
Comment: @Neara - Thanks. Updated.


Get a selector property value defined through a mixin with SASS

Question: Is it possible to get the value of a property defined through a mixin for a selector within another selector. For example:
<code>@mixin mymixin($mywidth) {
  width: $mywidth;
}

div {
  @include mymixin(90%);
}

p {
  width: (20 / (([GET_SOMEWAY_DIV_WIDTH] * 960) / 100)) * 100;
}
</code>
Answer: Use a variable:
<code>$mywidth: 90%;

div {
    width: $mywidth;
}

p {
    width: (20 / (($mywidth * 960) / 100)) * 100;
}
</code>

Edit re: OP edit. AFAICS, when using mixin arguments, those values are only accessible within the scope of the mixin, when the mixin is included. Refactor so that you pass a variable to the included mixin:
<code>$mywidth: 90%;

@mixin mymixin($mywidth) {
  width: $mywidth;
}

div {
  @include mymixin($mywidth);
}

p {
  width: (20 / (($mywidth * 960) / 100)) * 100;
}
</code>
Comment: Ok, sorry, I forgot something important in my question. The property is defined through a mixin. I updated the question. Thank you.


Can some one explain what does it mean by the words "integral over $R$"?

Question: The integral closure of a commutative unit ring $R$ in an extension ring $S$ is the set of all elements of $S$ which are integral over $R$. It is a subring of $S$ containing $R$.
Can someone explain what does it mean by the words integral over $R$?
Comment: Root of a monic polynomial with coefficients in $R$.
Answer: An element $x \in S$ is integral over $R$ if there is a monic polynomial $P(T) = T^n + a_{n-1}T^{n-1}+ \cdots + a_1 T+a_0 \in R[T]$ such that
$P(x) = 0.$

(Non-)examples:
1) Any element of $R$ is integral over $R$.
2) But $1/2 \in S = \Bbb Q$ is not integral over $R = \Bbb Z$ (it is a root of $2T-1$, but this polynomial is not monic ; and no monic polynomial with integer coefficients can have $1/2$ as root).
3) $\pi \in S = \Bbb R$ is not integral over $R = \Bbb Q$.
4) $i \in \Bbb C$ is integral over $\Bbb Z$, being a root of $T^2+1$.

Geometric interpretation : if $R \subset S$ is integral, then $\mathrm{Spec}(S) \to \mathrm{Spec}(R)$ is closed (because of the going-up), and it is surjective.
Comment: In fact a morphism of schemes is integral if and only if it is affine and universally closed, see [[Tag 01WM](https://stacks.math.columbia.edu/tag/01WM)].
Answer: An element $s\in S$ is integral over $R$ iff there exists a monic polynomial $f\in R[x]$ such that $f(s) = 0$ (as opposed to agebraic, which doesn't require the polynomial to be monic).
For instance, take $R = \Bbb Z$ and $S = \Bbb R$. Then $\frac12\in \Bbb R$ is not integral, because there is no monic polynomial (with integer coefficients) which has $\frac12$ as root. On the other hand, $\sqrt2$ is integral because $x^2 - 2$ is monic. So the integral closure of $\Bbb Z$ in $\Bbb R$ contains $\sqrt 2$ but not $\frac12$.
Answer: the definition of "$S$ is integral over $R$" is well-explained by the two answers already given. however if you are new to this concept it may be helpful to know the significance of this definition.
Informally we may say "$s$ is integral over $R$" means that for any $s \in S$, we have that $R[s]$ is a finite-dimensional extension of $R$. That is to say we can find a finite set $s_1, \dots, s_n$ of elements of $S$ such that any element $s'$ of $R[s]$ can be written as a finite sum:
$$
s' = \sum_i r_i s_i
$$
with $r_i \in R$.
once you see the connection between this idea and the requirement that $s$ satisfies a monic polynomial over $R$, you will be well on your way to understanding the importance of integrality
Comment: The  first line of the  2nd paragraph may have typo because you wrote $ \ s \ is \ integral \ over \ R \ $ . But I think it should be $ \ S \ is \ integral \ over \ R \ $ i.e. small $ \ s \ $ will be $ \ S \ $
Comment: no, i meant by $s$ a particular element of S. it is not necessarily true that the integral closure of $R$ is finite-dimensional over $R$. for instance the ring of algebraic integers is not finite-dimensional over $\mathbb{Z}$, but every algebraic integer is. whereas $\frac12$ is not integral over $\mathbb{Z}$ since it $\mathbb{Z}[\frac12]$ contains all numbers $\frac1{2^n}$


Turn a list into a matrix

Question: I worked all afternoon on a simple thing but cannot seem to get it right for some reason : how to turn a list into a matrix of given width.
Example :
I got a list such as
[1, 3, 5, 7, 6, 8, 9, 0]

and want to create a matrix such as
[[1, 3],
 [5, 7],
 [6, 8],
 [9, 0]]

through a predicate
list2matrix/3 : list2matrix(List, Size_of_Rows, Matrix).

In this example used like :
list2matrix([1, 3, 5, 7, 6, 8, 9, 0], 2, Matrix).

The predicate should fail if the length of the list is not a multiple of the size of the rows.
I decided not to post my work since I think I got it so wrong that it would not help me to get correction on it ;(
Thanks by advance if you can propose any leads about how to deal with such a problem.
Comment: Your problem statement is incomplete. Shall `list2matrix([1, 3, 5], 2, Matrix)` succeed or fail? And in case of success, shall `[5]` be dropped or extended to `[5,_]` or whatever other value.
Comment: let's say it'd fail, thanks for pointing that out. Since I intend on using it on list with square lengthes I didn't precise ;(
Answer: You can divide the problem in two parts.
The first building block would be to build a row of N elements. That is to take the input list and split it in two lists, one will have exactly N elements (the row) and the other is the remaining of the input list.
The second building block would be to build the matrix which is made of rows.
list_to_matrix([], _, []).
list_to_matrix(List, Size, [Row|Matrix]):-
  list_to_matrix_row(List, Size, Row, Tail),
  list_to_matrix(Tail, Size, Matrix).

list_to_matrix_row(Tail, 0, [], Tail).
list_to_matrix_row([Item|List], Size, [Item|Row], Tail):-
  NSize is Size-1,
  list_to_matrix_row(List, NSize, Row, Tail).

Comment: Your `list_to_matrix_row` can be simplified to `list_to_matrix_row(L, RowLen, Row, Rest) :- length(Row, RowLen), append(Row, Rest, L).`
Comment: Thanks a lot for your answer, I'm trying to understand it and will test it soon, I'll comment after that :)
Comment: Ok ok, I read it and understood it quite easily, though I still think I'd have had a hard time finding a solution by myself :(

I just added :- !. to cut backtracking after each first choice so that it's deterministic and now I have what I wanted, thank you a lot :)
Comment: You 're right!. However I believe it is easier to understand with this recursive procedure.
Answer: BTW, I thought I'd mention the code I finally wrote :
length_(Length, List) :- length(List, Length).

list2matrix(List, RowSize, Matrix) :-
    length(List, L),
    HowManyRows is L div RowSize,
    length(Matrix, HowManyRows),
    maplist(length_(RowSize), Matrix),
    append(Matrix, List).

It's more high order oriented and funnier to read I guess :)
Comment: Interesting! With [`library(lambda)`](http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl) you could write `maplist({RowSize}+\Xs^length(Xs,RowSize), Matrix)` instead of using an auxiliary definition. See [this intro](http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/ISO-Hiord).
Answer: Look for a pattern in your desired outcome.
That means pair numbers will be allocated as the second number in each pair and non pairs will be in first place each time.
Create a bi dimensional array and assign non pair positions to sub index "a"
and pairs to "b".
As you could see "i" is an index for an array, a multidimensional array.
i[a][b]
You need to iterate through both arrays in order to accomplish this.
Hope it helps.
Comment: the problem I got when doing it this way is that it's fine for 2 as width of the matrix but not for any number instead of 2. In my case I'm interested in particular in transforming a list whose length is 81 into a 9*9 matrix. I'd like the resulting predicate to be size-hardcoding free but if 9 gotta be hardcoded then it's ok !

Turn a list into a matrix


Proof of Riemann Hypothesis

Question: This proof was released this year:
http://arxiv.org/abs/1508.00533
Where is the mistake? I just found it and was wondering how obviously wrong it is.
Comment: Already the very first sentence of the introduction has two mistakes in "every nontirivial zeros"
Comment: Nine pages certainly does not induce confidence
Comment: @HagenvonEitzen Haha, I mean mathematical mistakes.
Answer: The proof of lemma 2.1 (the first thing the author proves at all) is false (though I didn't check if the claim of the lemma is possibly correct for other reasons):
Let $R_n(s):= \frac{1+(-1)^n}{n^{s}}$. This $R$ has sufficiently similar properties as the series remainder term, at least as far as they were used in the alleged proof:
First of all, $$\tag1\lim_{n\to\infty}R_n(s)=0.$$
Next, $$R_n(s)-R_{n-1}(s)=\frac{1+(-1)^n}{n^{s}}-\frac{1-(-1)^n}{(n-1)^{s}}=\begin{cases}-\frac{2}{(n-1)^s}&n\text{ odd}\\\hphantom{-}\frac2{n^s}&n\text{ even}\end{cases}$$ and
$$R_n(s)-R_{n+1}(s)=\frac{1+(-1)^n}{n^{s}}-\frac{1-(-1)^n}{(n+1)^{s}}=\begin{cases}-\frac{2}{(n+1)^s}&n\text{ odd}\\\hphantom{-}\frac2{n^s}&n\text{ even}\end{cases}$$
so that
$$\frac{R_n(s)-R_{n-1}(s)}{R_n(s)-R_{n+1}(s)}=\begin{cases}\left(1+\frac2{n-1}\right)^s&n\text{ odd}\\1&n\text{ even} \end{cases}$$
and $$\tag2 \lim_{n\to\infty}\frac{R_n(s)-R_{n-1}(s)}{R_n(s)-R_{n+1}(s)}=1.$$
It appears that the author thinks that $(1)$ and $(2)$ (or maybe even $(2)$ alone) imply
$$ \lim_{n\to\infty}\frac{-R_{n-1}(s)}{R_n(s)}= \lim_{n\to\infty}\frac{-R_{n+1}(s)}{R_n(s)}=1.$$
However, with $R$ as defined by me, these limits do not even exist.
Comment: Ha, thanks. What an odd thing to say.

Proof of Riemann Hypothesis


How do I make Amazon EC2's load balancer round-robin?

Question: When a user comes to my site, I want him to hit one server during his browsing period. I don't want him to jump from server to server as he pages through my site.
I want his "session" to be kept to that server only.
How can I do that with load balancer?
Answer: Well, technically that's what round-robin is - sending each connection to a different server in sequential order.
What you're referring to is usually called persistence, or stickiness, and the EC2 load balancer can achieve this by inserting cookies into the HTTP stream. It can generate its own cookies and then check for the value on subsequent requests. So the cookie might say something like "Server 1" and the load balancer knows to send the connection back to server 1. You can also make use of existing application cookies. See:
http://aws.amazon.com/about-aws/whats-new/2010/04/08/support-for-session-stickiness-in-elastic-load-balancing/
and
http://docs.amazonwebservices.com/ElasticLoadBalancing/latest/DeveloperGuide/
The drawback is that the client must have cookies enabled in their browser.


How can I make Asterisk keep track of dynamic SIP agent statuses?

Question: I am setting up a new server using Asterisk 1.8.11-certified4.  In testing, we're seeing that agents dynamically logged into the queue will receive a second queue call as a call-waiting when call-limit is set to 0.
Since the agents in question are not always in the agent queue, call-limit=1 would unnecessarily prevent them from receiving call waiting even when they're out of the queue.
The test and result from the below configs were as follows:

Had remote user login to queue
Placed call into queue
remote user answered call #1
placed call #2 to queue
remote user reported the second call came in as a call-waiting.

extensions.ael

context enter-sales-queue {
        s => {
                Answer();
                Queue(den-x-queue,,,,60);
                Voicemail(9001,u);
                Hangup();
        };
};

queues.conf

[den-careers-queue]
strategy=leastrecent
timeout=17
ringinuse=no
autopause=no
musicclass = default
context = so-operator
monitor-format = wav
setinterfacevar = yes
timeoutpriority = conf
monitor-type=MixMonitor
reportholdtime=no
ringinuse=no
joinempty=strict
leavewhenempty=strict
retry=2

sip.conf

[local-codecs](!) ; local user codecs, dont compress.
disallow=all
allow=ulaw
allow=alaw

[basic-options](!) ; template for what every sip user should have
dtmfmode=rfc2833
context=stationside
type=friend
host=dynamic
allowsubscribe=yes
subscribecontext=blf
notifyringing=yes
notifyhold=yes
limitonpeers=yes
call-limit=0

[local-mode](!,basic-options,local-codecs)
nat=no
qualify=yes

[6599](local-mode)
secret=xxxx
callerid=Peter Grace
accountcode=foobar

Answer: I asked the same question in the Asterisk IRC channel on freenode, and one of the developers responded indicating that in newer asterisk versions (I assume 1.8 and above) you need to specify callcounter=yes in your general config of sip.conf.
He also mentioned that call-limit should never be zero, as that is not technically a valid option for that field.  It should be 1 or greater.
In versions of asterisk prior to 1.8, callcounter=yes does not exist, so simply specifying a call-limit with an arbitrarily high number will cause Asterisk to track the number of calls properly and make the queue function as expected.

IF ASTERISK 1.8 OR LATER:
sip.conf

[general]
callcounter=yes

IF ASTERISK PRIOR TO 1.8:
sip.conf

[exten]
type=friend
...
call-limit=999

Answer: This may help:
Following reports from several Asterisk users that they're having
problems with ringinuse=no not working when Local Channels are used to
provide hot-desking support within the Asterisk Queue() function, we
have developed a very easy fix for this that is now documented in our
popular Asterisk Queues Tutorial.
You don't need to do anything fancy with STATEINTERFACE to get this to
work, and it also works with all Asterisk phone types, including SIP and
DAHDI channels.
For further details please see:
http://www.orderlyq.com/asteriskqueuesLocal.html#ringinuse
So, if you're struggling with this, perhaps as a result of abandoning
the now-deprecated Agent Channel mechanism, you might want to take a look :)
[edit]
This requires using OrderlyStats and setting the Auto-Pause parameter in the Admin section to >0
[\edit]
Comment: Welcome to Server Fault! Generally we like answers on the site to be able to stand on their own - Links are great, but if that link ever breaks the answer should have enough information to still be helpful. Please consider editing your answer to include more detail. See the [FAQ](http://www.serverfault.com/faq) for more info.


Constrained Maximum

Question: I need to prove that if the distance from a point $P$ contained in the surface $f(x,y,z)=1$ ($f$ is of class $C^1$) to the origin is maximum, then $P$ is perpendicular to the surface, how can I prove this?
Normally I would use Lagrange multipliers with the surface as a constraint, but in this case I don´t even know $f$ so I can´t obtain its partial derivatives, there must be something I'm missing, any help will be appreciated.
Answer: You can still use Lagrange multipliers, together with the information that $\nabla f$ is perpendicular to the level surface $\{f = 1\}$. Indeed, it suffices to show that $P$ is parallel to $\nabla f(P)$. To do this we use that $P$ is a solution to the system
\begin{cases}
\nabla d^2 = \lambda \nabla f \\
f = 1.
\end{cases}
Notice that the first equation evaluated at $P$ yields $2P = \nabla d^2(P)  = \lambda\nabla f(P)$, which is exactly what we are after.
Comment: I was missing that the gradient was perpendicular to the level surface, thanks a lot!
Comment: It is a really useful thing to keep in mind! I am glad I could help :)

Constrained Maximum


Endogeneity & IV = model misspecification?

Question: I'd like to raise a controversial point: if you need instrumental variables, your model is wrong.
Basic endogeneity problem and the IV solution
Let us suppose the basic framework of endogeneity and instrumental variables (IV): we want to estimate the regression function $E(y|x,z)$, and choose a linear model of $y$ on $x$ and $z$, where $x$ is endogenous and $z$ is not. Endogeneity is a serious problem, and can stem from many causes: reverse causation, simultaneity, omitted variables, measurement errors correlated to $y$, model misspecification, etc.
$y_i= \beta_0 + \beta_1 x_i + \beta_2 z_i + \varepsilon_i$ (1)
$E(\varepsilon|x) \neq 0$, $E(\varepsilon|z) = 0$
The OLS estimate of the $x$ parameter $\hat{\beta_1}_{OLS}$ is biased and inconsistent because of the endogeneity of $x$. We thus turn to an instrument, say $w$, which should be (ideally well) correlated to $x$ (conditional on the other regressors) and uncorrelated to the error term $\varepsilon$ of the previous model, in practice:
$E(x|w) \neq E(x)$, $E(x|w) \neq E(x|z,w)$, $E(\varepsilon|w) = 0$
The IV method can be seen as replacing $x$ by $\hat x_{z,w}$ in model (1), where $\hat x_{z,w}$ is the prediction of a linear regression of $x$ on $z$ and $w$. OLS on this new model yields a consistent estimate $\hat{\beta_1}_{IV}$ of the parameter of interest $\beta_1$.
Interpretation of IV estimates
Notice that the IV fit necessarily has a lesser predictive power compared to the OLS fit, because by definition OLS has the lowest mean squared error among all linear models. In econometrics this is justified as a trade-off between goodness-of-fit and consistency of the parameter estimation: the main interest lies not in prediction but in the estimated values of certain parameters, usually in linear models derived from economic theory.
My problem is that most econometric models interpret these parameters of interest ($\beta_1$ in model 1), as the partial derivative $\frac{\partial y}{\partial x}$, the mean effect of a variation of $x$ on the variation of $y$. This is obviously wrong, because in order to compute $\hat{\beta_1}_{IV}$ we deliberately ignored the non-linear effect that $x$ has on $y$ through $\varepsilon$, restricting ourselves to the $\beta_1$ component. This is an important point to make, given the high regard in which IV estimates are held by academics and policy makers.
Of course one could argue that the goal of modelization is to approximate reality, and that to capture the isolated linear effect is better than nothing. The fact of the matter, I would argue, is that if modelization and the estimation of $\frac{\partial y}{\partial x}$ are to be taken seriously, they should not be estimated by sweeping under the rug those relationships that are present in the data but do not conform with the model specification.
If you need IV, your model is wrong
If the point of interest is the estimation of the effect of $x$ on $y$ (given the other regressors) and if $x$ is endogenous in the linear model, then the specified linear model is just wrong, because it violates the hypothesis of non-correlation of $\varepsilon$. Using IV seems to amount to just ignoring this problem and return the "pure" linear effect of an erroneous model, which sounds rather insulting to the scientific spirit. At best, it can be seen as a truncated Taylor expansion, which will only be valid close to the mean point of the dataset.
So rather than resorting to IV when confronted with endogeneity, it seems to me one should aim to find a better model to explain the relationship. A great many "universal approximation" models are readily available (kernel regression, lasso, gradient boosting, neural networks...) and can be used as a benchmark in comparison with the prediction power of any specified model. If a model has poor prediction power, it is a poor representation of reality.
If the final aim is to estimate the "full" partial effect of $x$ on $y$, algorithms such as local kernel-weighted regressions can be run at the points of interest, the parameters of which can be interpreted as local partial derivatives.
And if one is stuck with an endogeneity-ridden linear model because of economic theory, then IV estimates will only be gross approximations of the true effects, and conclusions will only be misleading, right?
Any comments, or references to related literature? (sorry for the long post)
Comment: If I get you right, you're saying that the error term always moves with $x$, so getting the linear coefficient on $x$ will ignore the correlated effects in the error term.  It is true that observational variations in $x$ will change $y$ through $\epsilon$ as well as $x$.  The interpretation of the IV however is generally "what would happen if someone went and set some policy that exogenously changed $x$ and only $x$?"  Of course, the imposition of such a policy would probably change a whole other set of unobservables (Hawthorne effects, etc), but that's a different problem.
Comment: One more thing:  you keep harping on the linearity issue.  Economists definitely rely too much on linear models.  Two-stage generalized additive models are possible, as described in this under-cited (to my mind) paper:  https://www.ucl.ac.uk/statistics/research/pdfs/rr309.pdf
Comment: Thank you for the nice reference! About your comment, my present point is not so much the "ceteris paribus" assumption of a policy that exogenously changed $x$ and only $x$ (which is a serious problem on its own, of course), but rather the fact that IV methodology chooses to ignore part of the effects of $x$ itself.
Answer: You raise too many issues, and for most of them any answer will probably be seen as being primarily opinion-based, so this post may be quickly closed.
To provide some comments on some of them:

Quote: If a model has poor prediction power, it is a poor representation of
  reality.

This would be true in the natural sciences, where physical laws appear to not change over the years. But in social sciences, "laws" change over the years or over different socio-economical environments. Example: the econometric models that failed to cope with the Oil crisis of '73 became useless for the crisis and for after the crisis. They were doing a pretty good job up to that point, and even today, they remain pretty adequate models to describe the economy before that crisis. "Reality" is not the same as "future".

Quote: (The IV estimator)...At best, it can be seen as a truncated
  Taylor expansion, which will only be valid close to the mean point of
  the dataset.

and

Quote: ... IV estimates will only be gross approximations of the true
  effects, and conclusions will only be misleading, right?

...which implies that you somehow are certain that the correlation of the regressor with the error term is in most cases "large" and "strong". Is there evidence of such?
Mind you, I am not in love with IV estimation -I am just trying to point to you aspects of your deliberations that could be made more robust.
Comment: Thanks. About "Reality" is not the same as "future", I couldn't agree more, and what I meant by "prediction" is just prediction on withheld data that follow the same distribution as the training data.
Comment: And about your second point: the reverse point can be made just as easily, IV supposes that the correlation with the error term is irrelevant.
Comment: Exactly... which means that the argument against the IV has just been weakened, from "The IV ignores important correlations" to "The IV ignores correlations that could be important" -and there is a very big difference between the two. The point here is that to assess an estimation method one needs to _quantify_ somehow its flaws and merits, or at least rank the estimator based on its _relative_ flaws and merits, against other available (or newly proposed) estimators. And this is not what your post is doing... although it appears that you do have some concrete ideas towards such a direction.
Comment: Ok, so we agree that IV ignores potentially important relationships in the data, namely the effect of $x$ on $y$ through $\varepsilon$. My point is that IV is typically used when an endogeneity test (eg. Durbin-Wu) says this effect _is significant_, and then chooses to continue as if this effect had no part in the partial derivative of $y$ on $x$. Thus the vey argument taken to justify the use of IV tends to indicate that the ignored effect is sizeable.
Comment: Are you by any chance implying that "statistical significance" (as is the unfortunate name), has anything to do with the "size/magnitude" of an effect? Because it doesn't.
Comment: Good point of course, but what it does say is the effect is not null. So I would say the burden of proof concerning the magnitude of the effect should lie with those claiming it is negligible.
Comment: The burden of proof rests always with the accuser -never with the defendant. You think that a widely used estimation method is seriously flawed and misleading. It is your responsibility to set out to prove it, or at least provide convincing theoretical argument and empirical evidence that it does. Ideally, but not necessarily, you should also show which method(s) is(are) to be preferred, and why.
Comment: Well that is an appeal to authority, but you are right in the fact that I should present some empirical evidence (working on it). I think my theoretical argument is pretty clear now, though.
Comment: This is serious (and important) research-level work. I do not know what is your relation with all these, but if you are into scientific research, then you should seriously consider turning this into a research project.
Answer: If I understand correctly, your point, you are saying that, because the IV estimator gives only the "direct" effect of $x$ on $y$, and not the "indirect", of $x$ on $y$ through the errors (which you claim is non-linear), it does not give the correct interpretation of $\partial y /\partial x$. Instead, you suggest to use other methods such as kernel regression, lasso, etc... and say simply a model with endogeneity is wrong (so it is not clear what is your solution... use kernel/lasso for the model or discard the model?).
I see several issues with your argument. You notice correctly that in terms of prediction, OLS would be superior, so I assume your goal here is not to obtain the best prediction, but to estimate the effect of x on y precisely. If such is the case, the indirect effect through $\epsilon$ is generally of no interest for the model, since it is a sort of spurious effect, that precisely the IV estimator seeks to get rid of.
If you are interested in the interpretation of the IV estimate, there is an interesting discussion in the potential outcomes framework by Angrist and colleagues, who show that the IV identifies a "complier average treatment effect" (in the case dummy instrument and dummy endogeneous), so IV does correspond to a well defined quantity of direct interest.
Now regarding the other methods you suggest, note they no dot solve the problem of endogeneity. These are just different estimators for the same underlying model, and as such won't change the issue of endogeneity, and actually using these would be precisely sweeping under the rug the problem of endogeneity! So you would need to do kernel IV (a quite tough topic), or lasso IV, etc...
Coming finally to your last point that a model with endogeneity is a wrong model, here again you are getting confused between a model and its estimator... There are many models we cannot estimate (due to endogeneity, under-identification, too many parameters, etc), but saying that a model is wrong because our estimators are wrong is quite a controversial stand, and correspond to searching the keys under the light although you know they are somewhere else.
Comment: I agree that my post is confusing in regard of the "solution" (I would say: toss the model and find another one, either a linear model without endogeneity or a local method). However I disagree with your statement that the indirect effect through $\varepsilon$ is of no interest to the model: the fact that the model did not plan for this indirect effect does not make it spurious, but rather indicates that the model does not account for the full effect of $x$. And I must suppose the quantity of interest to which IV corresponds does not account for it either.
Comment: Regarding the assertion that a linear model with endogeneity is wrong, I still think it holds:
Comment: it is incapable of taking into account part of the effect of $x$ on $y$, because it supposes that $\varepsilon$ does not vary with $x$ (and IV comes down to taking the model seriously anyway). And I think the problem is not the estimator so much as the model: any linear model is interpreted as though $x$ did not affect $\varepsilon$, which is just wrong with endogeneity present. Any estimator taking the model seriously will rely on this violated hypothesis.
Comment: And my position is that local methods do not suffer from endogeneity, because they transform model (1) into $y^i = \beta_0^i + \beta_1^i x^i + \beta_2^i z^i + \varepsilon^i$, letting the parameters vary from one point to another, and thus do not impose any restriction on the form of $\frac{\partial y}{\partial x}$. So they solve endogeneity by relaxing the very hypothesis that made it a problem in the first place.
Comment: PS: my claim that the uncaptured effect is non-linear stems from the fact that I suppose any linear effect of $x$ will be captured by OLS or IV, but I am not fully sure that is true.
Answer: Here are Cameron and Trivedi (Microeconometrics, 2005) explaining the tight connection between IV consistency and correct model specification:

"The essential condition for consistency of IV is condition 1 in Section 4.8.6, that the instrument should be uncorrelated with the error term. No test is possible in the just-identified case. In the overidentified case a test of the overidentifying assumptions is possible (see Section 6.4.3). Rejection then could be due to either instrument endogeneity or model failure. Thus condition 1 is difficult to test directly and determining whether an instrument is exogenous is usually a subjective decision, albeit one often guided by economic theory."
"There is no formal test of instrument exogeneity that does not additionally test whether the regression equation is correctly specified. Instrument exogeneity inevitably relies on a priori information, such as that from economic or statistical theory."

So interpreting IV estimates as the true effects demands simple faith in a proposition that is absolutely untestable, because $\varepsilon$ is by definition unobserved, and on top of that any valid instrument will be correlated with $\hat \varepsilon_{OLS}$... does that sound scientific to anyone?
Unless there is solid external evidence that the model is correctly specified, and that $\frac{\partial y }{\partial x}$ has the form specified in the model, the error term counting for nothing, I would say it doesn't (and I tend to doubt that such evidence can be robustly found in the social sciences).
Comment: And a paper by Hall, Tavlas and Swamy (2011) [The Non-existence of Instrumental Variables](http://www.le.ac.uk/economics/research/RePEc/lec/leecon/dp09-16.pdf).
Comment: This paper basically says "let's express excluded variables as a function of included variables... why? because _mathematically_ and in abstract, we can express anything as a function of anything else". Their crucial equation is $[3]$ for which they only provide the following argument: "assuming that the included variables are uncorrelated with the excluded variables would be meaningless" Why it would be meaningless? I wonder. In other words they assume without any convincing argument (mathematical, philosophical or whatever), what they want to prove. Sorry, but this is very bad science.
Comment: Equation (3) you are talking about is a generalized form of any regression model, taking into account the fact that some unobserved (excluded) variables have an influence on $y$. Excluded variables that are uncorrelated with the included ones would be caught up in the intercept and error term of a correctly-specified OLS model, so it is not a very interesting case. Not assuming that they are uncorrelated is another way of saying we stay in the general case (which allows uncorrelation as a special case). Φίλε, αυτό είναι πολύ καλή επιστήμη!


Let $P$ a polynomial with positive coefficients.Determine $\lim_{ x\to\infty }\frac{ \lfloor P(x) \rfloor}{P(\lfloor x \rfloor)}$

Question: this is my idea. By definition $p(x)-1\leq \left \lfloor p(x) \right \rfloor \leq p(x)$ and $x-1 \leq \left \lfloor x \right \rfloor \leq x$. As $p(x)$ is increasing and positive in $(0, \infty )$ then $\frac{1}{p(x)}\leq \frac{1}{p(\left \lfloor x \right \rfloor)}\leq \frac{1}{p(x-1)}$,this is $1-\frac{1}{p(x)}\leq \frac{\left \lfloor p(x) \right \rfloor}{p(\left \lfloor x \right \rfloor)}\leq \frac{p(x)}{p(x-1)}$. I want to prove that $\lim_{ x\to\infty  }\frac{ \lfloor P(x)  \rfloor}{P(\left \lfloor x \right \rfloor)}=1$. this is correct?. Help me please!!
Answer: Hint If nonconstant, the polynomials $p(x-1), p(x),$ and $p(x)-1$ all have the same leading term.
Comment: Well, there's $p=1$...
Comment: I mean, if they're constant, they also have.


poverty analysis and regression

Question: I have a dataset and I intend to use multiple linear regression analysis with excel since the dataset isn't that massive in volume, just about 500 rows. I have continuous numerical data and I already checked the scatterplots for linearity. Here are my questions:

I applied the model I came up with to the dataset to compare the actual and predicted values. How do I know the range of the acceptable errors?
How do I know if my model is already the best model?
Do I have to remove outliers?
How do I do the hypothesis testing for this?

Sorry, this is for my dissertation and I'm currently on break so I couldn't bother my statistics professor. Please just give me a walkthrough, I'm not sure where to start here.
Comment: you should try to ask only one question per thread
Comment: @Wes, the fact that this is for the OP's dissertation doesn't really make this `[self-study]`. That basically means homework from a course or an exercise from a textbook, or similar. In addition, we don't usually add the `[self-study]` tag for the OP, but ask them to add it for themselves & read its wiki (there are sample comments [here](http://meta.stats.stackexchange.com/a/2486/7290)). That way, it is more likely the OP will be familiar w/ out policies, & adding the tag can indicate that they intend to abide by them.
Comment: Apologies, still new to the system
Answer: One question per thread is best, but in short:

To get an overall impression or idea, you could plot the regression line with confidence interval?
Using forwards/backwards selection would potentially be a good way to construct the model and find out.
Do you observe any individual values which are so extreme as to influence the overall results? There are plots and tests for this.
Look into t.tests, Anova, chi-square and F-tests.

This is just an idea of what to consider and research, as answering all these questions in 1 reply would be quite an undertaking. Nothing mentioned above is exact/ exhaustive, but it should provide a platform for developing your approach to the analysis. Plus working it all out is part of the fun/idea of working on a piece of research.
Good luck with the dissertation :)
Comment: Re (2), forwards/backwards selection is *not* a good way to construct a model (see here: [Algorithms for automatic model selection](http://stats.stackexchange.com/a/20856/7290)).
Comment: Quite right, but the answer is intended as a place to start. I usually include variables based upon theory, and only remove if there are problems with collinearity etc. The most important thing is that some thought goes into how you arrive at your model.

poverty analysis and regression


How to show $R/(I+J)\cong (R/I)/(\overline{J})$

Question:
Let $R$ be a ring and $I, J$ be two ideals. Let $I + J := \{a + b: a \in I, b\in J\}$ be the smallest ideal of $R$ containing $I$ and $J$ and let $\overline{J}$ be the image of $J$ in $R/I$. Show that $$R/(I +J)\cong (R/I)/(\ \overline{J}\ ).$$

Pictorially,
\begin{align*}
R\xrightarrow []{\pi}  R/I \xrightarrow[]{\phi} R/(I+J)\\
r\mapsto r+I\mapsto r+(I+J)
\end{align*}
$\pi(J)=\overline{J}$. Now I checked that

$\phi$ is well-defined.
$\phi$ is a ring homomorphism.
$\phi$ is surjective.

If I can show that Ker $\phi=(\overline{J})$ then using first isomorphism theorem, I can conclude the result.
Ker$\phi=\{ r+I: r+(I+J)=I+J \}=\{r+I: r\in (I+J)\}$. Now I stuck what to do. I am unable to use that $I+J$ is the smallest ideal containing $I$ and $J$.
Comment: The first inclusion shouldn't be a problem i guess. For the second one: What does it mean for an element $r + I$ to be in the kernel? What does it tell you about any representative $r$? How can you write $r$?
Answer: $$\bigl\{r+I\mid r\in I+J\bigr\}\stackrel{\text{def}}{=}(I+J)/I$$
since $I\subset I+J$. There remains to apply the 3rd isomorphism theorem.


Pretest-Posttest Statistical Test - No Control Group

Question: I am writing a research proposal measuring the effects of a treatment on a population with a pretest and posttest as the dependent variable. What is the best statistical analysis to use for this data?
Comment: That depends on two factors. 1) What do you want to know? 2) How are the populations distributed, e.g., are they normally distributed or not?
Answer: The default test would be a paired-samples t-test (aka related-samples t-test or dependent-samples t-test).  This test assumes that you have a normal distribution of difference scores, though, so if that assumption is not met you might consider a Wilcoxon signed rank test.
Just one observation.  The most basic pretest/posttest design is confounded with time.  That is, if you only have one group that you pretest, then administer treatment to, then posttest, you can't determine whether the change is due to treatment or time (or things related to time).  For example - a university professor decides to implement a writing skills program in his class.  He tests students at the start of term, and again at the end of term.  If he sees a change, he can't know whether it's caused by a) his program b) other education the students are receiving at the same time, c) simple maturation of his students, or d) anything else time-related.
To avoid this problem, run a concurrent control group that doesn't receive treatment, with random assignment to the treatment/nontreatment variable.  This should allow you to determine the effect of time and related variables - allowing you to determine the portion of pretest/posttest change that is due to the actual treatment.  The analysis would then be a mixed 2-factor ANOVA (pre/post as a within subjects variable and experimental/control as a between subjects variable). (Or you could run an independent-samples t-test on the before/after differences.)
(For ethical or practical reasons it's not always possible to run such a control group - which is why the education literature and the psychotherapy literatures sometimes have simple pretest/posttest studies.  But I am skeptical of interpretations of such studies.)


IRC bot issue regarding channel retrieval

Question: I would like to keep this short and simple for everyone. I've been working on a personal project just to learn something small of creating a relatively basic IRC bot using pIRC Java API.
Things were looking relatively well however I'm having(and have been having for days) issues in regards to obtaining current channel and current channel users.
The bot will only really support a single channel per instance for now but I would like to be able to display all current users on the left side of my frame as shown below:

The light blue is where I would like to display the users and the dark blue is where I would like to display channel messages
In PIRC you ought to call listChannels() method first, which in turn calls onChannelInfo() after every server it reads it returns (String channel, int userCount, String topic).
The issue is that I want to filter my channels only by channel name, thus @Overriding the current onChannelInfo is not enough.
If anyone has used pIRCBot before and knows what's going on please do help. I've been working on this issue for days and spent countless hours going back and fourth, nothing seemed to work.. Nothing ever returned and thus never appended on my JTextArea..
TL;DR - I would like to display users in current channel in left side and messages in right side but am having alot of issues with retrieving channel users and information!
Thanks a million in advance.
ALSO, here's the API for anyone who would like to look at - http://www.jibble.org/javadocs/pircbot/
Comment: I meant "better" in terms of code quality (e.g. Findbugs or sonar reports) and software architecture best practises.
Comment: You might also have a look at http://code.google.com/p/pircbotx/ - a kind of fork of pircbot. In my opinion the code quality is better than the original pircbot code.
Comment: Very interesting post mschenk, haven't heard of pircbotx. This immediately caught my attention thought! http://prntscr.com/3zkzac

Thanks for posting
Comment: I also found out about it some days ago when browsing some irc related question here on SO, but it seems that the author of pircbotx had the same thoughts about the original pircbot code like myself.
Comment: I mean yea, the original Pircbot works well, just that you have to go around doing unnecessary things at times to get it to work, causing alot of redundant code. Will definitely check this one out, maybe build another one based on it
Comment: Yea. Once again, many thanks for sharing it. I'll most definitely use it for my next client
Answer: Well it's seems I've been able to fix the issue if anyone is connected.
For a start there was no need to call Pircbot.listChannels().
listChannels() automatically invokes onChannelInfo(String channel, int userCount, String topic) after each server is received.
However all that was needed is to getChannels() and then getUsers(), iterate through those users, get user.getNick() and save the String in a list, then iterate through the list and append the users.
Here is the method I used for it:
public void appendUsersConnectedToChannel(){
    List<String> users = new ArrayList<>();
    for(User i : Main.bot.getUsers(Main.bot.getChannel())){
        users.add(i.getNick());
    }
    for(String i : users){
        append(i + "\n");
    }
}

The question will obviously arise, "Why didn't you just directly append from i.getNick()? And my answer would have to be, I don't know. Whenever I tried to do that, it would never work and have no explanation for it.
Here is a more efficient way of writing(theoretically):
public void appendUsersConnectedToChannel(){
    for(User i : Main.bot.getUsers(Main.bot.getChannel())){
        append(i.getNick());
    }
}

Once again, this is using PircBot's API, which has been fairly fun to work with and would encourage anyone to try it, it's not flawless but it works very well!


Weird error "No plugins loaded for this entry: xarray_image" when using hvplot

Question: Here's the code how I use hvplot
from hvplot.sample_data import us_crime

columns = ['Burglary rate', 'Larceny-theft rate', 'Robbery rate', 'Violent Crime rate']

us_crime.plot.violin(y=columns, group_label='Type of crime', value_label='Rate per 100k', invert=True)

But get the following error, does anyone know what might be wrong ?
ValueError: No plugins loaded for this entry: xarray_image
A listing of installable plugins can be found at https://intake.readthedocs.io/en/latest/plugin-directory.html .

Answer: pip3 install intake-xarray (followed by a restart of Jupyter) solved this problem for me. No additional imports were required.
Answer: Works fine for me as long as I import hvplot.xarray first to install hvplot xarray support:


Where to specify Apache2 Virtual Hosts in CentOS

Question: I'm used to Ubuntu, where there is a special file for containing the virtual hosts.
But I'm getting the impression that in CentOS the virtual hosts are listed right in the main configuration file.
Can anyone confirm this?
EDIT - Tried this and it didn't work:
Added this to httpd.conf
<VirtualHost *:80>
       ServerName example.com
       ErrorLog /var/www/example_apache_errors.log
       DocumentRoot /var/www/html/example
       <Directory /var/www/html/example/>
               Options Indexes FollowSymLinks MultiViews
               AllowOverride All
               Order allow,deny
               allow from all
       </Directory>
</VirtualHost>

It did not work. The test page I created at /var/www/html/example/index.html is not showing up. Instead, the default page at /var/www/html/index.html is showing up.
EDIT: before anyone asks, yes, I'm restarting apache after ever config change.
EDIT:
NameVirtualHost *:80 is commented out by default in the config file and I didn't uncomment it. I believe that was the problem.
But I decided to use ip-based instead, like this:
<VirtualHost 69.175.xxx.xxx:80>
  ServerName example.com
  ServerAlias www.example.com

  DocumentRoot /var/www/example/

# etc. etc.

</VirtualHost>

And this is working. We have 5 ip's so hopefully I can use this method to assign others in the future.
Comment: You have "NameVirtualHost *:80" turned on?  And "sudo apachectl configtest" is returning OK?
Answer: You know that you can just stick something like:
Include conf.d/*.conf
Include sites-enabled/*.conf

into /etc/httpd/conf/httpd.conf, run "mkdir -p /etc/httpd/sites-enabled /etc/httpd/sites-available" and get something similar to the Ubuntu directory structure for Apache, right?
Update (from information in comments):
You should verify that NameVirtualHosts for port 80 is turned on, also.
Comment: Yes, I know that now that you've told me and I will certainly try that if nothing else works. But what is standard practice on CentOS? I would rather not be too creative on the server config. I just want to do things the way they're usually done on CentOS if possible.
Comment: On my CentOS 5 box, I did an include of a virthosts.conf file which contained all my virtual hosts.  On my CentOS 6, I'm following Ubuntu conventions, after a couple years exposure to how Ubuntu does things.  I think as long as you document your changes and aren't insane about directory layout, it should be OK. I think it's much worse putting everything in the main httpd.conf file, for whatever my opinion matters.
Comment: A separate file does seem more elegant. I will try that, but since I can't even get it to work inside the file I'm wondering if something else is wrong.
Comment: NameVirtualHost was commented out in the config file, so I think your comment was right on.  Although, I did not test it because I ended up using ip-based VirtualHost instead. Your answer is good but I think you should add something about NameVirtualHost *:80 to it so I can give you the check mark. Thanks!
Comment: Updated with your suggestion.
Comment: Ok, check mark for you and gave you a +1. Thanks also for your answer on my other question although not sure if I want to go that route.
Answer: Since Centos has the Include conf.d/*.conf I place my configs there. However I typically have a conf.d/00_NameVirtualHost.conf with NameVirtualHost *:80. Im guessing you don't have that set in your apache config.


Is every finite ring a matrix algebra over a commutative ring?

Question: In this MO answer it is stated that every finite ring is a direct sum of finite-dimensional algebras over $\mathbb{Z}/p^k$ for varying $p$ and $k.$ What I am wondering is the following:

Can every finite ring $R$ be written as a subring of $\text{Mat}_{n\times n}A$ for some commutative ring $A$?
If not, then what is/are the smallest ring(s) that cannot be?

Sorry if this question is trivial for some reason (something like the regular representation or permuation representation?), or if I should have asked a question about algebras, or ideals, or modules, instead.
Comment: Duplicate, but the original doesn't contain a solution: http://math.stackexchange.com/questions/454097/presentation-of-finite-rings-fields
Comment: Since there is no indication the other question has "commutative" where this one does, it's not quite a duplicate.
Comment: Well, if you don't stick "commutative" in there then it's not very interesting. I'm willing to give the OP the benefit of the doubt.
Answer: Apparently the answer is no, and the smallest counterexample has order $2^5 = 32$. I suspect it is $\text{End}(\mathbb{Z}_2 \oplus \mathbb{Z}_4)$, but don't quote me on that. (By looking at the action of a finite ring on itself by left multiplication you can reduce the question to endomorphism rings of finite abelian groups, and by looking at each prime separately you can reduce the question to endomorphism rings of finite abelian $p$-groups. That ring above is the simplest such ring which isn't already a matrix ring.)


How to force include a field into AuthComponent's user?

Question: I have a role field for my users that I really need to access. If a user is an admin, they would have extra available actions on many of my views.
So, in the beforeRender of my AppController I do this:
$this->set('loggedInUser', $this->Auth->user());

This way, I can use $loggedInUser to access the logged in user in all of my views.
The thing is that from the 10 fields that the table users has, the AuthComponent seems to fetch only these 4: id, username, verified and modified.
I cannot find anywhere in my code specifying those 4 fields as a whole.
What is causing AuthComponent to select randomly those specific fields? How can I force the fields I need?
Extra information in case it is needed:
All the fields of the users table are:
id
username
email
password
role
verification_hash
email_md5
verified
created
modified

The initialization of AuthComponent inside my AppController is the following:
$this->loadComponent(
    'Auth',
    [
        'authorize' => 'Controller',
        'authError' => 'You are not allowed to go there',
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'username',
                    'email' => 'email',
                    'password' => 'password'
                ]
            ]
        ],
        'loginAction' => [
            'controller' => 'Pages',
            'action' => 'display',
            'home'
        ]
    ]
);

Comment: That is not correct, by default AuthComponent will fetch all fields. Also, in the `fields` key of your configuration the `email` key is not required.
Comment: @JoséLorenzo, thanks, do you know what causes AuthComponent to fetch only those specific fields?
Comment: Do you have anything in `$_hiddenFields` in your entity?
Comment: The `User` entity contains the `$_accessible` variable and the `_setPassword` function for password hashing.
Comment: how did you implement the login function?
Answer: The problem was with the accessible fields in my entity. I had left there some non-existent fields that I had forgotten to remove.
For some reason it seems that the AuthComponent did not like those non-existent fields and it fetched only 4 fields.
Removing from the accessible fields the ones that did not exist seems to fix the problem.


signal.alarm() handler causing problem with pyserial

Question: so i have a motion sensor connected to an avr micro that is communicating with my python app via usb. im using pyserial to do the comm. during my script i have an infinate loop checking for data from the avr micro. before this loop i start a timer with signal.alarm() that will call a function to end a subprocess. when this alarm goes it interrupts the pyserial comm and the program exits completly. i get the error that pyserial read() is interrupted. is there any way around this issue. any help would be awesome
Answer: The problem is that your alarm will interrupt the read from the serial port, which isn't at all what you want.
It sounds like you probably want to break this into two threads that do work separately.
Comment: No, it's normal to interrupt system calls with signals; it's up to the application or library to retry the call or otherwise handle it sanely.  Failing entirely on EINTR is a bug.
Comment: thats what im trying now. i have the read() function on a child process and now im running into issues with the child and parent communicatin. this is just from my lack of knowledge of python.
Comment: so i learned what pipes are and my problem is solved. thanx everyone who replied
Answer: You are using alarm(), which send a signal, and pyserial, which does reads and writes to a serial port. When you are reading or writing to a device like that, and the SIGALRM signal is received, a read() or a write() call is interrupted so the signal can be handled.
As signals are handled in userspace, and reading and writing is actually handled by the kernel, this makes things rather ugly. This is a know wart of the way signals are handled, and dates back to the very early UNIX days.
Code that handles signals correctly in python may look like:
import errno
while True:
    try:
        data = read_operation()
    except OSError, e:
        if getattr(e, 'errno', errno.EINTR):
            continue
        raise
    else:
        break

Comment: so ive tried to impliment the error handleing and from debugging im seeing that the error is not being caught and the script still exits. also im very new to using forums, how would i post my code like you did above
Comment: To paste code how I did, just paste it into the edit box, then click the 1010 button. It will indent everything by 4 spaces and make it look pretty.


Setting up tomcat autostart on Linux?

Question: So I have a java web app on tomcat installed on the server. How can I setup auto start for it so that it starts up automatically when the server is restarted?
Answer: /etc/init.d/tomcat-wepappname
#!/bin/sh
### BEGIN INIT INFO
# Provides:          tomcat-wepappname
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: foo bar
# Description:       long desc
### END INIT INFO
# Author: Foo Bar <firstname.lastname@example.com>

. /lib/lsb/init-functions

# Actions
case "$1" in
 start)
  log_action_begin_msg "Starting tomcat webapp" "tomcat-webappname"
  su - tomcat-webappuser -c "/home/sites/tomcat-webappname/webappname.sh $1"
  log_end_msg 0
  ;;
 stop)
  su - tomcat-webappuser -c "/home/sites/tomcat-webappname/webappname.sh $1"
  ;;
# restart)
# something else...
#  ;;
esac

exit 0

At least, register the service:
update-rc.d activemq defaults

Comment: i guess it should be : update-rc.d tomcat-wepappname defaults
Answer: Use
/sbin/chkconfig tomcat6 on

If you have installed the tomcat6 RPM.
Comment: No man I'm using SUSE Enterprise Linux 9 here
Answer: Found this article here that did it for me.
http://www.sitepoint.com/jsp-quick-start-guide-linux/
Comment: broken link....
Comment: Link updated...
Answer: One way to start the tomcat on the startup is to run it using cron using the @reboot attribute:
open up a terminal and type :
sudo crontab -e

at the end of the file enter the command:
@reboot /`PATH_TO_WHERE_TOMCAT_INSTALLED`/bin/startup.sh

save the file and exit.
The above command will run the command once everytime computer boots up.

Setting up tomcat autostart on Linux?


PhpStorm Re-commit and push after accidental commit

Question: With PhpStorm I know that if you hit Ctrl+K and click commit, the IDE does only a local commit and the changes are not showed on GitHub.
If I accidentally committed, but actually wanted to commit and push to GitHub how do I go back and do that from my local commit?
Also is there no way to default a commit and push, the tiny drop-down icon is easy to miss click?
Comment: *"Also is there no way to default a commit and push, the tiny drop-down icon is easy to miss click?"* You may have them as separate buttons -- `Settings/Preferences | Appearance & Behavior | Appearance --> Allow merging buttons on dialogs`. Alternatively just use keyboard shortcut for that specific action.
Answer: You can do it by using Ctrl+Shift+K.  This will open up the Push menu.
You can find this by going to the VCS menu, going to the Git section and looking at the options in there.


Apache mod_proxy_balancer health checking

Question: I have 3 Apache web servers set up behind another Apache server running mod_proxy_balancer.
During today, one of the web servers got rebooted. It took about 16 minutes to reboot.
During that time, I can see the following log line every 30 seconds in the error log on my Apache mod_proxy_balancer server
<code>[Tue Sep 30 07:04:42 2014] [error] ap_proxy_connect_backend disabling worker for (s1-sc1-c-use)
</code>
This is logged 32 times during the 16 minute outage
I am trying to figure out what is going on here. My concern is that due to deficiencies in my balancer config, that the balancer is repeatedly trying to send requests to the rebooting server (and therefore returning errors to the user).
Why is Apache repeatedly telling me that it is "disabling worker"? Does the balancer module intermittently send user requests to the failing node, to try and determine if it is back up, or does it have its own internal health checking mechanism that is invisible to the user?
Answer: OK. I can explain this.
Apache mod_proxy_balancer doesn't have its own independent healthcheck mechanism. The state of Balancer Members (workers) is determined based on outcome of actual forwarded users requests.
Sequence is as follows:

Apache httpd sends request to worker
Worker doesn't respond, or responds with HTTP status which triggers failover,and puts member into ERR state
Apache httpd starts retry timer (default 60 secs) and doesn't send any more requests until retry timer expires
When retry timer expires, go back to Step 1 in sequence

My retry value is 60 secs (default).
The reason I am seeing multiple log entries is that my Apache httpd Balancer is configured with multiple balancers, each with its own independent retry timer.
As such, depending on application activity, the retry timers are being reset arbitrarily, and being tested arbitrarily, which explains the non-uniform distribution of worker status updates in the log.


A bijection from the plane to itself that takes a circle to a circle must take a straight line to a straight line.

Question: Let $ f: \mathbb{R}^{2} \rightarrow \mathbb{R}^{2} $ be a bijective function. If the image of any circle under $ f $ is a circle, prove that the image of any straight line under $ f $ is a straight line.
Comment: Where is this problem from?
Comment: This problem was a question some of my classmates and I discussed over tea-time. We have regular discussions like this. Have you seen it somewhere before?
Comment: Mostly I'm wondering if you happen to know for a fact that this is true (e.g. because it was stated in a book of problems somewhere) or just believe it to be true.
Comment: I'm not sure if this was obtained from a book. However, someone in my group mentioned that this was a folklore result and that he had seen a proof of it in some article. None of the rest of us could find a proof ourselves, and that fellow had trouble remembering the article where he had seen the proof.
Answer: This has the result (second page).  I hope it's thorough enough to placate your curiosity...
Comment: Thanks! You've provided a very nice pancake indeed.


manipulating lists in common lisp

Question: how does one create a list from a list,what function can i really use i was thinking of using mapcar or maplist with cons together but im not getting any fruitful results,lets say i have a  list (a b)  then i want a function that will create a list containing the same elements but they should be inform of lists like this  ((a) (b)) ,any ideas on how i can solve this problem?? is there a function a use to it?
if i have a list(a b)
the result should be ((a)(b))

thanks guys
Comment: I don't speak lisp, but you should be able to do something like `map (lambda x: cons(x,nil))`. Hope that's understandable...
Comment: this sounds like another fake question from a bunch of fake stackoverflow accounts. All have extremely poor spelling, wrong Lisp syntax, show no own effort and ask trivial questions.
Comment: @RainerJoswig "fake question"? What have I missed?
Comment: @RainerJoswig how is it fake???the syntax is not the lisp syntax its just an example on how i want it to look like,just trying to learn here i will appreciate if you just help me  out if you have ideas thanks
Comment: @fableal thanks for the contribution :)
Comment: @wvxvw: this is a similar question by another user just an hour earlier: http://stackoverflow.com/questions/13442008/repeating-elements-in-common-lisp. Same spelling mistakes, same formatting mistakes, no effort put into it, ...
Answer: What you want to do is this:
(defun listify(ls)
    (mapcar (lambda (elem) (list elem))  ls))

EDIT
Which is the same as (Thanks to @RainerJoswig):
(defun listify(ls)
    (mapcar #'list ls))

And if you do:
(listify (list 1 2 3))

or
(listify '(1 2 3))

The output will be:
((1) (2) (3))

Comment: (lambda (elem) (list elem)) is just #'list
Comment: No need for the down vote. Jeez.
Comment: The syntax is `#'list`, not `'#list`.
Comment: @Xach my bad, fixed :P. Lousy copy-past skills.

manipulating lists in common lisp


$a^3+b^3+2(a^2+b^2)=b^3+c^3+2(b^2+c^2)=c^3+a^3+2(c^2+a^2), a\not=b\not=c$; what is $ab+bc+ca$

Question:
$a^3+b^3+2(a^2+b^2)=b^3+c^3+2(b^2+c^2)=c^3+a^3+2(c^2+a^2) \\ a\not=b\not=c \\ ab+bc+ca=$

since $a^3+b^3+2(a^2+b^2)=b^3+c^3+2(b^2+c^2)$
$a^3+c^3=-2(a+c)(a-c)=(a-c)(a^2-ac+c^2)$
$-2a-2c=a^2-ac+c^2$
$a^2+c^2+2a+2c=ac$
isw, $ab+bc+ca=2(a^2+b^2+c^2)+4(a+b+c)$
Comment: there is a mistake in the line "since ..". It should be $a^3 - c^3$ and it is equal to $(a-c)(a^2 + ac + c^2)$
Answer: Bigbang pointed out a typo. It's not immediately clear to me how the solution can be continued from there.

Hint: Show that $ a, b, c$ are the distinct roots of $ x^3 + 2x^2 + k  = 0 $ for some $k$.
Hence, conclude that $ ab+bc+ca = 0 $.
Comment: Oh.. When $a^3+b^3+2(a^2+b^2)=b^3+c^3+2(b^2+c^2)=c^3+a^3+2(c^2+a^2)=k$, $2(a^3+ b^3+c^3)+4(a^2+b^2+c^2)=2k$, $(a^3+ b^3+c^3)+2(a^2+b^2+c^2)=k$. but I'm not sure that $a^3+2a^2=k$ and $b^3+2b^2=k$ and $c^3+2c^2=k$.
Comment: @Phoenixrafaelthemusicmake You have the idea. Some of your $k$'s are different, so you should keep proper track of that instead of the abuse of notation that you're using (which likely makes you not sure of the rest). Show that $ a^3 + a^2 = (a^3 + b^3 + c^3) + 2 ( a^2 + b^2 + c^2 ) - [ b^3 + c^3 + 2 ( b^2 + c^2) ] = k_1 - k_2 = K.$
Answer: Well there is a typo mistake. It should be $a^3-c^3$

 Then factorise the LHS and obtain $(a-c)(a^2+ac+c^2)$ and try to move on from there
Comment: To check, are you able to move on from there?


Hide Mat Sidebar and Mat Tool bar on specific components

Question: I have a simple log-in component just like the pic below:

I have a mat-sidenav component to navigate through components. This is an example of my mat-sidenav:
<mat-toolbar class="mat-elevation-z8">
<button mat-icon-button *ngIf="sidenav.mode === 'over'" (click)="sidenav.toggle()">
    <mat-icon *ngIf="!sidenav.opened">
        menu
    </mat-icon>
    <mat-icon *ngIf="sidenav.opened">
        close
    </mat-icon>
</button>

</mat-toolbar>

<mat-sidenav-container>
<mat-sidenav #sidenav="matSidenav" class="mat-elevation-z8">

Juan Perez

Chef

    <mat-divider></mat-divider>

        <mat-icon>person</mat-icon>
        Pacientes

                Formulario Pacientes

                Ingreso Pacientes

                Ingresos Diarios

    <mat-divider></mat-divider>

    <button mat-button class="menu-button">
        <mat-icon>help</mat-icon>
        Help
    </button>

</mat-sidenav>
<mat-sidenav-content>

        <router-outlet></router-outlet>

</mat-sidenav-content>

What I'm trying to achieve is to hide the sidenav and the toolbar when I'm in the login component.  Placing app-sidenav on app.component.html shows the login with both bars (I assume it's because I have the router-outlet inside the mat-sidenav-content) but I don't know another way to achieve this. I actually have 2 components (login and other one) where I need them hidden...I'm trying to think a better way but I don't find any solution :(.
Thanks !!
Comment: Does this answer your question? [How to hide the Angular Material Sidenav when a user clicks a link](https://stackoverflow.com/questions/61089304/how-to-hide-the-angular-material-sidenav-when-a-user-clicks-a-link)
Answer: So i know this amswer might change your folders structure, but i believe this would be better and lowers the overhead, and it's the other way you're looking for i guess.
I suggest to place all login, sign up, forgot password, etc.. components in a seperated module, call it AuthModule.
And make a shared module for app-header, app-sidenav, app-footer components, call it SharedModule.
(You can organize this even more by creating a component for each sidenav anochor tag or a link)
Now make a module name it HomeModule, create your components, and just call the 3 tags you made in the SharedModule in all required pages.
Here are couple of basic snapshots.
Folders Structure
Usage of Shared Components
Hope this helped.
Comment: Thanks man, I've tried this and it worked. I had to change the router-outlet for ng-content and place the sidenav where I need it. Now, I want to disable the sidenav animation because every time a click a nav, the sidenav shows its animation and looks 'weird'.
Comment: I'm not sure what kind of animation looks weird when clicking a nav item, but here's a working demo for disabling sidenav animation.

https://stackblitz.com/edit/angular-6enqwb-yxaggq?file=src%2Fapp%2Fsidenav-autosize-example.ts


does anybody make a tin whistle with the same fingering as a recorder?

Question: I play the recorder, but the other day I heard someone playing a tin whistle, and was like WOW!  After getting a cheap tin whistle it's apparent that the fingering is different.  Does anyone make a good tin whistle that has recorder fingering?
I already play sax and flute and keyboard, and having to learn another set of fingerings may cause me to break out in hives!
Answer: It would be possible to design a whistle with recorder fingerings that would work at least for the first two octaves, maybe even for the third. It would be necessary to lengthen the tube and add an extra hole for the RH 4th finger, and add a hole for the LH thumb. Obviously there is no demand for such an instrument because as far as I know no instrument maker builds one. Of course it's possible that recorder players might have had whistles custom made for them.
The opposite, a recorder with whistle fingerings, is commercially available.
Another answer here states that a whistle with recorder fingerings would be a recorder. This is not the case. There are important differences between a whistle and a recorder. The main factors affecting the differences in sound are:

Bore design.
Whistles are normally cylindrical, recorders are reverse conical. A typical alto recorder has a bore of about 17mm at the top of the main joint to 10mm at the foot. There is more variation in whistle bores, but 17mm is about average for a low G whistle (which would correspond to an alto recorder). This gives the recorder a much 'sweeter' sound, and it's the reason a whistle will never sound the same as a recorder. There are some whistles (Shaw) with a conical bore, but they have a very different fipple design and sound very 'breathy'.
Fipple design.
There is a lot of variation in the fipples of whistles. Some are quite close to the recorder design, and these whistles tend get closer to the recorder sound.
Tube material.
Recorders are made of wood (or plastic). Whistles are usually made of various metals. Whistles made of wood or plastic also get closer the the recorder sound.
Finger hole size
Whistles generally have larger finger holes than recorders which gives them a louder, brighter sound. The disadvantage is that it's harder or impossible to cross-finger for chromatic notes. Some whistles do have smaller holes which make them a sound slightly more recorder-like, but allows for good cross-fingerings.
Answer: The thing is, recorder fingering is not the same as Boehm flute or saxophone anyway, so you're faced with learning new fingerings whichever route you go down.
My advice would be to just do it though, it's not going to be as bad as you think; I play several wind instruments each with slightly different fingerings, and the change between each system quickly becomes automatic depending on which instrument you're holding at that moment.
Or, if you really can't face learning tin whistle fingering, why not get a Boehm piccolo?
Answer: No, if you built a tin whistle with Recorder fingering, you would have a Recorder. The tin whistles are tuned in specific keys, and lack a thumb hole. The closest fingering Tin whistle you could get is probably one in the Key of D.
Comment: But how would such a "tin recorder" sound?
Comment: I believe it is the fipple style that adds the breathy-ness to the tin whistle, not the body material.  The tin whistle also has a steeper conical bore than the recorder, which may also affect tone, though I'm not sure about that.  I was thinking about it, and it may be possible to create a Recorder head that has the Tin Whistle fipple.
Comment: In which case,  we eagerly await your design at thingiverse.com  :-)


Como editar o gráfico de barras a seguir no R?

Question: Gostaria de entender como posso fazer as seguintes alterações no gráfico a seguir:

Alterar a escala do eixo Y e ocultá-la do gráfico caso queira
Colocar os valores em cima de cada barra
Colocar os meses do eixo X na ordem crescente (junho... julho..) e colocar em negrito a escrita

Estou utilizando o seguinte script:
<code>library(ggplot2)
library(tidyr)

TCH <- data.frame(Período =c("Jun", "Jul"),
                         CV6654 = c(9.38, 26.14), CTC9002 = c(16.27, 47.71))

df <- gather(TCH, "Variedades", "Valor", -Período)

ggplot(df, aes(x = factor(Período), y = Valor, fill = Variedades)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_manual(values = c("1", "3")) +
  labs(x = "Período", y = "")
</code>
Comment: 1) Alterar para quê? 2) veja `geom_text` ou `geom_label`; 3) `x = factor(Período, levels = c("Jun", "Jul"))`.
Comment: Olá Patrick, bem vindo ao SOpt. Algumas dicas para ter sua pergunta respondida satisfatoriamente: 1) Seja específico quanto ao resultado que busca. Quer alterar a escala do eixo como? Para escala logarítmica? Fração? Porcentagem? Sem especificar, conseguirá no máximo uma resposta genérica. 2) Divida suas dúvidas em várias postagens. Idealmente, cada questão deve se referir a um único problema. Isso auxilia outros usuários quando buscarem solução e auxilia você a delimitar as etapas do seu código. Inclusive, se buscar pelas etapas separadas, encontrará no site respostas que talvez te ajudem.
Answer: <code> ggplot(df, aes(x = factor(Período), y = Valor, fill = Variedades)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_manual(values = c("1", "3")) +
  geom_text(aes(y = Valor, label = Valor), vjust = -0.2, # COLOCAR VALORES EM CIMA DAS BARRAS
            position = position_dodge(width = 1)) +
  labs(x = "Período", y = "") +
  theme(axis.text.y = element_blank(), axis.ticks = element_blank(), # APAGAR EIXO Y
        axis.text.x = element_text(face="bold")) + # ROTULO EIXO X EM NEGRITO
  scale_x_discrete(breaks=c("6", "7"),
                   labels=c("Junho", "Julho")) # REORDENANDO COLUNAS
</code>


static library from Fortran Modules

Question: I am not a very expert Fortran programmer, but now that I have written many subroutines (in Fortran 90), I have to put them in Modules (employed by "use" statement in other subroutines and program) to avoid writing the interfaces. I have to use these modules with old code written in F77.
I don't want the compiler to compile these modules again and again. So I created a static library from the ".o" files after compiling these modules:
ar rc libmymath.a module1.o module2.o module3.o
However I still need to keep the ".mod" files of these modules to be able to "use" them in my code.
My question: is it possible to pack these ".mod" files in the static library archive ".a" (as we did with .o files), so that everything is encapsulated in the single file static library?
P.S: by anywhere I mean across my systems, all of them use gfortran 64 bit.
Answer: No, it is not possible.
In an analogue to C/C++, a .mod file is like a header file. It describes the contents of the module and the USE <module> is similar to the #include .
These mod files are compiler (and often even version) specific and are required because modules name-mangle the functions and so there needs to be a lookup table for the resulting function names.
Comment: How you handle them depends on your build system really. We use CMake and have it install all the mod files into an include directory, just like you would header files. So our codes install into a `/bin`, `/lib` and `/include` directory structure. But otherwise, it's just like handling a bunch of header files and organization is up to you, and how you implement the organization depends on your build system.
Comment: Unfortunately, `.mod` files are not compatible with other compilers typically. In fact, they often aren't even compatible with different versions of the same compiler. The analogy to header files falls apart when you need to look at multiple compilers. Because the way compilers name-mangle isn't part of the Fortran standard, the format for `.mod` files is also not standardized. In fact, gfortran mod files are plain text while ifort (Intel) mod files are in binary.
Comment: Thank you very much. This analogy is very helpful in understanding the way '.mod' files are used in Fortran.
Comment: Is there any easy way to handle these '.mod' files?
I have many modules, and each module contains many functions and subroutines for specific calculations.
So it is not desirable to reduce number of modules by increasing number of subroutines/functions per module.
Comment: Now I have another problem ! I have built the library from modules compiled by `gfortran`. I sent these libraries to a colleague who has AMD's Open64 (OpenF90) compiler. So when he tried to used this static library with his code, using OpenF90, he got error about missing `.mod` files (Open64 uses upper case alphabets for naming `.mod` files). Is there any method to tell Open64 that these `.mod` files have names written in lower case alphabets?
Answer: You just copy those .mod files to your fortran finclude directory.
e.g I am using ubuntu with gcc -4.4.3. What i did is I have copied the library librandom.a to /usr/local/lib and the mod file random.mod to /usr/lib/gcc/i486-linux-gnu/finclude.
Now I don't have to create those mods again and again . I just have to use gfortran -o myfile myfile.f90 -lrandom to compile my program and link with the library. Of course i have to use "use random " in my myfile.f90.
Cheers
Answer: A simple way is to compile with
gfortran myprog.f90  -I/path/to/mod_files -L /path/to/lib -lmylib
where the module.mod are in the directory /path/to/mod_files. The module.o was generated by
gfortran -c /path/to/mod_files/module.f90
and the library mylib.a was generated  by
ar rcv /path/to/lib/mylib.a /path/to/mod_files/module.o
But you still have to keep the .mod files.
I had this same issue.
I hope I have helped.

static library from Fortran Modules