Calculating Age: Ambiguous reference to member on DateComponents

Question: I'm trying to come up with a code that calculates age from a datePicker allocated to a text field. I get the correct date just fine, it passed the print test. However, while trying to get dateComponents to work I get the "Ambiguous reference to member 'dateComponents(_:from:to:)'"error. -- This is not the same code as the one stackoverflow notified me of, I am trying to use datepicker to get there. --
I looked around for solutions online and I can't seem to get past this. Can you help please?
-Total Beginner
@objc func dateChanged(datePicker: UIDatePicker) {

    let myCalendar = Calendar(identifier: .gregorian)
    let dmy = myCalendar.dateComponents([.day, .month, .year], from: Date())

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"

    inputTextField.text = dateFormatter.string(from: datePicker.date)

    let birthdayDate = dateFormatter.string(from: datePicker.date)
    print(birthdayDate)

    let now = NSDate()
    let ageComponents = myCalendar.dateComponents(.year, from: birthdayDate, to: now) //Ambiguous reference to member 'dateComponents(_:from:to:)'
    let age = ageComponents.year!

    label.text = age

    view.endEditing(true)

}

Comment: Use `Date()`, not `NSDate()`
Comment: `label.text = age`  should be `label.text = String(age)`
Answer: You have a few issues in your code

You should use Date, not NSDate in Swift
birthdayDate is a String, but the from: parameter needs to be an instance of Date
The components parameter needs to be a set.

Correcting these gives you:
@objc func dateChanged(datePicker: UIDatePicker) {

    let birthdayDate = datePicker.date
    let myCalendar = Calendar(identifier: .gregorian)
    let dmy = myCalendar.dateComponents([.day, .month, .year], from: Date())

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"

    inputTextField.text = dateFormatter.string(from: birthdayDate)

    let now = Date()
    let ageComponents = myCalendar.dateComponents([.year], from: birthdayDate, to: now)
    let age = ageComponents.year!

    label.text = "\(age)"

    view.endEditing(true)

}

Comment: You can't assign an `Int` to a `String`.
Answer: Here:
let ageComponents = myCalendar.dateComponents(.year, from: birthdayDate, to: now)

You are directly passing .year to dateComponents, but it actually expects a Set<DateComponents>. Also, birthdayDate is a String, not a Date. You should pass datePicker.date instead. So you should do this:
let ageComponents = myCalendar.dateComponents([.year], from: datePicker.date, to: now)

Also, now should be a Date, not NSDate.
Comment: It is definitely better to use `Calendar` than multiply seconds, since that won't account for leap years or leap seconds. although the error probably isn't significant over a normal lifespan, it is a bad habit to get into.
Comment: Stackoverflow is awesome! I hadn't even think of leap years when I thought about that.


Inverted SPSS results: Logistic regression command vs. Genlin?

Question: I want to do a logistic regression in SPSS. However, since I analyse unemployment spells the subjects are sometimes repeated (violating the independence assumption of the regression). One way of removing the within subject variation is by applying a Genlin model with the repeated subject subcommand (in essence a GEE model). Thus, I tried out a Genlin model with binomal probability and the logit link, comparing it to a standard logistic regression. I used the exact same variables in the two procedures.
However, the results that was delivered from the Genlin procedure was inverted relative to that of the logistic regression. For instance: Exp(B) for women (of the independent variable sex/gender) was just above 2.0 in logistic regression while being at 0.49 in Genlin. The same happened with every independent variable.

Any suggestions to why the results of the Genlin procedure is
inverted?
Is there any way to get the Genlin results in accordance to the logistic regression?
Comment: Check **the other tables** of the outputs and look for the coding schemes. These two modules might have coded your sex variable differently; one might have used male as reference while the other one used female.
Comment: No, that is not it. I have been very careful to get the same reference for every variable in both logistic and Genlin. In every respect (since I have left out the repeated subcommand) the models should be the same.
Comment: It's the reference of the outcome that matters. How is this coded?
Answer: This is because the default for the reference category in GENLIN is FIRST. Try changing this to LAST.


O que é um literal?

Question: Nesse link do site da MSDN diz que um literal é:

Um literal é um valor que é expresso como si mesmo em vez de como um valor variável ou o resultado de uma expressão, como o número 3 ou a sequência "Alô".

Mesmo assim eu não entendi o que é um literal. No mesmo link tem um exemplo:
Option Strict On

Public Class Sample
    Public Const MyByte As Byte = 2
End Class

Agora minhas dúvidas são:

O que é um literal?
Para qual finalidade ele existe?
Onde tem um literal no exemplo acima?
Answer: No exemplo acima o literal é o 2.
O termo literal não é algo do .NET ou mesmo da computação, é um termo matemático básico.
Literal pode ser dito, grosso modo, já que está difícil entender, como um valor fixo.
Ele existe para determinar valores. O mais comum é que estes valores sejam números. Muitos desses números podem ter um sufixo indicado o seu tipo, ou podem ter prefixos indicando se a notação é diferente do decimal (hexadecimal, binário e octal são comuns). Outro literal bem comum é o que representa um texto, uma string ou mesmo apenas um caractere. true e false costumam ser literais do tipo booleano.
Algumas linguagens possuem outros literais. Algumas permitem até que se crie um literal, ainda que raro porque dá confusão.
O literal é sempre constante, mas uma constante não precisa ser representada por um literal. Muitas pessoas usam o termo constante inadequadamente para o literal. Apesar do literal ser constante ele pode ser atribuído para variáveis, o literal nunca mudará, mas o valor da variável poderá mudar.
Literal é exatamente como está colocado ali, não será manipulado, não cabe interpretação, não é algo representativo, é aquilo e só.
Coloquei no GitHub para referência futura.
Comment: Está escrito na resposta que não.
Comment: Um literal é constante. O que eu quis dizer é que você não declara uma constante por causa de um valor literal.
Comment: Eu: **"Resumindo, é a mesma coisa que uma constante?"** bigown diz: *"O literal é sempre constante"*, jbueno diz: *"Não. Constantes têm valores literais definidos e não podem ter valor mudado durante a execução."*
Comment: Editei o comentário.
Answer: Um literal é um valor que  é expresso literalmente no meio do seu código.
No seu exemplo, 2 é um literal.
Public Const MyByte As Byte = 2

No exemplo abaixo (em C#), meu texto é um literal
var algumaString = "meu texto";

Literais não são variáveis, nem constantes
Você pode definir um valor literal para uma variável
var texto = "meu texto";

para uma constante
const string Nome = "João";

ou, até mesmo, mostrar um literal numa MessageBox
MessageBox.Show("Meu literal");

Comment: Quase isso. Você define um valor literal para uma variável.
Comment: Resumindo, é a mesma coisa que uma **constante**?
Comment: Não. Constantes têm valores literais definidos e **não podem ter valor mudado durante a execução**. Você pode definir um literal para uma variável e mudar os valores depois.
Comment: Então os literais são variáveis? Literal é o valor que eu dou para o membro, e então durante a execução o literal vira uma variável?
Comment: Editei os exemplos @RZ-8121

O que é um literal?


Problema ao Exibir e Esconder Div com Jquery

Question: Tenho um código, onde quero exibir o resultado de uma soma sem recarregar a página. Como exemplo, já defini valores iniciais nos campos.
*Problema: Tenho um div com id resultado que tem um css para ocultá-la em estado inicial. Ao clicar no botão de calcular tem uma função para exibir a div.
Existe outra função que vai pegar os valores dos campos input e exibir o resultado dentro da div com id normal. Esta div está dentro da div com id resultado.
Porém não sei porque a div com id resultado não está sendo exibida. Somente a div com id normal com o resultado. Se eu remover a função que faz a soma e clicar no botão a div com id resultado é exibida normalmente.
O código pode ser visto clicando aqui.
Answer: Não notei no seu código nenhuma instrução para habilitar novamente o display da div resultado.
Fiz uma pequena modificação e agora seu código está funcionando.
PS: Evite usar a propriedade onclick das tags, use addEventListener ao invés.

document.getElementById("calcular").addEventListener("click", function() {
  var a = document.getElementById('a').value;
  var b = document.getElementById('b').value;
  document.getElementById("normal").innerHTML = (a / b);
  document.getElementById("resultado").style.display = "block";
});
.principal-i {
  width: 600px;
  height: 135px;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 10px;
  background: #ff7f27;
  border-radius: 5px;
  font-family: 'Open Sans', sans-serif;
}
.calcule {
  font-size: 15px;
  text-transform: uppercase;
  color: #FFFFFF;
  text-align: center;
  font-weight: 600;
  margin-bottom: 20px
}
.col-md-34 {
  width: 28%;
  height: auto;
  float: left;
  margin-left: 7%;
  margin-right: 3%;
}
.col-md-34-2 {
  width: 28%;
  height: auto;
  float: left;
  margin-left: 2%;
  margin-right: 2%;
}
.col-md-30 {
  width: 20%;
  height: auto;
  float: left;
  margin-left: 3%;
  margin-right: 7%;
}
input.campo-i {
  width: 100%;
  height: 55px;
  border-radius: 4px;
  border: 1px solid #ccc;
  background: #fff;
}
.botao-calcular {
  background: #20a648;
  color: #ffffff;
  padding: 20px 20px;
  width: 100%;
  height: auto;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  font-weight: bold;
  text-transform: uppercase;
  cursor: pointer;
}
.botao-calcular:hover {
  background: #1b923f;
}
#resultado {
  display: none;
}
.resultado {
  margin-top: 20px;
  width: 600px;
  height: auto;
}
.resultado-exibido {
  width: 100%;
  height: auto;
  border-radius: 15px;
  background: #ebebeb;
  padding: 15px;
  font-family: 'Open Sans', sans-serif;
  font-weight: 300;
}
.titulo-i {
  color: #7f7f7f;
  text-align: center;
}
.i-centro {
  width: 49%;
  float: left;
}
.text-align-left {
  text-align: left;
}
.text-align-right {
  text-align: right;
}
.resultado-valor {
  font-size: 30px;
  color: #009b36;
  font-weight: 700;
}

Divisão de A por B

    <input type="text" name="a" id="a" class="campo-i" placeholder="A" value="50">

    <input type="text" name="b" id="b" class="campo-i" placeholder="B" value="10" />

    <button type="submit" id="calcular" class="botao-calcular">Dividir</button>

RESULTADO

Espero ter ajudado.
Answer: Olha você esta substituindo todo conteúdo da div pelo resultado. Por isso não mostra:
document.getElementById("normal").innerHTML = (a / b);

Tudo dentro da div normal é substituído pelo valor. Então o titulo é excluído.
Comment: não está funcionando normalmente, se olhar a `div` principal com `id` `resultado` tem dentro dele um título, o mesmo não é exibido devida a `div` principal não estar sendo exibida.
Comment: Boa tentativa, mas respostas como esse é melhor não dar, certo?
Comment: olha vc ta substituindo todo conteudo da div pelo resultado. por isso nao mostra

document.getElementById("normal").innerHTML = (a / b);

Tudo dentro da div normal é substituido pelo valor. entao o titulo é excluido
Comment: testa isso http://codepen.io/anon/pen/bZXZgZ


Piano learning books: history

Question: Learning piano, I learnt, changed over time. There are classical books like Hanon, Beyer, and Czerny, and modern ones which I don't know (I am half-way with Beyer's).
What are the major differences in "modern" vs "old" learning techniques from a student's point of view?
Note that I am not primarily interested in the positional vs non-positional debate, I'd like to know if there are deeper and fundamental differences between two students, old and new ones.
Answer: The obvious difference is that any book can only teach you techniques for playing the music up to the date when it was written. For example Czerny and Beyer died about 150 years ago, so you won't find anything about 20th/21st century playing techniques, or 20th/21st century popular music.
A good modern book will probably have exercises and pieces from wider range of musical genres. Even for "classical" music, compare Czerny and Beyer with Bartok's "Mikrocosmos" - which isn't "contemporary music" now, but it's very different from anything in Czerny or Beyer.
As well as the musical content, keyboard playing technique has developed a lot since Czerny and Beyer's time. These illustrations from http://imslp.org/wiki/Vorschule_im_Klavierspiel,Op.101(Beyer,_Ferdinand), don't really show "piano technique" at all - that is harpsichord technique. Trying to play modern piano music that way is at best not very effective and will severely limit your progress, and at worst will cause long term strain injuries. (IMHO Hanon's book of exercises should be banned, on health grounds!)
Comment: This is intriguing. I have modern Beyer (not of course the original) and techniques like those are not present. How come it is still widely used in some European countries?

Piano learning books: history


Response comes after 6 min while creating user using services module of Drupal 7?

Question: I have a client side application developed in angularJS. As i am sending POST request to Drupal to create user, user is getting created without any delay if i check in Backend. But i get response after 6minutes!. The request just goes on and on!! Any advice what i am doing wrong?
Answer: It's unlikely that your site needs 6 minutes of CPU time to create a user but you can confirm that checking the system load during the process.
When I've faced that kind of problems the reason was one or more timeouts when trying to connect to an external service from the server.
For example, imagine that when you create the user the site querys an external database via an HTTP connection checking for the user usual nickname (Abigail → Abbie, Peter → Pete, etc). If that external service is down your site happily will launch the connection, waiting patiently the answer until the timeout is reached and connection is closed. If your site tries to connect six times and system timeut is 30 seconds then there you have your six minutes for use creation.
Check your installation for modules that may conenct to external services, check dblog for timeouts errors messages, check system log for similar messages. Disable any suspicious module and try to create a user.
If this only happens when using Services (not in the regular user creation form) narrow your search to any Services related modules or custom code.
Comment: My user is getting created instantaneously in Drupal but response comes after 6 minute
Comment: Exactly, check any after user creation process and specially if external connections are done. I dind't mention, but your best options is to debug the process using XDebug.


How to set content-security-policy header?

Question: I want to set Content-Security-Policy header in my site.
I found a module to set CSP (I have not tried it yet). But I want to know is there any option available in drupal 8 core itself to set CSP.
Comment: i set it in nginx config since it has nothing to do with drupal itself. but you could simply alter the page headers via hook_attachments(i think) and add a new header.
Comment: There might be. There is stuff for CORS (https://www.drupal.org/node/2715637). I am actually working on this stuff right now.
Answer: I may be a bit biased in thinking that the Content Security Policy module is the best solution for adding a policy to your site, but here are some of the reasons for using the module:

Integration with the Libraries API to automatically generate script and style directives
An admin interface that validates your policy configuration
Provides a reporting endpoint to receive policy violations and add them to your site log, so you don't need to use an external service like Report-URI.com (but it also provides a plugin to use it, if you do).
The Reporting API module is still in beta, but it will have improvements over CSP's reporting handler, and has a plugin to integrate with CSP module.
Some optimizations to shorten your policy where possible (e.g. If a fetch directive like img-src that falls back to default-src has the same value, it is omitted)
In the future modules will be able to integrate with CSP module to alter the policy as needed (enabling additional directives, altering the policy per-page)

There are a couple alternatives to the CSP module, if you don't want all of these additional features:

The Security Kit module allows adding a CSP policy header, but it only allows either an enforced or report-only policy, and it does not have fields for many newer directives.
The HTTP Response Headers module allows you to configure a static value for any HTTP header you want
Set a static header in your own response event subscriber in a custom module.
You can set the header directly in Apache or nginx configuration


How to find which sentences have the most words in common?

Question: Let us say i have a paragraph. I separate this into sentences by sent_tokenize:
variable = ['By the 1870s the scientific community and much of the general public had accepted evolution as a fact.',
    'However, many favoured competing explanations and it was not until the emergence of the modern evolutionary synthesis from the 1930s to the 1950s that a broad consensus developed in which natural selection was the basic mechanism of evolution.',
    'Darwin published his theory of evolution with compelling evidence in his 1859 book On the Origin of Species, overcoming scientific rejection of earlier concepts of transmutation of species.']

Now i split each sentence into words and append it to some variable. How can i find the two group of sentences which has the most number of same words. I am not sure how to do this.
If i have 10 sentences, then i will have 90 checks (between each sentence.) Thanks.
Comment: It's actually 45 checks, not 90. You divide by 2 since order does not matter.
Answer: You can use intersection of python sets.
If you have three sentences as such:
a = "a b c d"
b = "a c x y"
c = "a q v"

You can check how many of the same words occur in two sentences by doing:
sameWords = set.intersection(set(a.split(" ")), set(c.split(" ")))
numberOfWords = len(sameWords)

With this you can iterate over your list of sentences, and find the two with the most sameWords in them. This gives us:
sentences = ["a b c d", "a d e f", "c x y", "a b c d x"]

def similar(s1, s2):
    sameWords = set.intersection(set(s1.split(" ")), set(s2.split(" ")))
    return len(sameWords)

currentSimilar = 0
s1 = ""
s2 = ""

for sentence in sentences:
    for sentence2 in sentences:
        if sentence is sentence2:
            continue
        similiarity = similar(sentence, sentence2)
        if (similiarity > currentSimilar):
            s1 = sentence
            s2 = sentence2
            currentSimilar = similiarity

print(s1, s2)

There might be some dynamic programming soultion to this problem if the performance is an issue.
Comment: You can speed this up quite a bit: a) Form the set for each sentence one, not once per comparison; b) no need to compare both `(a, b)` and `(b, a)`
Answer: import itertools

sentences = ["There is no subtle meaning in this.", "Don't analyze this!", "What is this sentence?"]
decomposedsentences = ((index, set(sentence.strip(".?!,").split(" "))) for index, sentence in enumerate(sentences))
s1,s2 = max(itertools.combinations(decomposedsentences, 2), key = lambda sentences: len(sentences[0][1]&sentences[1][1]))
print("The two sentences with the most common words", sentences[s1[0]], sentences[s2[0]])


How do i calculate Ranks based on score?

Question: There is a platform on which we rank users based on their points. Let's say there are about 10,000 entries. And database looks something like below.

Id
UserName
Points
Rank

0
Archit
0
4

1
Archit1
15
1

2
Archit2
10
2

3
Archit3
5
3

Whenever somebody does an action their point increases or decreases, based on that I also need to update the Rank in the database. But the problem is that updating it, again and again, every time somebody does action is a very slow process.
And also calculating the rank while showing it on the profile is also not a good way.
What should be the ideal solution to such a problem?
Answer: To make it efficient you should change only ranks changed, and not recalculate the whole data every time.
As you haven't specified programming language, here is an example pseudo code:
<code>-- input variables: CurrID, PointChange
CurrRank = Rank[CurrID]
Points[CurrID] = Points[CurrID] + PointChange
CurrPoints = Points[CurrID]
NewRank = SELECT count(Id) From YourTable where Points >= CurrPoints
if NewRank > CurrRank Then
  update YourTable Rank = Rank - 1 where Rank > CurrRank And Rank <= NewRank
else
  update YourTable Rank = Rank + 1 where Rank <= CurrRank And Rank > NewRank
end if
Rank[CurrID] = newRank
</code>
Comment: What if there is a person A with 1st Rank, person B with 2nd Rank, and person C with 3rd Rank, Person C gains score, and his rank changes to 1st. Now you mean that I should only update person C and person A. What will happen to a person B in between? Logically i person B should also be updated.
Comment: I don't say only person A and C. If you have a change, like rank 3rd to 8th, then you need to change everybody with original rank between 3rd and 8th (but don't change ranks 1st, 2nd and from 9th to end). That's also what the code does.
Comment: Oh okay got it. Thanks.


Adobe Edge Mobile Image Gallery

Question: I am using Adobe Edge Animate to create a large portion of my website, but I want to make a mobile version as well, and so obviously instead of onClick events, I want to use onTouch events. I just can't seem to find any good information on how to use touch events as I have never used them before.
I want to make a simple image gallery that plays forward when you swipe to the left, and plays reverse when you swipe to the right.
The big problem here is, how do I tell a touch event to do different things based on the direction of the swipe?
Answer: first of all, you're right, you want to use three event handlers: touchstart, touchmove, touchend
one approach you might take is to compare the starting position of the user's finger(s) to the ending position.  although the code will vary based on how many fingers you want to detect, i'll outline a basic method you can adapt.  in order to detect one finger, enter the following in a "touchstart" event handler:
var xStart = e.originalEvent.touches[0].pageX;
sym.setVariable('xStart', xStart);

that will store the starting x-position of the first finger in a variable and then make it globally accessible by other event handlers.
then maybe do the same thing in a "touchend" event handler.  use some logic to compare the two values.
xStart = sym.getVariable('xStart');
var xEnd = e.originalEvent.touches[0].pageX;

if (xEnd > xStart)
{
    sym.playReverse();
}
else if (xEnd < xStart)
{
    sym.play();
}

then you'll have some stop frames to hold at those images.
that's just an example, but hopefully it'll help you get going.
good luck!

Adobe Edge Mobile Image Gallery


Dimensions of Subspaces

Question: One of my review questions is:

True or false: if $E$ is a subspace of $V$, then $\dim(E)+\dim(E^\perp)=\dim(V)$? Justify.

My thought are that this is true, since E and E perp would sort of account for entire space of V, meaning there dimensions added would be the same as Dim V, or at least I am visualizing this to be true. I was wondering if anyone knew of a nice proof of this? I think I understand but I cannot really articulate it, so was hoping someone could help me.
Comment: Do you really mean $V^4$, and not just $V$?
Comment: Are you still here? Would you care to engage with the comment and the answers that have been posted?
Comment: Hi am here meant V, not V4 unsure how that happened, my apologies.
Comment: Good. So, care to engage with the answers that have been posted?
Answer: The following is a sketch of the result that may help you out. I assume that you mean that $V$ is a vector space and the question is that if $E$ is a subspace of $V$ (not $V^4$) then the dimension of $E$ plus the dimension of its orthogonal complement equal the dimension of $V$. $V$ has an orthonormal basis by the Gram-Schmidt result. So does $E$. Call these $e_1, ..., e_{\dim{(E)}}$. We can take $k = \dim{V}-\dim{(E)}.$ We have at least $k$ vectors in the basis of $V$ that aren't spanned by the $e_i$ basis vectors of $E$. By the Gram-Schmidt procedure, we can construct these to be orthogonal to the orthonormal basis vectors of $E$. Call these new vectors $v_1, ..., v_k$. Given that the basis of $v$ are the $v_i$ and $e_i$ vectors, the dimension of $V$ is clearly $\dim{(E)} + K$.
It is pretty straightforward to show that the $v_i$ vectors space the orthogonal complement of $E$. Though let me know if it is not.
Edit: RE: $V$ versus $V^4$. If $V=\mathbb{R}$ and $E$ = $\mathbb{R}^2$, then $\dim{(E)} + \dim{(E^\perp)} = 4>\dim{(V)} = 1$.
Edit 2: I assumed, also, that we are dealing with finite-dimensional vector spaces here.
Answer: If $X$ is a vector space and if $Y,Z$ are subspaces of $X$ with $X=Y \oplus Z$, then we always have
$\dim X= \dim Y + \dim Z$

Dimensions of Subspaces


Cyclic extension of local fields

Question: Let $K/k$ be an extension of number fields.
Is it true that for almost all places $v$ of $k$, the extension $K \otimes_k k_v / k_v$ is a cyclic extension of local fields? (Maybe under some additional assumption on $K/k$, e.g. if $K/k$ is Galois/abelian/...)
EDIT: OK, maybe that was not the question I wanted to ask. Is it true that for almost all paces $v$ of $k$, there exists a place $w$ of $K$ lying over $v$ such that the extension $K_w/k_v$ is cyclic?
Comment: The tensor product $K \otimes_k k_v$ need not be a field for most  $v$. Try $k = {\mathbf Q}$ and $K$ a Galois extension of ${\mathbf Q}$ whose Galois group is not cyclic (e.g., $K = {\mathbf Q}(\sqrt{2},\sqrt{3})$, whose Galois group is abelian). For all unramified places $v$ of $\mathbf Q$, the tensor product $K \otimes_{\mathbf Q} {\mathbf Q}_v$ is not a field since $v$ has at least two places over it (an unramified place with just one place above it has a decomposition group that is both cyclic and equal to the Galois group, which would be impossible if the Galois group is not cyclic).
Answer: Yes. You want to say that the decomposition group is cyclic for most primes. This is true for unramified primes because the decomposition group is isomorphic to the Galois group of the extension of residue fields, which is always cyclic.

Cyclic extension of local fields


Game losing goal

Question: In the NHL, or generally in ice hockey and similar sports, there is a statistic of GWG - game winning goals. A goal is a GWG if it is enough for a team to score only until this goal with no more goals in the game and still win the match. For example, if team A wins a match 5:2, their third goal was the GWG. It does not need to be the last goal scored.
Now, I want to ask, what happens if the GWG is an own goal? I know that in the NHL, the concept of own goals does not exist. But maybe in other sports like field hockey or floorball, even football, or in other ice-hockey leagues etc, what would happen then? Is it meaningful to talk about a statistics of GLG - game losing goals? It would be an own goal which is enough for the opposing team to win a match with it.
Comment: The 2001 UEFA Cup final was decided a golden own-goal: https://en.wikipedia.org/wiki/2000%E2%80%9301_UEFA_Cup#Final
Answer: Own goals, as a statistic, are rare enough in football that they are not regularly tracked by all competitions, if at all (some do, like the English Premier League).
They are not even possible in field hockey, as the rules require an attacker to play the ball inside the circle for a goal to be scored.
Given their rarity on an absolute scale, and the number of matches in which they would matter to the result, tracking a game-losing own goal ("GLOG") statistic does not make much sense.
From a player analysis perspective, it doesn't make sense to worry about whether an own goal was the GLOG, since the player scoring enough OGs to have significant GLOGs is not a good enough player to be at the level where such tracking would occur.
Comment: I agree, but it would be definitely an interesting curious statistic for fans, if an GLG occurs :D

Game losing goal


Electric field of finite sheet: Full analytical solution of integration?

Question: I am trying to work out the integral
$$
\operatorname{E}_{z}\left(x,y,z\right) =
\alpha\int\int\frac{z\,\mathrm{d}x'\,\mathrm{d}y'}
{\left[\left(x - x'\right)^{2} + \left(y -y'\right)^{2} + z^{2}\right]^{3/2}}
$$ with the limits $$-\frac{a}{2}\leq dx'\leq\frac{a}{2}\qquad-\frac{b}{2}\leq dy'\leq\frac{b}{2}$$ Mathematica does not return the solution in a reasonable time and I can't seem to find it.
This integral is for the $z$ component of the electric field of a homogeneously charged finite sheets in the $z=0$ plane. The sheets dimensions are $a \cdot b$. The integrals that need to be solved are detailed on the second page of this text. Note that The three integrals are for $E_x$, $E_y$ and $E_z$ (typo in the linked document).
I solved the $E_x$ and $E_y$ integrals in Mathematica and I would be grateful for some help or a pointer to get the analytical expression for $E_z$.
Comment: Perhaps taking one of the integrals first then the other might help.
Answer: This integral may be done analytically as far as I can see.  First, for the inner integral over $y'$, use a trig substitution $y'=y+\sqrt{(z^2+(x-x')^2} \tan{\theta}$ to transform the integral into
$$\alpha z \int_{-a/2}^{a/2} \frac{dx'}{z^2+(x-x')^2} \, \int_{-\arctan{((b/2)+y)/\sqrt{(z^2+(x-x')^2}}}^{\arctan{((b/2)-y)/\sqrt{(z^2+(x-x')^2}}} d\theta \frac{\cos{\theta}}{\sin^3{\theta}}$$
The inner integral has a simple antiderivative, and after some algebra, we are down to single integrals:
$$\frac{\alpha z}{2} \left (\frac{b}{2}+y\right)^2 \int_{-a/2}^{a/2} \frac{dx'}{\left[ (x-x')^2+\left (\frac{b}{2}+y\right)^2+z^2\right ]\left[(x-x')^2+z^2 \right ]} - \\\frac{\alpha z}{2} \left (\frac{b}{2}-y\right)^2 \int_{-a/2}^{a/2} \frac{dx'}{\left[ (x-x')^2+\left (\frac{b}{2}-y\right)^2+z^2\right ]\left[(x-x')^2+z^2 \right ]}$$
Using partial fraction decompositions, we may simplify the above expression drastically to get
$$\frac{\alpha z}{2} \int_{-a/2}^{a/2} dx' \left [\frac{1}{(x-x')^2+\left (\frac{b}{2}-y\right)^2+z^2}- \frac{1}{(x-x')^2+\left (\frac{b}{2}+y\right)^2+z^2} \right ]$$
These integrals are expressible in terms of arctan, and I assume you can take it from here.
Comment: Thank you very much Ron! That is a beautiful approach which makes the final integral much easier than I had thought. It is not a problem for Mathematica and indeed gives a nicer expression than the software finds. Another interesting lesson I learned today is about Mathematica: When giving it definite integrals, it worries a lot about the boundaries and their nature (are they complex, etc.) so that it takes much longer to solve than an indefinite integral. All of the three integrals in the above PDF are solved by Mathematica in seconds if you provide them as indefinite integrals.


Multipart PUT/POST timeout

Question: I configured my gitlab instance with an external nginx server according this documentation and following nginx configuration.
All is working fine, but when i try to change some profile settings in the UI I get an connection reset.
The problem only occurs on multipart form POST/PUT operations.
The funny thing is, that there are no log entries in any gitlab log files, so i think there is a problem in the nginx configuration somewhere.
Please when someone has any idea on how to further analyse the problem.
Thanks
Answer: The problem was the MTU setting for the TCP-IP Stack on my windows machine. I switched from 1500 to 1300 and now all is working fine again.

Multipart PUT/POST timeout


Diagnosing drush sql-sync problem

Question: Broadly, I'm having problems running drush sql-sync so that I can get a local copy of my dev database. I was getting an "The external command could not be executed due to an application error ... code: 255)" type thing.
To diagnose the problem more specifically, I ran drush @local sql-conf and got
 Array
    (
        [driver] => mysql
        [database] => soa
        [username] => drupaluser
        [host] => 127.0.0.1
        [port] => 33066
    )

When I then ran drush @dev sql-conf I got
Permission denied (publickey,password).

Running drush @dev sql-conf -s results in
Simulating backend invoke: ssh -o PasswordAuthentication=no firstname.lastname@example.com 'drush  --invoke --simulate --root=/var/www/dev --uri=http://default  sql-conf   --site=sub --env=dev 2>&1' 2>&1

Answer:
Permission denied (publickey,password).

This means the issue isn't with Drush, it's that the server that matches up to your @dev alias doesn't have your SSH public key set up to allow you access. Either your public key hasn't been added to the ~/.ssh/authorized_keys file or the permissions on that file (or the ~/.ssh/ directory) have the wrong settings.
Comment: Thank you! My id_rsa.pub was definitely copied into autorized_keys...Actually turned out I had rewritten ~/.ssh/config somehow!  Cleaned that up and in business.

Diagnosing drush sql-sync problem


How can I add usbip modules on Redhat 6 kernel?

Question: I have RHEL 6 with
<code># uname -r
2.6.32-131.0.15.el6.x86_64
</code>
I'm trying to build usbip modules on staging driver. Everything is OK. I have all needed *.ko files.
But I cannot add those modules on running kernel.
<code># pwd
/lib/modules/2.6.32-131.0.15.el6.x86_64
# ls | grep ko
usbip_common_mod.ko
usbip.ko
vhci-hcd.ko

# modprobe usbip
FATAL: Error inserting usbip (/lib/modules/2.6.32-131.0.15.el6.x86_64/usbip.ko): Required key not available
# insmod usbip.ko
insmod: error inserting 'usbip.ko': -1 Required key not available
</code>
How can I add it? Do I need to rebuild whole kernel?
TIA,
giobuon
Answer: I believe RHEL 6 will permit the loading of unsigned modules but not modules signed with an unknown key.
Try removing the signature from the module and loading again:

objcopy -R .note.module.sig usbip.ko usbip-new.ko


Parse attribute-centric XML with missing tags in R

Question: I have an XML file like this
<deviations-hour date-hour="2019052403" i-point="1.12291" price-up="1.12291" price-down="1.06395">
    <deviations deviation-type="46" deviation-price="1.12290" deviation-power="138.000">
    </deviations>
</deviations-hour>
<deviations-hour date-hour="2019052404" i-point="1.16397" price-up="1.16397" price-down="1.10773">
    <deviations deviation-type="45" deviation-price="1.10774" deviation-power="-685.000">
    </deviations>
</deviations-hour>
    <deviations-hour date-hour="2019052405" i-point="1.32412" price-up="1.32412" price-down="1.12999">
</deviations-hour>
<deviations-hour date-hour="2019052406" i-point="1.18508" price-up="1.18508" price-down="1.14266">
    <deviations deviation-type="45" deviation-price="1.14266" deviation-power="-214.000">
    </deviations>
</deviations-hour>

I tried to read file into dataframe.
library("XML")
doc <- xmlParse(xmlfile)
partA <- XML:::xmlAttrsToDataFrame(getNodeSet(doc, path='//deviations-hour'))
partB <- XML:::xmlAttrsToDataFrame(getNodeSet(doc, path='//deviations'))

xmlAttrsToDataFrame works fine. But.. Some lines of deviations tags are missing in XML file, but dataframe partB does not contain NAs. The function just skips these lines.
Eventually partB does not contain the same number of lines as partA, and I cannot correctly merge them.
Answer: Here's a first go using the xml2 packagens and the tidyverse.
I included a lot of comments to clarify each step taken.
library( xml2 )
library( tidyverse )

#read xml
doc <- xml2::read_xml( "./test.xml" )

#get the deviation-hour/deviation nodes
devHr.nodes <- xml2::xml_find_all( doc, ".//deviations-hour")
dev.nodes   <- xml2::xml_find_all( doc, ".//deviations")

#create vector all (unique) attrubutes inside deviations-hour/deviation nodes
att.devHr <- xml2::xml_attrs(devHr.nodes) %>% lapply( names ) %>% unlist() %>% unique()
att.dev   <- xml2::xml_attrs(dev.nodes)   %>% lapply( names ) %>% unlist() %>% unique()

#build part A
partA <-
  #loop over the attributes, extract attribute-values from all devHr.nodes
  lapply( att.devHr, function(x) devHr.nodes %>% xml_attr(x) ) %>%
  #set column names
  set_names( att.devHr ) %>%
  #convert to data.frame
  as.data.frame()

#build part B
partB <-
  #loop over the attributes, extract attribute-values from all devHr.nodes
  lapply( att.dev, function(x) dev.nodes %>% xml_attr(x) ) %>%
  #set column names
  set_names( att.dev ) %>%
  #convert to data.frame
  as.data.frame() %>%
  #find the parent node's date-time attribute, and extract it's value
  mutate( date.hour = xml_find_first( dev.nodes , ".//parent::deviations-hour") %>% xml_attr("date-hour") )

#left join on the timestamp
left_join( partA, partB, by = "date.hour")

output
#    date.hour i.point price.up price.down deviation.type deviation.price deviation.power
# 1 2019052403 1.12291  1.12291    1.06395             46         1.12290         138.000
# 2 2019052404 1.16397  1.16397    1.10773             45         1.10774        -685.000
# 3 2019052405 1.32412  1.32412    1.12999           <NA>            <NA>            <NA>
# 4 2019052406 1.18508  1.18508    1.14266             45         1.14266        -214.000

sample data "./test.xml"
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <deviations-hour date-hour="2019052403" i-point="1.12291" price-up="1.12291" price-down="1.06395">
        <deviations deviation-type="46" deviation-price="1.12290" deviation-power="138.000">
        </deviations>
    </deviations-hour>
    <deviations-hour date-hour="2019052404" i-point="1.16397" price-up="1.16397" price-down="1.10773">
        <deviations deviation-type="45" deviation-price="1.10774" deviation-power="-685.000">
        </deviations>
    </deviations-hour>
        <deviations-hour date-hour="2019052405" i-point="1.32412" price-up="1.32412" price-down="1.12999">
    </deviations-hour>
    <deviations-hour date-hour="2019052406" i-point="1.18508" price-up="1.18508" price-down="1.14266">
        <deviations deviation-type="45" deviation-price="1.14266" deviation-power="-214.000">
        </deviations>
    </deviations-hour>
</data>


Como executar uma funcao JS ou jQuery apos um update, reload em JSF e PrimeFaces?

Question: Preciso executar essa função depois que um botao dá um update="@form" na pagina

Ela funciona no cabeçalho da pagina, mas quando o update do ajax é executado ela nao funciona e os icones nao recebem as classes que deveriam receber..
Comment: Execute a função no callback do update do ajax...
Comment: Esta usando um `commandButton`? Dê uma olhada no atributo `onComplete` para chamar essa função.
Answer: Para que a solução fique genérica, coloque um chamada a função dentro do formulário.
Assim, toda vez que um update for realizado no form, a função será chamada novamente, independente do componente que fez update no form.
Quando o form for renderizado novamente, a função será novamente chamada
A idéia é que fique parecido com:
<h:form>

...

Comment: Hoje passei por uma situação parecido e a resposta do Felipe foi muito útil..
Answer: Eu faço assim:

o oncomplete é executado sempre que a requisição efetuada pelo componente for executado com sucesso. É equivalente ao success do ajax.
Comment: Eu tentei assim e não funcionou, até porque quando um campo atualiza o @form o css sai e nao funciona mais, pois nao é só os botoes que dao update="@form"
Comment: As classes dos seletores se perdem ao dar update nos componentes?
Comment: Isso.. Se perdem, nao atualizam junto com o form
Comment: Vc não consegue usar o atributo `styleClass` nesses componentes para poder buscar depois?
Comment: @Gerson, você consegue pegar os componentes usando id ou outra coisa? Eu acho que a resposta do [Felipe Fonseca](http://pt.stackoverflow.com/a/29980/4050) vai te ajudar, coloque no final da página e veja se funciona.


Safari SVG transform-origin zoom animation

Question: I have an inline SVG which is being animated, however when you zoom in or out in the browser the object which is being rotated no longer rotates at its centre point.
It works fine in Chrome.
http://codepen.io/chrismorrison/pen/rmLXWw
#rays {
  animation: spin 6s linear infinite;
  -webkit-transform-origin: center center;
  transform-origin: center center;
}

@keyframes spin {
  from {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
    -webkit-transform-origin: center center;
    transform-origin: center center;
  }
  to {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transform-origin: center center;
    transform-origin: center center;
  }
}

Comment: @Iceberg, no, finally we needed to adjust our site not to transform that SVG element...
Comment: Sorry it's been a while since I looked at this but having fixed values as px seemed to work as suggested below.
Answer: I know this is late, but I found the same issue. If you use transform-box: fill-box;, the object will rotate on its axis properly in Safari.
Comment: I do have the same problem now, and I cannot solve with `transform:fill-box;`. And all the examples I find with this does behave wrong when I do zoom in/out in Safari. can you maybe send me an example which iteam I need to apply this?
Answer: I had a similar issue which I was able to resolve by adjusting the SVG's viewport attribute so that i could set
transform-origin: 0 0;

for the element I need to transform.
I've created a pen here showing the difference between the two: https://codepen.io/mbrrw/pen/NWxMamm
For a 20x20 circle, I changed the viewBox from 0,0,20,20 to -10, -10, 20, 20.
Hopefully this helps!
Comment: Brilliant! This does it! `transform-origin: 50%, 50%` is required however, as your CodePen uses.
Comment: Actually it looks like leaving out `transform-origin` entirely works fine in Safari. (Which is effectively what was happening in my previous comment as using `,` isn't valid for this property.)
Comment: hm thanks. is the pen / solution above wrong then?
Comment: Pen works great! With the solution update here both are working for me now :)
Answer: I know this is a very old question, but I've spent the last hour trying to come up with a solution and I wanted to share my solution in case it ever happens to anyone else!
Just like the OP, zooming in or out in Safari would screw up my transform-origins and they would be based on what the original size of the SVG pre-zoom. In my example, I was trying to rotate with a transform-origin of 100% 0%.
My fix (using Javascript): transform-origin: svgElem.currentScale * 100 + '% 0%';
Now, instead of having my rotate be off-axis, it's always in the right position.
Hopefully that helps someone!
Answer: Chrome's implementation of transform-origin is different from other browsers.  Try using absolute coordinates.
-webkit-transform-origin: 201px 191px;
transform-origin: 201px 191px;

I'm not sure if this will fix your Safari problem, but it is good practice anyway. Especially if you want it to work in Firefox also.
Answer: I fixed it using rem unit to set transform-origin.
.logo-spinner path {
    animation: my-spinning-animation 1.8s infinite ease;
    transform-origin: 3rem 3rem;
}

Now, animation always remains centred while zooming-in/out on Safari.
(Except for the smallest zoom level which I think is acceptable)


1GB dedicated port

Question: I'm in the process of selecting a dedicated host for a big data project deployment. I need my servers to be well connected with each other.
One of the provider I'm investigating is serverloft.
Here is a statement I've found on the website about their server networking : "The dedicated 1 Gbit/s port provides you with the maximum, exclusive bandwidth of 1000 Mbit/s."
I need help for decrypting the real meaning of this statement.
Does it means my server will be connected to a switch capable of 1Gb/s uplink, so the badwidth will be 1Gb/NUMBER_OF_SERVER_BEHIND_THIS_SWITCH; or does it mean that my server will effectively be able to push 1Gb/s to another server in another rack in the same datacenter at all time?
This might be a dump question, but I'm a bit lost; so if you have an informed opinion about this, or even better, a direct knowledge of the serverloft network, I'll be very grateful if you can help.
Answer: The "Dedicated 1 Gbit/s switch port" means pretty much exactly what it says. You get your own 1Gb/s port on the switch that links servers to their backbone. This port will carry both your server-to-server traffic and your Internet traffic. Presumably their backbone is well-designed and not overloaded and so you will be able to actually use this bandwidth for any combination of server-to-server and Internet traffic that you want.
Answer: This means that you will have a single 1Gbps uplink to the internet. What you do with this is your choice. Most people will install a firewall, switch and expand from there. If this is a single host, this does not necessarily mean you'll have 1Gbps performance to another dedicated server in the same facility.
Comment: Ask the datacenter or hosting provider. We can't answer this for you.
Comment: So, you mean I might have a 1Gb/s link to the internet, but server-to-server bandwidth in the same datacenter could be less thn that ?
Answer: You mix up your link and the backbone - if I were you I would NOT use that link for anything but internet uplink and provide your own switch in the rack to connect the servers. That simple. Especially when you do big data - youshould likely go to 10g for some data servers that do the backups.
Then use the 1g link provded by your hoster for exactly and only the internet traffic.
Hoster ports are expensive and not really needed for in rack traffic. This is how I did it and how I do it now - in fact, right now (although my racks are in my own data room now):

I use 10g for file and backup servers using Netgears nice 52 port switch that has 48 1g ports and 4 SFP+ ports for 10g.
One of those 1g port goes to to our router which is a Mkrotik and from there we go to our internet provider uplink.

THis gives my all my local traffic local. It also allows me to use my own IP address scheme for servers that are not public.
Comment: Sounds like a great setup. But I dont't have the option to do my own setup. I have to choose a dedicated server provider. The server only have 1 NIC, the intra-datacenter traffic and internet both goest though the "1Gb dedicated port switch"; the whole question being; would I really got 1Gb/s bandwidth between two servers hosted in the same datacenter of my provider.
Comment: I am sure the server provider is not as idiotic as you make him sound like. The rest ican not be answered - it depends on how the data center is set up, which may vary between providers. BUt really, choose one that does not suck that badly. I have one server rented right now at a provider and I know that if I ramp up, I can ship them a switch or have them install one that I rent.

1GB dedicated port


Como criar uma janela sem usar o construtor de GUI?

Question: Estou começando a estudar C# e assim como no Java, IDEs fornecem recursos que tornam possível construir GUIs facilmente arrastando componentes. O netbeans possui uma poderosa ferramenta de construção onde é possível arrastar componentes Swing para um JFrame, JDialog, etc. No visual-studio me senti em casa, é praticamente o mesmo esquema.
A minha duvida é: No Netbeans, o código gerado pelo GUI Builder é funcional, porém muito complicado de dar manutenção - supondo que quem for dar manutenção não usará o construtor de interface do Netbeans (e.g um usuário do eclipse). Dependendo dos requisitos na interface gráfica é muito melhor escrever o código "na unha", tornando o código fonte bem mais simples de ler. Não sei como o código da janela é gerado em C#, mas gostaria de saber se é possível construir uma interface gráfica no código "puro", manualmente.
Por exemplo, em Java basta o seguinte trecho para mostrar uma janela:
import java.awt.event.*;
import javax.swing.*;

public class MinhaJanela extends JFrame {

    public MinhaJanela(){
        super("Minha Janela");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 300);
        setLocationRelativeTo(null);

        JButton btn = new JButton("Click aqui");
        btn.addActionListener((ActionEvent e) -> {
            btnClick();
        });
        getContentPane().add(btn);
        setVisible(true);
    }

    private void btnClick(){
         JOptionPane.showMessageDialog(null, "Clicou!");
    }

    public static void main(String[] args) {
        new MinhaJanela();
    }
}

Como seria criar a mesma janela em C#?

PS: Não, eu não sou um hater de construtores de GUI, é mais por questão de curiosidade mesmo, quero entender como funciona.
Answer: Concordo que frequentemente é melhor escrever o código na mão que usar o gerador. Dá mais flexibilidade e controle. Eu sou visual builder hater :P
O Visual Studio gera códigos mais fáceis de dar manutenção separando inclusive o que você deve mexer e o que só o gerador deveria manipular (você até pode mexer nesta parte sob risco de criar dificuldades para o gerador). A existência de métodos e classes parciais ajudam muito nisto.
Mas nada impede de escrever tudo na mão. O que eu vejo acontecer muito em programadores experientes que estão começando no C# é gerar um classe pelo IDE para analisar e ver como proceder em futuras implementações manuais.
Um Hello World um pouco mais funcional que o seu exemplo:
using System;
using System.Windows.Forms;

public class HelloWorld : Form {
    static public void Main() {
        Application.Run(new HelloWorld());
    }

    public HelloWorld() {
        this.Text = "Minha Janela";
        Button b = new Button();
        b.Text = "Click aqui";
        b.Click += new EventHandler(Button_Click);
        Controls.Add(b);
    }

    private void Button_Click(object sender, EventArgs e) {
        MessageBox.Show("Clicou!");
    }
}

Coloquei no GitHub para referência futura.
Um tutorial mais completo.
Comment: @renan e não deixa de ser uma concatenação. Ele concatena a uma lista de assinantes.
Comment: Achei interessante (e estranho) a forma de adicionar um *listener* no botão: `b.Click += new EventHandler(Button_Click);` é quase um "concatenar" evento.


Regression with small data set and many independent variables

Question: I have 14 observations.
There are 11 independent variables $(x_1,x_2,\dots,x_{11})$.
Dependent variables and all independent variables are continuous.
I am not sure which regression model we use in this case to predict y( dependent variable).
Any hints ?
Comment: To my understanding, the size of the dependent and independent variables must match for regression.
Comment: This question depends on your problem domain.  If you already have a known model that the data's expected to fit, e.g. as in measurements, then it's sufficient to have one observation per independent variable.  However if you have no idea what sort of models might fit the data, then regressions are basically guess-and-check, which is why big data analysts tend to split up their data sets into training data (which is regressed) and validation data (which validates the regression of the training data).  [...]
Comment: Then, there're also intermediate cases in which you have a general idea about what regressions might fit the data.  Since there's such a range of possible answers given your problem domain, it'd probably be a good idea to state the problem background in the question.  Otherwise, people who provide answers will respond with what they know - which is nothing - resulting in a training/validation approach.  And you don't have enough observations to do that well, so that's unlikely to be productive.
Comment: _**tl;dr**-_  You should add your problem domain to the question statement.
Comment: @StudentT, sample size is 14 for complete data.  for ex: 11 are dependent variables with 14 observations value and 1 dependent variable with 14 observations
Comment: @Nat, So I need to use training,testing data and check which regression is fit for data, right?
Answer: When you have only 14 observations and 11 independent variables, almost any model is likely to be overfit, even if you just choose among the 11 models with one variable, you are going to be biasing results.
You could still try LASSO to build the model, but it is likely to pick no variables at all (just the mean).
Another option is to present all 11 regressions so the reader can see what is going on.
In a comment, you suggest using backward and forward selection, but these have been proven to give wrong output.
Comment: ,Hello sir,  here is the link for this research paper then told us, if p >=n then use LASSO-EN  ,   http://web.stanford.edu/~hastie/Papers/B67.2%20(2005)%20301-320%20Zou%20&%20Hastie.pdf      &   http://web.stanford.edu/~hastie/TALKS/enet_talk.pdf
Comment: Hello sir, I read some research paper regarding LASSO-elastic net,  can I apply this in my data?
Answer: If your sample is this small, I would suggest you go through a methodical process of building different models with different sets of variables. Any domain knowledge you have will be useful as well.
In any case, you will find it hard to finally choose a model with confidence as you will not be able to validate with any accuracy.
Comment: I think that any model with more than 1 IV here is likely to be overfit.
Comment: Can you explain which regression model I have to use? i am thinking about backward-forward, can I use that ?


Why not to normalize the image to have zero mean in reinforcement learning?

Question: I learned in deep learning classes, cs231n for example, that it is better to have input data to have negative values so as to have negative gradients. Although negative gradients may also be achieved deep neural net, this, to my best knowledge, is still recommended in compute vision tasks. But I've recently seen many reinforcement learning algorithms on Atari, such as OpenAI's baselines, that do not zero center the input data --- they simply divide the input images by 255. What makes this difference? Why don't they zero center the data? Which is is better in practice?
Answer: In reinforcement learning (RL) it is not common to normalise inputs to mean $0$ standard deviation $1$, because the problem is non-stationary, plus data for training is generated as required. Due to these traits, you don't have access to a large unbiased data set where you can establish accurate bounds on statistics for the input features and outputs, except towards the end of training close to convergence.
For this reason, you won't generally see use of standard feature normalisers for deep RL. However, neural networks are still sensitive to scale of input features, so at least some basic scaling needs to be done.
That does not stop you for example dividing by 128 and subtracting 127 for normalising pixel values. This should work fine for training ML based on neural networks, and make the value 0 refer to a mid grey colour. Other scalings could also work, and you could based them loosely on general statistics of the images found in the target environment.
Scaling of pixel channels into the range $[0,1]$ is often convenient for other purposes, such as displaying the images from some code libraries. It is also a convention that has been used in some original RL papers, so it may be continued to be used for fair comparison between techniques.


Space-efficient probabilistic data structures for number retrieval

Question: Consider we have an algorithm that receives a hypothetically long stream of keys. It then generates a value between 0 and 1 for each key, as we process it, for posterior retrieval. The input set is large enough that we can't afford to store one value for each key. The value-generating rule is independent across keys.
Now, assume that we can tolerate error in the posterior lookup, but we want to still minimize the difference in retrieved and original values (i.e. asymptotically over many random retrievals).
For example, if the original value for a given key was 0.008, retrieving 0.06 is much better than retrieving 0.6.
What data structures or algorithms can we use to address this problem?
Bloom filters are the closest data structure that I can think of. One could  quantize the output range, use a bloom filter for each bucket, and somehow combine their output at retrieval time to estimate the most likely value. Before I proceed with this path and reinvent the wheel, are there any known data structures, algorithms,  theoretical or practical approaches to address this problem?
I am ideally looking for a solution that can parameterize the tradeoff between space and error rates.
Comment: Can we do range partitioning and write a hash function to map every number to specific range. The values within range can be controlled based on error factor.
Answer: Perhaps a variant of the Bloom filter called Compact Approximator: like a bloom filter but generalized so the entries are values from a lattice.
That lattice is here just floats between 0 and 1 (it has more structure than just being a lattice but it satisfies the requirements) or however you're storing those numbers.
An update replaces the relevant entries by the max between it and the value being remembered, a query computes the minimum of all its relevant entries (examples below). The results can only overestimate the true value. By reversing the ordering (swapping min and max and initializing to 1 instead of 0) you can get an underestimation, together giving an interval that contains the true value.

So for example, using the first approximated (overestimations), putting in a number looks like this:
index1 = hash1(key)
data[index1] = max(data[index1], value);
index2 = hash2(key)
data[index2] = max(data[index2], value);
... etc

And getting the overestimation looks like:
result = 1
index1 = hash1(key)
result = min(data[index1], result);
index2 = hash2(key)
result = min(data[index2], result);
... etc

Comment: Beat me to it.  Well played.
Comment: Thanks @harold. Very helpful. I think an example for number retrieval would just make this perfect. Would you mind perhaps adding one?
Comment: Thanks! Reading the original paper it looks like one can use d-independent hash functions. (i.e. one uses "a d-dimensional, m-bucket compact approximator") Does `d` have to be = 2 in our case? What is the relationship?
Comment: @AmelioVazquez-Reina it doesn't have to be 2, the optimal number depends on the size of the table and the number and distribution of items placed into it. That paper doesn't address error in the sense that we have here so it may turn out a bit different, I'll investigate a bit
Comment: @AmelioVazquez-Reina it turns out this is really terrible if we want to "overstuff" the table with more values than entries, no matter the d it very quickly reaches an average error worse than if it just guessed 0.5 for everything, at least if the values are uniform in [0..1]. Actually higher d was even worse, with d=1 being the best. So it turns out this is not a proper use case for compact approximators after all..
Comment: Thanks harold that makes sense. I'd be curious to know what you think @LouisWasserman


RxJS - Fire subscribes in order

Question: I am trying to figure out the RxJS pattern for declaring my "subscribes" such that they execute in order.
Here's the situation I'm in:
var flag = false;

// Stream that non-deterministically emits `true` when flag is true
var random$ = Rx.Observable.interval(1000)
  .map(() => setFlagToRandomTrueOrFalse())
  .filter(x => x)
  .first();

// How can I declare my "subscribes" so that the console.logs happen in order?
var sub1 = random$.subscribe(() => console.log(1), console.log, resetFlagToFalse);
var sub2 = random$.subscribe(() => console.log(2), console.log, resetFlagToFalse);

function setFlagToRandomTrueOrFalse() {
  flag = flag || !!Math.floor(Math.random() * 2);
  return flag;
}

function resetFlagToFalse() { flag = false; }

This currently prints 1 and 2 in random order due to the async nature of .subscribe.
Also, what is the proper name for these "subscribes"? Total RxJS noob here.
Comment: If the order is important, shouldn't they be composed into a single subscribe?
Comment: I was hoping to avoid nesting a subscribe within the `onNext` of a subscribe. This is just a strawman example, where `flag` is actually a boolean that is maintained by a different library.
Answer: eeerr I am not sure the order you observe is because of the async nature of subscribe.
First of all, as currently written, random$ is a cold source, i.e. a producer which has not been subscribed yet. That producer will start producing every time you subscribe to it. That means here, you are starting the producer twice, so you will have two different random values emitted for each, so the log will be shown at different times, given that you have not subscribed to the same sequence of values, even when it looks very much like so.
A more clear description of the distinction between cold and hot streams is Hot and Cold observables : are there 'hot' and 'cold' operators?. Spend as much time as necessary to understand this because this is very important before you start to do anything fancy with Rxjs.
If you want to subscribe to the same sequence of values, i.e. if you want the producer to multicast its values to all subscribers (hot behavior), instead of restarting for each subscriber (cold behavior), you need to use a variation of the multicast operator, as explained in the abovementioned link. That means in your case
var random$ = Rx.Observable.interval(1000)
    .map(() => setFlagToRandomTrueOrFalse())
    .filter(x => x)
    .share();

Going back to your question about data propagation order, it is indeed mostly deterministic, which does not mean always simple. In a simple case as yours, the first subscribe will indeed be executed first. That is because under the hood, multicast-like operators are using subjects, which emit immediately (hot source) the value they receive to all their subscribers, in order of subscription. For information about subjects, have a look at What are the semantics of different RxJS subjects?.
Last thing, it helps a lot to reason about your streams if you compose pure functions. Having a closure variable such as flag makes thing really more complex very fast.
I recommend you to have a look here before delving much further into Rxjs : The introduction to Reactive Programming you've been missing
Answer: You can use publish() and connect() to perform the actions in sequence like this

var flag = false;

// Stream that non-deterministically emits `true` when flag is true
var random$ = Rx.Observable.interval(1000)
    .map(() => setFlagToRandomTrueOrFalse())
    .filter(x => x)
    .first().publish();

// How can I declare my "subscribes" so that the console.logs happen in order?
var sub1 = random$.subscribe(() => console.log(1), console.log, resetFlagToFalse);
var sub2 = random$.subscribe(() => console.log(2), console.log, resetFlagToFalse);

random$.connect();

function setFlagToRandomTrueOrFalse() {
    flag = flag || !!Math.floor(Math.random() * 2);
    return flag;
}

function resetFlagToFalse() { flag = false; }

RxJS - Fire subscribes in order


How to change number of item per page in taxonomy page?

Question: I have multiple content types. I want to change number of item per page in teaser mode and  it is different for every content type.
In admin/config/system/site-information we can change number of item for all content types. But I want to change number of items for each content type.
What do I do? Please help.
.
Answer: Go to Admin > Structure > Views. Enable the Taxonomy Term View :

In views configuration change the pager settings as you want.
Comment: Can I see the screenshot of configuration you change after enabling the view?
Comment: I eneabled this view but in taxonomy page don't show any thing while in preview of this view show node of defined term id.i dont know that dont show any thing in any taxonomy page?
Comment: please describe config of view
Comment: Well you have added a filter in filter criteria. It seems it has some tid filter. I think because of that it is not displaying list. Try to see after removing the filter.
Comment: no when i remove this filter but yet dont show any thing.when i enabeld this view with default config dont show any things.!!!
Comment: Well, It seems translation issue or something like that. Can't say without checking it.
Comment: I want to display different number item per page for every content type.thus i need add a filter that specified content type.please help
Comment: No, filter is not required in that case. I don't think if it is possible without some custom coding.
Comment: please describe how i do number of item per page in any content type that different for any content type?
Comment: in this view i can number of item for all content type as same.bu i want to be different. and unforunately dont display any things in taxonomy page???


A proof exercises of conditional expectation of sigma algebra

Question: I have two questions for my assignment that I don't know how to prove.
Both are based on the condition (omega, F, P) is a probability space, and G is a sub sigma-field of F.
The first question is show that E(XE[X|G]) = E[E[X|G)^2].
The second question is
Let X be a F-measuarable random variable such that E(X^2) is finite. Prove that
E(E[X|G] - X)^2 = inf {E(Y-X)^2, E(Y^2)

They are about conditional expectation of random variables. Can anyone please help?Thanks a lot!
Answer: Hint: (1) $E[X\mid \mathcal G]$ is $\mathcal G$-measurable, hence
$$ \def\G{\mathcal G}E\bigl[XE[X\mid \G] \mid \G\bigr] = E[X \mid \G]E[X\mid G]
$$
now take expected values and use that $E[E[Y\mid G]] = E[Y]$ for any $Y$.
(2) We havefor $Y \in L^2(\mathcal G)$, $\def\abs#1{\left|#1\right|}$
\begin{align*}
   E\bigl[Y(X-E[X\mid G])\bigr] &= E\bigl[XY - E[XY\mid G]\bigr]\\
       &= E[XY]- E[XY]\\
       &= 0,
\end{align*}
Hence, for any $Y \in L^2(\mathcal G)$:
\begin{align*}
  E\bigl[\abs{X-Y}^2\bigr] &= E\bigl[\abs{X-E[X\mid G] - (Y - E[X\mid G])}^2\bigr]\\
   &= E[\abs{X-E[X\mid G]}^2] - 2E[(X-E[X\mid G])(Y-E[X\mid G])] + E[\abs{Y-E[X\mid G]}^2]\\
   &= E[\abs{X-E[X\mid G]}^2] + E[\abs{Y-E[X\mid G]}^2]
\end{align*}


Check if field has value (content)

Question: I have code which checks if field exists, but I try to change it to check if field has value (content) or not.
In views I have one field to show all content (Rewrite results). So all fields are loaded always. Thats why I need code which checks does field have content or not.
This is what I got now, but it adds "has_no_field" to all - no matter if field_image has content or not.
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (isset($row->field_image['und'][0]['value']) == 1) {
      $vars['classes_array'][$id] = 'has_field';
    }
    else {
      $vars['classes_array'][$id] = 'has_no_field';
    }
  }
}

Answer: Try changing
if (isset($row->field_image['und'][0]['value']) == 1) {

to
if (!empty($row->field_field_image)) {

Comment: Still adding "has_no_field" to all rows - no matter if there is image or not.
Comment: @hene I've updated the answer. Observe the extra field_ in front of field_image. Had to have a look myself and just noticed that :)

Check if field has value (content)


Create monthly tabs in excel with VBA

Question: I am trying to write a code in VBA which will use the specific date in the cell 'B1' and create new tabs in excel which will be the date in 'B1' + one month. I am new to VBA, and for this reason do not know how to write a code, I will appreciate your help. To the moment I have the following code, but it creates only one sheet, and for previous month, not for future one, and I do not know how to link it to the cell B1 in the existing tab. In addition, I would like to have a code which will create monthly sheets for next 5 years. Below is what I currently have:
Private Sub MonthlyUpdate2()
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.name = Format(DateAdd("m", -1, Date), "MMM-YY")
    End With
End Sub

Answer: Set a var to the date value in B1 before creating the new worksheet so that you can use it in the naming process..
Private Sub MonthlyUpdate2()
    Dim ws As Worksheet, dt as long
    With ThisWorkbook
        dt = activesheet.range("B1").value2
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.name = Format(DateAdd("m", 1, dt), "MMM-YY")
    End With
End Sub

A date is just a number representing the number of days since 31-Dec-1899. For this purpose, a long integer is just as suitable as a date var. Also note -1 became 1 in DateAdd.
There is some confusion as to where the B1 cell actually is so I've used ActiveSheet (the one you can see). This isn't always the best method and a properly defined parent worksheet is preferred.
Answer: Try this code and adjust var nb_month_to_create as you want. I suppose that b1 date is in your 1st sheet but you can adjust the name "sheet1"
Private Sub MonthlyUpdate2()
    Dim datestart As Date
    datestart = ThisWorkbook.Sheets("Sheet1").Range("B1").Value

    Dim nb_month_to_create As Integer
    nb_month_to_create = 5 * 12 '5 years

  For i = 1 To nb_month_to_create
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.Name = Format(DateAdd("m", i, datestart), "MMM-YY")
    End With
    Next i
End Sub

Comment: Thanks a lot for the code, it works incredibly perfect!
Comment: Great pleasure to help you :)
Comment: @MrMirzayev if this answer helped you resolve your issue, please accept it by clicking the green V on the left ;) thx

Create monthly tabs in excel with VBA


Can't access socket.io

Question: this might be a bit of a silly question but it's something that i've been struggling to find the answer to and for some reason it doesn't seem to be evident from the tutorials and websites i have been reading, so maybe it's something that is assumed that i'm really missing.
So anyway, i installed node.js and then used the command npm install socket.io. it them proceeds to download and install a bunch of files, i don't see any error with this process in the command line.
So now i've tried to access socket.io like this:

Like it shows on the socket.io website, however i get an error saying the file isn't found..... my first guess is that the installation of node.js and stocket.io are both on the local machine (program files) and not in the htdocs.
I have tested this one two platforms, first was my localhost which is Windows 7 running XAMPP on it, and i installed node.js and stocket.io globally (Program files). Second was my Windows server that uses IIS still get the error.
So my question is, how do i reference the stocket.io API and start using it based on the installations i have?
Thanks for your time.
Answer: npm isntall socket.io installs Socket.IO in a local node_modules folder so that the library is accessible to you in your own Node.js applications. You still need to create (and run) a Node.js application that loads up the module and sets up an HTTP server that uses the module; the examples under How to use in the project readme is a good starting point, although preexisting knowledge of Node.js will be helpful. You might check out Node.js Tutorial with Socket.IO if you're looking for additional information.

Can't access socket.io


Special chart of a compact connected manifold.

Question: A friend of mine asked me if the following question is true:

Question: Let $M$ be a compact connected smooth manifold without boundary, then if $a_1,$ $a_2$ $\in$ $M$, there is a chart $(\varphi,U)$ of $M$ such that $a_1,$ $a_2$ $\in$ $U$.

Despite this seems like a lie, I wasn't able to find a counterexample or prove this statement.
Anyone know how to demonstrate this or know a counterexample for this question?
Answer: Here's a general fact:

Theorem: For any $x,y \in M$, any path $\gamma : [0,1] \to M$ such that $\gamma(0)=x$ and $\gamma(1)=y$, and any open subset $V \subset M$ containing $\text{image}(\gamma)$, there exists a diffeomorphism $f : M \to M$ such that $f(x)=y$ and such that $f(z)=z$ for all $z \in M-V$.

You can apply this theorem to your problem by starting with any chart $(\phi',U')$ containing $a_1$. If $U'$ contains $a_2$ then you're done. Otherwise, pick a point $a'_2 \ne a_1 \in U'$. Let $\gamma : [0,1] \to M$ be a path with $\gamma(0)=a_2$ and $\gamma(1)=a'_2$, and perturb $\gamma$ so that $a_1 \not\in\text{image}(\gamma)$. Now take $V$ to be any open set that contains $\text{image}(\gamma)$ and does not contain $a_1$. Then apply the above theorem to get a diffeomorphism $f$, and we obtain the desired chart $(\phi,U)$ where $U = f^{-1}(U')$ and $\phi = \phi' \circ f$.
The theorem above is not hard to prove. One starts with any covering of $\text{image}(\gamma)$ by coordinate charts of $M$ that are contained in $V$. Then one applies the Lebesgue number lemma to subdivide $\gamma$ into finitely many subpaths each of which is contained in a single coordinate chart that is contained in $V$:
$$\gamma = \gamma \mid [t_0,t_1] * ... * \gamma \mid [t_{K-1},t_K] \qquad 0=t_0 < t_1 < .... < t_{K-1} < t_K=1
$$
where $\gamma \mid [t_{k-1},t_k]$ is contained in a coordinate chart $(\phi_k,U_k)$ such that $U_k \subset V$. For each $k$ one can easily produce a diffeomorphism $f_k : M \to M$ which is the identity on $M-U_k$ and such that $f_k(t_{k-1})=t_k$. Then one defines $f = f_K \circ ... \circ f_1$.


Restringing Acoustic guitar

Question: I always have issues restringing the high E string. It breaks when tuning it. So today I used 2nd string as the first one and tuned it to High E, does it have a significant impact on tonality?
Comment: Does it tend to break at the same point and if so, where? There may be a sharp edge it can't cope with.
Comment: Maybe the obvious question… are you absolutely certain you're tuning it to the correct note?
Comment: I agree with @Tim, a sharp edge on the saddle or nut might be the culprit. Does it always break in the same place?
Comment: Yes, please consider what @Tim said. Skipping the first string is a hack that surely won't be sustainable. Instead try to fix the problem. If the string consistently breaks there is probably something wrong with either the bridge, the nut or the tuning pegs. Such edges can easily be smoothened out. So by looking at where the string breaks you can determine where the problem lies.
Comment: I had that issue with a different string after I had a new bone saddle installed on one of my acoustic guitars.  Turns out the saddle had a sharp edge that I had to file down with a a very fine material (did not take much).  I read about and tried applying graphite in the little groves your strings cut in the saddle.  Just use a number two pencil and rub it in the groove.  That lubricates the point of contact to reduce friction when tightening the string to bring it to pitch.
Answer: The tonality is easily checked by comaring the 12th fret harmonic with the pitch it produces when 12th fret is fretted.
It may put that string a little out of tune as you go up the neck, but a bigger problem I see is that the string is much tighter than the others in the set. Making it feel strange to fret. It's not the real answer to your problem. The extra tension is hardly going to do much else apart from increase its propensity to break due to increased tension, but if it breaks at the same point as the others, there will probably be a sharp causing it. Maybe at the saddle, maybe the nut or even the machine head winding post itself. You may have solved the sympton but not the cause.
What gauge strings (individually) are on now?
Answer: Possibly. Intonation is balance of factors, and going from .012 to .016 for the high E (gauges from Stringjoy's light set) might mean the bridge is in the wrong place and your higher strings will be off.
My concern is that the tension would be much higher — moving from 25 to 45 lbs of tension — so assuming it would not break, it would be uncomfortable to play. As a desperate stopgap measure, you can do it but I wouldn't want to leave it that way. Not because you'll break your guitar (maybe you will?) but because it will hurt your fingers.
Seriously, new musicians who start on guitar do not have trained ears, which means that you do not know what the high E should be. I certainly did not, and once bought a ten-pack of replacement E strings because I was breaking so many. (Guitar store guy thought I was making a tattoo gun.) Electronic tuners help with this. Strings cost like a dollar each (in the US) and there are great free phone apps you can use. Learn to tune it right with the right strings.
This is assuming this is a steel-string acoustic guitar. I think it would be fine with a nylon-string guitar, but I'm not sure.

Restringing Acoustic guitar


Book for probability and various probability distribution functions.

Question: Please suggest a book/books where i can understand

Probability theory (with lots of example and solution)
examples on permutations and combinations.
list of all probability distribution functions, and their mathematical derivation. (I have good understanding on differential and integral calculus)
A case study where some random experiment is conducted and data is analysed as some standard probability distribution function.
From above case study how meta data is extracted from Probability distribution functions.
Comment: Schaum's outline on Probability and Statistics explains concepts in terms of questions and answers. Can serve as a book with "examples".
Comment: @shyamupa thanks for quick answer.
Answer: I have recently researched a lot for finding good stuff on Probability . I would suggest you to have a look at this . This is undergraduate course of probability taught in MIT . The professor is very good . You will have lots of resources on this site
1.Video Lectures
2.Assignments
3.Tutorials and Quizs
Comment: video lectures are amazing, thanx a ton, really appreciate it :)


Como remover a mensagem de error 401 do console com AngularJS/Javascript?

Question: Eu recebo a seguinte mensagem de erro no meu console:
POST http://localhost:8080/minhaURL 401 (Unauthorized)

Gostaria de saber como faço pra retirar esse log de erro do console, pois já estou dando um retorno visual para o usuário de que ele errou alguma coisa.
Só pra contextualizar, estou fazendo um POST com um password, e caso o mesmo esteja incorreto, eu retorno um 401.
EDIT:
JS
    requestHandler.authenticate(password).then(function(response){
         console.log('200 ok');
    }).catch(function(err){
         console.log('401 deu erro na validação')
    });

Esta é mensagem de erro a qual me refiro:
Comment: Poste código e em qual momento isso acontece.
Comment: Ok, eu vou postar....
Comment: Acho que mesmo você tratando, o erro vai continuar sendo exibido no Console. O fato de tratar não quer dizer que o erro vai parar de ser exibido no console, mas que agora o usuário vai ter uma satisfação do que aconteceu.
Comment: Eu acho que isso não é possível por se tratar de um comportamento do browser e não do angularjs.
Comment: Eu ja me perguntei se não poderia ser isso @LucasCosta.... Mas ai queria saber se alguém tem uma saída...
Answer: Não há maneira de prevenir a saída para o console.
Se você deseja forçar a limpeza completa do log, utilize
console.clear();

Entretanto isso eliminará todas as linhas, não apenas a última.
Answer: .catch(function(err, status){
    if (status === 401) return;
    console.log('algo diferente de 401');
});

Comment: eu não quero logar uma mensagem diferente... eu só não quero que logue nada.... Eu já dou o retorno de algo deu errado no front, para o usuário
Comment: @fernandoocf, não é o caso de só remover o `console.log` ou na verdade você está procurando por outra coisa?
Comment: vou tentar postar uma imagem pra vcs
Comment: Eu quero tirar essa maldita linha... pq como se trata de um input, o usuário pode errar várias vezes e acaba enchendo o console de erros...
Comment: Não é possível. Vai aparecer e "pronto", qualquer request com status >= 400 vai aparecer ali.


How is a DB supposed to keep an eye on the receiver's "hips"?

Question: When coaches tell me to keep the eyes on the receiver's hips, I find that impossible. I can't see his hips because they're covered by the pads, or by the jersey, or by a long shirt in practice.
How the heck am I supposed to watch his hips? I end up watching how he is generally going to turn, which doesn't fail - but the hips advice has never worked for me.
Comment: My guess is that this is kind of like http://en.wikipedia.org/wiki/Battle_of_Bunker_Hill#.22The_whites_of_their_eyes.22 "don't fire till you see the whites of their eyes". It's not meant to be taken literally, but intended as a reminder of a key point (don't get excited and shoot too soon). In your case, the coach is telling you to ignore the receiver's arms, head and in particular where he's looking, as these are all things use to fake the direction he's about to go. Once his hips and torso are moving, he's not faking. Take this general advice, not the specific wording.
Comment: Correct Spinner! I am referring primarily to cornerbacks as well, because they mostly cover man-to-man.
Comment: The hip area is the centre of gravity, so the action of turning **starts** there.
Comment: @skullpatrol, that doesn't answer my question.
Comment: You keep your eyes on the beltline area.
Comment: I find that impossible. I can't see his hips because they're covered by the pads, or by the jersey, or by a long shirt in practice.
Comment: Just a quick note, watching the hips of your opponent is really not that specific to american football, but essentially in any sport where the attacker needs to shake off a defender by a fake movement, hips will be your guide to judge the _true intent_ of the opponent. It is crucial for a defender in football, when the opponent is running at your with the ball, and of course also very important for goalkeepers when saving penalties.
Answer: It's a simplification of a bunch of ways to avoid route running techniques. Basically, coaches just don't want you to key on the upper body or feet as a simple head-fake or shuffle could cause you to over-commit.
I don't think they expect full focus on the receivers hips at all times such as when the ball's in the air. At some point you're going to have look at the receivers eyes and spot the ball yourself too. Rather, the point of keying on the hips is to not get fooled by a receiver's break. If he's running a post, your coach wants you to take the turn and drive of the hips as a sign that the receiver's made his break, not the shoulder and head fake he just made for an out. Once the receiver has made his break to commit to his route, the emphasis on watching the hips diminishes. He's going to look for the ball and you're going to now recover and close down the angle. Barring a broken play, the receiver is probably not going to work you one on one again as he's instead trying to provide a throwing target.
BTW, this is why receivers who can run a double move are often successful. They make one cut, changing their hip direction to sell the DB on one route and then drive hard into their real route. If they're quick and strong enough to make a successful second break, you will often be out of position because you did read his hips correctly!


Change  text if element is :hidden or :visible

Question: I have a button that toggles the playlistHolder div. In addition, when '.albumImage a' is selected, it also unhides the playlist. I am trying to change the text of the button to 'Show Playlist' if the playlist is hidden and 'Hide Playlist' if it is not hidden. I have tried click functions with if(('.playlist').is(:hidden)) but have not had any luck with getting it to work. I am new to Jquery so I understand that my code below can use much improvement, here is my setup now that works when the album image is selected as well as when the toggle button is selected without changing the text:
HTML

    <button id="togglePlaylistBT">Show/Hide Playlist</button>

Now Playing

Javascript/JQuery
$('#togglePlaylistBT, .albumImage a').on('click', function() {
                var $this = $('#togglePlaylistBT');
                if($('.playlistHolder').is(':visible'))
                {
                    $('.playlistHolder').hide('slow');
                    $this.text('Hide Playlist');
                }
                else
                {
                    $('.playlistHolder').show('slow');
                    $this.text('Show Playlist');
                }
            });

Comment: `but have not had any luck with getting it to work.` What do you mean? Do you get any error at all?
Comment: Why can't you change the text at the same time as you hide/show the playlist?
Answer: Try this snippet of code:
    $('.togglePlaylist button').on('click', function() {
        var $this = $(this);
        if($('.playlistHolder').is(':visible'))
        {
            $('.playlistHolder').hide();
            $this.text('Hide Playlist');
        }
        else
        {
            $('.playlistHolder').show();
            $this.text('Show Playlist');
        }
    });

Working JSFiddle
Answer: When you hide and show the playlist just run document.getElementById("togglePlaylistBT").value="Show Playlist";
For example:

function change()
{
    var elem = document.getElementById("playlistButton");
    if (elem.value=="Open Playlist") { elem.value = "Close Playlist"; closeBox(); }
    else { elem.value = "Open Playlist"; openBox(); }
}

function openBox() {
    alert("open");
}

function closeBox() {
    alert("closed");
}
<input onclick="change()" type="button" value="Open Playlist" id="playlistButton"></input>

Make sure to change openBox() and closeBox() functions to your box code!


How to check if a correlation exists between a continuous independent and a binary dependent variable

Question: So this has been a headache for me. None of the resources I found could explain it in a manner I understand.
Having two sets of data:
x <- c(2, 4, 5, 6, 7, 8, 9, 9, 4, 5)
y <- c(0, 1, 0, 0, 0, 1, 1, 0, 1, 0)
df <- data.frame(x, y)

The y variable is binary and the x variable is continuous as you can see.
What I understand so far is that some machine learning models, like logistic regression, expect the log odds of the y variable to have a linear relationship with the y variable.
How would I make a plot that shows if they abide to this assumption or not and how would I read that plot? I prefer examples in R but any explanation you feel might contribute to my understanding is more than welcome.
Comment: You need a two-sample procedure with groups 0 and 1 determined by `y` and continuous variable in `x`.
Answer: One way to look at the data:
x <- c(2, 4, 5, 6, 7, 8, 9, 9, 4, 5)
y <- c(0, 1, 0, 0, 0, 1, 1, 0, 1, 0)

stripchart(x ~ y, meth="stack", ylim=c(.5,2.5), pch=19)
  abline(h=1.5, col="green2")

From the stripcharts, we can see that the data values for the two groups are not much different. If integer values given in x are rounded continuous variables, then a 2-sample t-test would be
appropriate, but with so much overlap between values for the
two groups, I would not expect significance. Output from running this test in R shows a P-value greater than 5%, so the two sample means, 5.67 and  6.25,
are not significantly different from each other.
t.test(x ~ y)

        Welch Two Sample t-test

data:  x by y
t = -0.359, df = 5.9956, p-value = 0.7319
alternative hypothesis:
   true difference in means is not equal to 0
95 percent confidence interval:
 -4.560011  3.393344
sample estimates:
mean in group 0 mean in group 1
       5.666667        6.250000

Here are somewhat similar data for which there is a highly significant difference between groups.
stripchart(x1 ~ y, meth="stack", ylim=c(.5,2.5), pch=19)
  abline(h=1.5, col="green2")

t.test(x1 ~ y)

        Welch Two Sample t-test

data:  x1 by y
t = -5.2824, df = 5.9956, p-value = 0.001865
alternative hypothesis:
   true difference in means is not equal to 0
95 percent confidence interval:
  -12.560011  -4.606656
sample estimates:
mean in group 0 mean in group 1
       5.666667       14.250000

Comment: You my friend are a hero. Could you by accident know anything about Wald's Test as well? I just learned this is a test that could be done to figure out if a independent variable can be used in a machine learning model to predict a dependent variable.
Comment: Sorry not sure about that reference. Wald was very prolific, so I'm not sure how to narrow it down by searching. Maybe include search word `asymptotic`.
Comment: No problem. Just out of curiousity. Does using jitter/points plots difference from using boxplots to see if they split up nicely? As that is my simplistic interpretation of what you are doing.


Display picture based on UDP message

Question: I'm new to Python and I'm trying to write a program that display image on an interface based on a received UDP message.
While I can do the two things separately I can't make it work together.
The reason is simple, the while loop of the UDP listener does not allow the tkinter's mainloop to happen and I can't find a way to make it work.
I'm also not sure about the image "delete" side of the code.
Can you help me to find the solution ?
Not sure if this is important but this is running on a Raspberry Pi.
Here is the code:
    from tkinter import *
    import socket
root = Tk()
canvas = Canvas(root)
canvas.pack()

UDP_PORT = 11000
UDP_IP = ""

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

photo1 = PhotoImage(file="test.gif")
photo2 = PhotoImage(file="ant.gif")

canvas.create_image(25, 25, image=photo1)

while True:
    data, addr = sock.recvfrom(1024)
    if data.decode() == "on":
        canvas.create_image(100, 125, image=photo2)
    elif data.decode() == "off":
        canvas.delete(photo2)

root.mainloop()

Thank you so much.
Vince.
Answer: If you want 2 things to happen at the same time you need to run 2 threads. The python threading module makes this very easy.
from threading import Thread

root = Tk()
canvas = Canvas(root)
canvas.pack()

UDP_PORT = 11000
UDP_IP = ""

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

photo1 = PhotoImage(file="test.gif")
photo2 = PhotoImage(file="ant.gif")

canvas.create_image(25, 25, image=photo1)

def listen_for_udp():
    while True:
        data, addr = sock.recvfrom(1024)
        if data.decode() == "on":
            canvas.create_image(100, 125, image=photo2)
        elif data.decode() == "off":
            canvas.delete(photo2)

t = Thread(target=listen_for_udp)
t.daemon = True
t.start()

root.mainloop()

(totally untested)
Comment: Thank you very much for the solution. It is working great now with threads. I just edit your solution to add the two missing Imports (my bad, they were out of the code section on my original email.
Comment: Just one last thing... The "canvas.delete" side of it does not work. I can add the image but cannot remove it.  Any idea? Thanks

Display picture based on UDP message


Como garantir que três condições sejam satisfeitas? Há uma maneira melhor de fazer?

Question: Programa que pergunta a idade, o peso e a altura de uma pessoa e decide se ela está apta a entrar pro exército. Para entrar, é preciso maior de idade, pesar mais ou igual 60 quilos e medir mais ou igual 1,70 metros.
print('='*5, 'Aliste-se no Exército Brasileiro', '='*5)

idade = int(input('Digite sua idade: '))
peso = int(input('Digite seu peso: '))
altura = float(input('Digite sua altura: ex:1.7 '))

apto = ' '

if idade >= 18:
    apto = '1'
else:
    apto = '0'

if peso >= 60:
    apto += '1'
else:
    apto += '0'

if altura >= 1.70:
    apto += '1'
else:
    apto += '0'

if apto == '111':
    print('Você está apto a alista-se no exército brasileiro, parabéns.')
elif apto == '011':
    print('Você não possue Idade sulficiente para ingressar no exército.')
elif apto == '101':
    print('Você não possue peso sulficiente para ingressar no exército.')
elif apto == '110':
    print('Você não possue altura sulficiente para ingressar no exército.')
elif apto == '100':
    print('Você não possue nem Peso nem Altura sulficiente para ingressar no exército.')
elif apto == '001':
    print('Você não possue nem Idade nem Peso sulficiente para ingressar no exército.')
elif apto == '010':
    print('Você não possue nem Idade nem Altura sulficiente para ingressar no exército.')
else:
    print('Você não possui nenhum dos requisitos para entrar no Exército')

Answer: A ideia é apenas verificar se está apto ou não a partir de 3 condições. Para tal, ao invés de criar uma string com três valores e depois verificar todas as possibilidades, você pode usar a função all:
idade = int(input('Sua idade: '))
peso = float(input('Seu peso: '))
altura = float(input('Sua altura: '))

apto = all([
    idade >= 18,
    peso >= 60,
    altura >= 1.70
])

Assim, apto será True quando as três condições forem satisfeitas ou False em todos os outros casos.

Dada a nova informação que as mensagens também são necessárias, o que você pode fazer é algo como:
idade = int(input('Sua idade: '))
peso = float(input('Seu peso: '))
altura = float(input('Sua altura: '))

apto = True

if idade < 18:
    print('Você precisa ter, pelo menos, 18 anos')
    apto = False

if peso < 60:
    print('Você precisa ter, pelo menos, 60 quilos')
    apto = False

if altura < 1.70:
    print('Você precisa ter, pelo menos, 1.70 m de altura')
    apto = False

if apto:
    print('parabéns, você está apto a alistar-se')

Ao final, se alguma condição não for satisfeita, apto será False.
Comment: É, mas eu esqueci de relatar q é preciso informar no script em que quesito o candidato (ao exército) falha, idade, peso ou altura ou duas das ou as três...
Comment: Silas, e precisa ser em apenas um texto ou podem ser múltiplas mensagens? Por favor, edite a sua pergunta e adicione este detalhe no enunciado.
Comment: Não. Agora, está perfeito! rsrs.
Answer: Pegando a idéia do Anderson Carlos Woss:
print('='*5, 'Aliste-se no Exército Brasileiro', '='*5)
idade = int(input('Sua idade: '))
peso = float(input('Seu peso: '))
altura = float(input('Sua altura: '))
printe = ''
apto = True
if idade < 18:
    printe = 'Você precisa ter, pelo menos, 18 anos'
    apto = False
if peso < 60:
    printe += '\nVocê precisa ter, pelo menos, 60 quilos'
    apto = False
if altura < 1.70:
    printe += '\nVocê precisa ter, pelo menos, 1.70 m de altura'
    apto = False
nenhum_requisito = all([
    idade < 18,
    peso < 60,
    altura < 1.70
])
if nenhum_requisito:
   printe ='Você não possui nenhum dos quesitos para se alistar!'
if apto == True:
    printe = 'parabéns, você está apto a alistar-se'
print(printe)

OU TALVEZ:
print('='*5, 'Aliste-se no Exército Brasileiro', '='*5)
idade = int(input('Sua idade: '))
peso = float(input('Seu peso: '))
altura = float(input('Sua altura: '))
printe = ''
nenhum_requisito = ''
apto = True
if idade < 18:
    printe = 'Você precisa ter, pelo menos, 18 anos'
    apto = False
if peso < 60:
    printe += '\nVocê precisa ter, pelo menos, 60 quilos'
    apto = False
if altura < 1.70:
    printe += '\nVocê precisa ter, pelo menos, 1.70 m de altura'
    apto = False
if idade < 18 and peso < 60 and altura < 1.70:
    nenhum_requisito = 'Você não possui nenhum dos quesitos para se alistar!'
    printe = nenhum_requisito
if apto == True:
    printe = 'parabéns, você está apto a alistar-se'
print(printe)

Não sei qual o melhor script, apostaria no primeiro. Se alguém poder avaliar...