Is the OLS estimator ${w} = ({X}^T{X})^{-1}{X}^T{y}$ or ${w} = ({X}{X}^T)^{-1}{X}{y}^T$?

Question: the closed form solution of the weights for the ordinary least squares problem is given by $\mathbf{w} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}$. This is the almost 'universal' form that I have found in all derivatives and textbooks, except for one source.
In this source:
https://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote08.html, however, the least squares solution is given by $\mathbf{w} = (\mathbf{X}\mathbf{X}^T)^{-1}\mathbf{X}\mathbf{y}^T$.
I am trying to show these two are equivalent, but not successful.
I took the transpose of the first form, but I only have: $\mathbf{w} = \mathbf{y}^T\mathbf{X}(\mathbf{X}\mathbf{X}^T)^{-1}$. Is there any additional assumption here?
Comment: In the source you quote the model is *explicitly* written in terms of $w^\prime$ rather than $w.$  Thus, you need to transpose everything when relating it to models written in terms of $w.$  It's important to read the details!  That source, btw, is (grievously) remiss in not distinguishing the parameter vector $w$ from its estimate.  Therein lies the source of many misconceptions about regression and statistical procedures generally.
Answer: In the second form, the authors transposed $X$ compared to the first form. In other words:

in the first form, the rows are observations and the columns are features;
in the second form, the rows are features and the columns are observations.


Jira Groovy Script Numeric Textbox value

Question: I use Jira 4.0
Jira has a meaning on numeric textbox.
I'm checking in the Groovy Script this space and I assign a variable as below.
 value = (String)WorkflowUtils.getFieldValueFromIssue(issue, WorkflowUtils.getFieldFromKey("customfield_10507")) ?: ""

If the value I assign to  "value" variable, which is written on customField, is greater than 200 as shown above, it should execute.
Example:
  if (value > 200)
  {}
  else if (value < 200)
  {}

My issue is that it detects it as smaller than 200 if the first digit of the number is smaller than 2, such as:
value = 10 – 100 – 150 – 165 – 1000
For instance; When I type 45,30,50,89 it accepts it as greater than 200
Answer: You need to cast the value to Integer. Use toInteger() method on non-empty String object.
It should be something like:
def value = (String) WorkflowUtils.getFieldValueFromIssue(issue,WorkflowUtils.getFieldFromKey("customfield_10507"))
def valueNum = value?.isNumber() ? value.toInteger() : 0//You may change the default value

Comment: Hi Opal,how to syntax?
Answer: Solution:
value = '56.0'
value2 = value.replace(".0", "");
int convertedNumber = Integer.valueOf(value2).intValue()
if (convertNumber > 200)
{}
else if (convertNumber < 200)


How to draw graphs of functions?

Question: I have knowledge in programming language C++..However I want to draw graphs of various functions such as $\sin\dfrac{1}{x},x\sin\dfrac{1}{x}$ etc.
Is there any available software that can be run on Windows $7$ for download for plotting these functions
Or can I use C to run programs for plotting them?
I searched on the web ;alternatives are available for Linux etc.
Please do tell me any other alternatives available for windows $7$ operating system
Comment: gnuplot is free.
Comment: Matlab,python,mathematica
Comment: Microsoft Mathematics. Free, powerful, easy.
Comment: You might want to try out the free online service http://www.fooplot.com
Comment: Or even [Geogebra](https://www.geogebra.org), which is free.
Comment: [gnuplot](http://www.gnuplot.info/), free online services like [SageMathCloud](https://cloud.sagemath.com/), [SymPy Gamma](http://www.sympygamma.com/)
Comment: [Asymptote](http://asymptote.sourceforge.net) uses C++ - like language
to create high-quality 2D and 3D technical drawing, using (La)TeX to handle text labels.
It's also free, open-source.
Comment: Definitely gnuplot. Incredibly easy, open source, and everybody uses it.
Answer: Desmos,Wolfram Alpha,gnuplot ,Geogebra,Microsoft Mathematics,Matlab,FooPlot,GraphSketch,MAFA Function Plotter.

How to draw graphs of functions?


Show that $23a^2$ is not the sum of 3 squares.

Question: I know that Legendre's theorem states that a number is expressible as a sum of 3 squares iff. it's not of the form $4^x (8m+7)$, so I need to show that $23a^2$ is of this form, how could I go about doing this?
Comment: Write $a$ as $2^k \times r$ for odd $r$, then show that $r^2 \equiv 1 \pmod 8$.
Comment: In general, it's helpful to try an expression like $23a^2$ for various small values of $a$, seeing how the factorization works for each one.  Where does the $4^x$ comes from?  Where does the $8m+7$ come from?
Answer: Note that $4^x(8m + 7)$ is a product of two terms:

a power of $4$, and
the remaining odd part.

This motivates assuming $a$ to be of the form $2^xr$ where $r \ge 1$ is odd and $x \ge 0$. (Both $r$ and $x$ are integers.)
Note that every integer can indeed be written in the above form (in a unique manner).
Now, we get that $a^2 = 4^xr$. This is promising because we have gotten a $4^x$ term.
This shows that
$$23a^2 = 4^x(23r^2).$$
Now, we need to show that $23r^2$ is of the form $8m + 7$. Note that $23 = 8\cdot2 + 7$.
So, if we can show that $r^2$ is of the form $8k + 1$, then we would be done.
This can be done easily by exhaustion.
Since $r$ is odd, there are only the following possibilities for $r$:
$r$ is of one of the following forms:

$8k + 1$
$8k + 3$
$8k + 5$
$8k + 7$

You can square each and verify that $r^2$ is always of the form $8k + 1$. Thus, $23a^2$ further simplifies as
$$\begin{align}23a^2 &= 4^x(23r^2)\\
&=4^x(23(8k+1))\\
&=4^x(23\cdot8k + 16 + 7)\\
&=4^x((23k + 2)\cdot8 + 7)\\
&= 4^x(8m + 7),\end{align}$$
as desired.
Comment: Just a comment that you can reduce the work to showing that $r^2 \equiv 1 \pmod 8$ by either (a) looking at just $r = 4q+1$ and $r = 4q+3$; or (b) looking at just $r = 2q+1$, and showing that $q^2+q$ is always even.
Comment: @Aryaman Thanks, why  do we need to show $r^2$ is of the form $8k+1$ as opposed to $8k+7$?
Comment: If $a$ and $b$ are both of the form $8k + 7$, then their product is of the form $8k+1$. (See that $49$ leaves a remainder of $1$ when divided by $8$.) Since $23$ was of the form $8k+7$, you couldn't have had $r^2$ to be of that form as well. (Similar argument would rule out the forms $8k+3$ and $8k+5$ as well.)
Comment: However, note that that was just a motivation/foresight. The "methodical"  way would be to see what possible values can $r^2$ take modulo $8$ and then verify that $23r^2$ is indeed of the form $8m+7$.
Answer: If a number $n$ is of this form, then:
$$n = 4^x \left(8m + 7\right) = 4^x \cdot 8m + 7 \cdot 4^x = 23a^2$$
Therefore
$$n \equiv 7 \cdot 4^x \equiv \begin{cases}0 & \text{if } x > 1 \\4 & \text{if } x = 1\\7 & \text{if } x = 0\end{cases}\pmod{8}$$
and
$$n \equiv 23 a^2 \equiv \begin{cases}0 & \text{if } a \equiv 0 \pmod{4}\\4 & \text{if } a \equiv 2 \pmod{4}\\7 & \text{if } a \text{ is odd}\end{cases}\pmod{8}$$
Lets bust the case where $n \equiv 7 \pmod{8}$. It means that $a$ is odd. So $23a^2$ is odd, too. However $4^x \left(8m + 7\right)$ is even. Because $n$ can't be even and odd at the same time, it is a contradiction.
Next case: $n \equiv 4 \pmod{8}$
$$4 \left(8m + 7\right) = 23a^2 \quad a \in \{2,6,10,12,...\}$$
Because $\left(8m + 7\right)$ is not divisible by $4$, $a$ needs to be $2$, then:
$$8m + 7 = 23$$
Therefore $m = 2$.
So actually it is of the form!
$$4^1 \left( 8 \cdot 2 + 7 \right) = 23 \cdot 2^2$$
One possible solution: $x = 1$, $m = 2$, $a = 2$


which daemons are running?

Question: Runing snow leopard, I'd like to find a way to say:
"Right now, this is what's is running and this is who is running it"  I've enabled process accounting and auditing, which should tell me this, but I thought I'd ask here to see if there were other insights.
So, how can I quickly find out which daemons are running, besides using launchctl list?  Or is there a way to modify that somehow to get a list of the running daemons?
Answer: ps aux

in console :D
OR
top

for a live view
Comment: Right... but here's the thing:  Those tools work, yes, but there is an almost dual nature to osX I'm finding.  My mental model is exactly that, find, top, etc. I work with linux mostly, and I'm familiar with BSD.  However launchd and the rest of the osX stuff especially DirectoryServices, is a bit odd to me, and recently it's been hammered home that even though macports makes me feel like it's linux, I am missing a great deal by sticking to familiar tools.  I greatly dislike all this stuff running, thus my initial question.
Comment: oh how i feel your pain moving from ubuntu to osx.. however im slowly enjoying the change :)
Comment: It's quite nice. I was debating moving back to linux a while ago, but realistically, that's just crazytalk ;) However, launchctl should do it all, it's supposed to be running everything.
Comment: Did i help with your question / convincing you to admire OSx a little??
Comment: You misunderstand me I think.  I loved it before, but now I am fascinated by it.  IMO best OS ever, far better that iOS.  I'm actually going stop ssh'ing into places and sshfs them down to me, so i can stay in it all the time ;)
Answer: Apologies about the self answering, but the BSD/Mach semantics are below the launchd stuff.
From the security manual:

Listing Active Daemons and Agents on the System

To see a list of the daemons managed by launchd, run the following command:
$ sudo launchctl list

Agents are programs that run in the background on behalf of a user, to provide services to that user. To see a list of the agents managed by launchd for you (since you are the current user), run the following command:

$ launchctl list

I highly recommend reading this manual, btw.   Page 223 tells you how to disable the
Remote Management and Screen Sharing daemons/agents.
Running by default, no less.
From "Snow Leopard Security Config v 10.6 available on the apple.com site.

which daemons are running?


Defining the Product of Ideals

Question:
Where does the "naive definition" of the product of two ideals $I$ and $J$, $IJ = \{ ij \mid i \in I, j \in J \}$ fall apart?
(The product of two ideals $I$ and $J$ is defined to be $IJ := \sum_i a_ib_i$, where each $a_i$ is in $I$ and each $b_i$ is in $J$.)

Note: This is a question from a problem set I'm working on. I am not expecting a full solution for the answers, but I'd like some help knowing where to look. It seems to work fine in $\mathbb{Z}$ and $\mathbb{C}[x]$.
Comment: Since it seems that the question from your problem set is precisely to explain where the naive definition goes awry, I've made it into a block-quote so it is clear that this is the homework speaking, and not you (it is not entirely clear to me if your assigment might instead be to work with the definition $IJ=\sum a_ib_i$, but **you**, on your own initiative, are wondering why the "naive definition" does not work).
Answer: Suppose $I=J=(x,y)\subseteq \mathbb R[x,y]$. Then $x^2$ and $y^2$ are in your naive definition, but their sum is not.
It is an enlightening exercise to try to see what exactly $\mathbb Z$ and $\mathbb C[x]$ have that make the naive definition work...
Comment: @Michael: if you can prove that the naive definition does work in a principal ideal domain, then yes. If not, no :=)
Comment: Is it because they are principal ideal domains? That seems to be the common thread I see.
Comment: @Michael: Principal ideal rings will suffice; they don't have to be domains.
Comment: Also, finding an example which is not a principal ideal domain but where nonetheless the naive definition works is a good exercise.
Comment: @MarianoSuárez-Alvarez I wonder what is (x,y) in R[x,y]? do you mean the polynomial rings with 2 variables? Thanks!
Comment: R[X,y] is the standard notation for the polynomial ring in the variables x and y, and (x,y) is the standard notation for the ideal generated in that ring by x and y. This is completely standard notation.
Answer: I think you'll find of interest my old sci.math post below.

From: Bill Dubuque
Date: 30 Jul 2003 23:54:07 -0400
Message-ID:
Bill Dubuque  wrote:

Rasmus Villemoes  wrote:
  >

In my algebra textbook, the product of two ideals I,J is defined as
{ sum_{i=1..n} a_i b_i | n >= 1 , a_i in I and b_i in J }
Now it is rather easy to prove that IJ is an ideal in R. The last
    question of the exercise is:
Is A = { ab | a in I, b in J } an ideal of R.
Now the preceding questions strongly suggest that the answer in
    general is no, but I can't find a counterexample. Clearly, (since it
    is understood that R is commutative), if one of I or J is a principal
    ideal, the set A is an ideal, so a counterexample has to consist of a
    non-PID and two ideals generated by at least two elements each  [...]

HINT: Find proper ideals whose product contains an irreducible element,
e.g.  p in (p,a)(p,b)  if  (a,b) = (1)
Examples abound.

Domains where ideals multiply simply as  IJ = { ij : i in I, j in J },
are called condensed domains. Below are reviews of related papers.

84a:13019  13F99
Anderson, David F.; Dobbs, David E.
On the product of ideals.
Canad. Math. Bull. 26 (1983), no. 1, 106-114.

In this paper the authors define an integral domain R to be a condensed
domain provided  IJ = {ij: i in I, j in J}  for all ideals I and J of R.
Bezout domains are condensed domains. The main results of the paper
characterize condensed domains within some large class of domains. For
example, it is shown that a GCD-domain is condensed if and only if it is
a Bezout domain, and a Krull domain is condensed if and only if it is a
principal ideal domain. For a Noetherian domain  R  to be condensed it
is necessary that  dim R <= 1  and that the integral closure of  R  be
a principal ideal.
       Reviewed by J. T. Arnold

86h:13017  13F05 (13B20 13G05)
Anderson, David F.(1-TN); Arnold, Jimmy T.(1-VAPI); Dobbs, David E.(1-TN)
Integrally closed condensed domains are Bezout.
Canad. Math. Bull. 28 (1985), no. 1, 98-102.

An integral domain  R  is termed quasicondensed if  I^n = {i_1 i_2...i_n :
i_j in I  for  1 <= j <= n}  for each positive integer  n  and each
two-generated ideal  I = (a,b)  of  R.  R  is said to be condensed if
IJ = {ij: i in I, j in J} for all ideals  I  and  J  of  R. The main theorem
shows that an integral domain is a Bezout domain if and only if it is
integrally closed and condensed. An example (a  D+M  construction) is given
of an integrally closed quasicondensed domain which is not a Bezout domain.
       Reviewed by Anne Grams

90e:13019  13F30 (13B20 13G05)
Gottlieb, Christian (S-STOC)
On condensed Noetherian domains whose integral closures are discrete
valuation rings.
Canad. Math. Bull. 32 (1989), no. 2, 166-168.

Following D. F. Anderson and the reviewer [same journal 26 (1983), no. 1,
106-114; MR 84a:13019] an integral domain  R  is said to be condensed in case
IJ = {ij : i in I, j in J}  for all ideals  I,J  of  R. The author defines an
integral domain  R  to be strongly condensed if for every pair  I,J  of ideals
of R, either IJ = aJ for some  a in I  or IJ = Ib for some  b in J. Suppose
henceforth that  R  is a Noetherian integral domain whose integral closure  R'
is a discrete valuation ring. It is proved that if  R  is condensed, then  R
contains an element of value 2 (in the associated discrete rank 1 valuation).
It is not known whether the converse holds, nor whether all condensed domains
are strongly condensed. As a partial converse, it is proved that R is strongly
condensed under the following conditions: (R',M')  is a finitely generated
R-module,  R'/M' is isomorphic to  R/M  and R contains an element of value 2.
       Reviewed by David E. Dobbs

1 955 608  13A15 (13Bxx)
Anderson, D. D.; Dumitrescu, Tiberiu
Condensed domains.
Canad. Math. Bull. 46 (2003), no. 1, 3-13.
http://journals.cms.math.ca/cgi-bin/vault/view/anderson8107

Abstract:
An integral domain D with identity is condensed (resp., strongly condensed) if
for each pair of ideals I,J of D, IJ = {ij : i in I, j in J} (resp., IJ = iJ
for some i in I or IJ = Ij for some j in J). We show that for a Noetherian
domain D, D is condensed if and only if Pic(D) = 0 and D is locally condensed,
while a local domain is strongly condensed if and only if it has the
two-generator property. An integrally closed domain D is strongly condensed
if and only if D is a Bezout generalized Dedekind domain with at most one
maximal ideal of height greater than one. We give a number of equivalencies
for a local domain with finite integral closure to be strongly condensed.
Finally, we show that for a field extension k < K, the domain D = k + XK[[X]]
is condensed if and only if [K:k] <= 2 or [K:k] = 3 and each degree-two
polynomial in  k[X] splits over  k, while D is strongly condensed if and
only if [K:k] <= 2.
Answer: If you read Remark 2.7 of my paper "On a property of pre-Schreier domains"
[Comm. Algebra 15 (1987) 1895-1920] you would find that the question of
discrepancy between products of two ideals $A,B$ $(AB=\{\Sigma $ $%
a_{i}b_{i}|a_{i}\in A,b_{i}\in B\}$ in a ring and the product of two ideals $%
I,J$ $(IJ=\{a_{i}b_{i}|a_{i}\in I$ and $b_{i}\in I\}$ in a semigroup was
raised in the above mentioned paper of mine. I was naive and thought
everyone was my friend. So I would send preprints of even half written
papers around. I have a feeling that the Anderson-Dobbs paper, that is
mentioned by Bill Dubuque, was an effort to lift the idea from a pre-print
of the above paper with very little credit (they do mention the pre-print,
but without giving a clue to why they mention a result from Zafrullah.) At
the end of that remark I do mention the Anderson-Dobbs' paper. I think I
handled it beautifully, mentioning the heist and at the same time praising
it. But now I am bitter, as I don't see any light at the end of the tunnel.
For as I look back I see this kind of activity around most of my solo
papers. In any case, the property $\ast $ came right out of this discussion
of the discrepancy of the definitions of products of ideals. Recall that a
domain $D$ is a $\ast $-domain if $((\cap (a_{i}))(\cap (b_{j}))=\cap
_{ij}(a_{i}b_{j})$ for all $a_{1},...,a_{n},b_{1},....b_{m}\in D$
equivalently, $\in K=qf(D).$ I address an effort to lift the $\ast$-property in https://lohar.com/mithelpdesk/hd2006.pdf
Anyone interested in products of ideals or pre-Schreier domains may like to
study the $\ast $-property, as a Prufer domain has the $\ast $-property and
a so called Prufer $v$-multiplication domain (PVMD) that is a $\ast $-domain
is a locally GCD domain.

Defining the Product of Ideals


Why does writing to file change the content (hash)?

Question: I noticed, that when trying to generate some hashes after copy-pasting them into a file with vim, the hash is not as it is supposed to be. Same when file was opened and written out. Same behavior with nano, so there must be something I am mising.
$ echo -n  "foo" | openssl dgst -sha256
2c26...e7ae
$ echo -n "foo" > hash.txt
$ openssl dgst -sha256 hash.txt
SHA256(hash.txt)= 2c26...e7ae

But when I open hash.txt with nano or vim and quit without inserting anything, I subsequently get the following hash: b5bb...944c
I also noticed that without opening the file and writing out I do not see the output when using cat or head. Was the encoding changed?
Comment: Somehow you inserted a newline into the file. In any event, I cannot reproduce your results.
Comment: `echo foo | openssl dgst -sha256` => b5bb…4944c. This is the same `foo` with a newline.
Answer: Most text editors, including Vim, save the file with a newline at the end when you quit.  That's because according to POSIX, a text file is either empty or ends with a newline, so most users expect and want that behavior.
As you've noticed, adding a newline at the end changes the hash, and the hash you're getting is consistent with the sequence foo\n, where \n is a newline.
If you have a recent enough Vim, you can control the behavior mentioned above by setting nofixeol, which will preserve the existing line ending, or lack thereof, on the last line.
Comment: I believe without `nofixeol`, `noeol` is documented to work only with `binary`.


Comparar horário atual com valores de um arquivo

Question: Estou tentando pegar uma lista de horários de um arquivo (Já consegui), e agendar conforme o horário: compra programada para as 15:30, neste horário vou executar a compra (API.Buy)
# alimentação
sinal vem do arquivo TXT
lista = (23,5,2020,18:10,EURJPY-OTC,PUT)
today = datetime.today()

for sinal in lista:
    dados = sinal.split(',')

    # Divide variáveis
    dados[3] = datetime.strptime(dados[3], '%H:%M').time()

    #compara horários
    if(dados[3]==today):
        API.buy(entrada,dados[4],dados[5],5)
        #valor, moeda, direção, tempo;

print("Operação efetuada...")

Answer: A comparação de horário que você está fazendo não vai funcionar.
Quando você faz o parsing de uma string que só tem a hora e o minuto ('%H:%M'), o segundos e frações de segundo são setados para zero. Além disso, o método time() retorna um datetime.time, ou seja, um objeto que só contém os campos de horário, independente do dia. Ex:
print(datetime.strptime('18:30', '%H:%M').time()) # 18:30:00

Mas quando você usa datetime.today, o horário contém a hora atual, incluindo os segundos e frações de segundo:
print(datetime.today()) # 2020-07-27 09:28:57.649383

Além disso, today retorna também a data (dia, mês e ano). Ou seja, mesmo que as horas e minutos sejam iguais, os demais campos não serão.
Por isso, para a comparação funcionar, precisamos extrair apenas os campos de horário de today e setar os segundos e frações de segundo para zero, usando replace:
# pega somente o horário com time(), e seta os segundos e frações de segundo para zero com replace()
today = datetime.today().time().replace(second=0, microsecond=0)

for sinal in lista:
    dados = sinal.split(',')
    dados[3] = datetime.strptime(dados[3], '%H:%M').time()
    # compara horários
    if(dados[3] == today):
        # etc...


Uso de attr para aplicar cor de borda em LI

Question: Possuo uma li, que é um quadrado, o CSS está assim
.produtos{
    width: 294px;
    height: 349px;
    /*background-color: #f1f2f2;*/
    border: 3px solid transparent;
    position: relative;
    cursor: pointer;
    transition: all .4s ease-out;
    background-repeat: no-repeat;
}

O que acontece, é que quero mudar o cor do border quando o usuário passar o mouse em cima.
Não posso fazer isso com o hover simples do CSS, pois essa cor será gerenciável. Já tenho uma palavra reservada que irá aplicar essa cor, só acho que o ideal seria usar um attr em Jquery, estou certo?
Meu HTML está assim:

codigoSYS é o valor hexadecimal da cor que é recebido pelo gerenciador.
Jquery:
var cor = $('.produtosBorda').attr('data-cor');
$('.produtosBorda').css('border-color', cor);

Comment: Tem como colocar um trecho do código html, o css e um exemplo de como ficaria o resultado final?, porque talvez tenha várias soluções ai se pode escolhe a melhor ao seu código!
Answer: Não, use o método .css() em vez do attr. Por exemplo:
$('li').css('border-color', '#00ff00');

Se a cor vier de um data-attribute no seu HTML, não tem problema. Por exemplo:

...

var cor = $('#sei-la').attr('data-cor');
$('#sei-la').css('border-color', cor);

Para reagir à entrada e saída do mouse em cada
, algo assim deve funcionar:
$('li.produtos').mouseenter(function() {
    var li = $(this);
    // guarda cor original num atributo
    li.attr('data-cor-original', li.css('border-color'));
    // define nova cor
    li.css('border-color', li.attr('data-cor'));
}).mouseleave(function() {
    var li = $(this);
    // restaura cor original
    li.css('border-color', li.attr('data-cor-original'));
});

Comment: Você está falando de data-attributes? Atualizei minha resposta, veja se é isso.
Comment: Editei a resposta novamente, @FelipeStoker
Comment: Cara, ficou PERFEITO! Muito obrigado!
Comment: Obrigado pela resposta. Eu gostaria de usar um `attr`, pois como eu comentei, essa cor será gerenciável pelo usuário. Por isso, eu não posso definir a cor da borda com com jquery, e sim no HTML. Acredito eu.
Comment: Exatamente isso! Nota 10. Só tem duas coisas, que agradeceria se você pudesse me ajudar. Tenho uma listagem de elementos e ele está aplicando apenas no primeiro item. Segundo, ele tem como aplicar apensa no :hover?
Comment: Você está fazendo o hover por jquery, @FelipeStoker? O exemplo que dei usa um ID para escolher o li que será afetado, mas qualquer seletor funcionaria. Fica difícil dizer o que usar no seu caso sem ver mais do seu código. Você poderia atualizar a pergunta?
Comment: Oi, como é uma listagem de repetição, eu tirei o ID e coloquei na classe. Funfou, porém ele aplica a mesma cor para todos. Editei minha pergunta.


Routing Error No route matches [GET] "/microposts/304 - Deleting a Micropost - Michael Hartl's railstutorial.org Chapter 11

Question: I'm working through Michael Hartl's Ruby on Rails tutorial on http://ruby.railstutorial.org.  I'm having trouble with Chapter 11, specifically when attempting to delete a micropost.
I'm having the same problem as this user Routing Error No route matches [GET] "/microposts/304".  He was able to solve the problem by commenting out the jQuery gem and it worked.  I, however, wasn't as lucky.
Here is my current Gemfile:
source 'http://rubygems.org'

gem 'rails', '3.1.1'

# Bundle edge Rails instead:
# gem 'rails',     :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'
gem 'gravatar_image_tag', '1.0.0.pre2'
gem 'will_paginate', '3.0.pre2'

gem 'jquery-rails'
gem 'pg'

group :development do
  gem 'faker', '0.3.1'
end

# Gems used only for assets and not required
# in production environments by default.
#group :assets do
#  gem 'sass-rails',   '~> 3.1.4'
#  gem 'coffee-rails', '~> 3.1.1'
#  gem 'uglifier', '>= 1.0.3'
#end

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'

group :test do
  # Pretty printed test output
  gem 'turn', :require => false
end

=> A quick side-note: An error No Javascript runtime on windows when running rails server kept arising when I ran the rails server command but once I commented out the 'sass-rails', 'coffee-rails', and 'uglifier' gems it would run successfully.  I'm using a Windows PC and was told that this might be a specific problem to Windows machines.
Also, here is the current outcome of my bundle install command:
Using rake (0.9.2.2)
Using multi_json (1.0.3)
Using activesupport (3.1.1)
Using builder (3.0.0)
Using i18n (0.6.0)
Using activemodel (3.1.1)
Using erubis (2.7.0)
Using rack (1.3.5)
Using rack-cache (1.1)
Using rack-mount (0.8.3)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.0.3)
Using actionpack (3.1.1)
Using mime-types (1.17.2)
Using polyglot (0.3.3)
Using treetop (1.4.10)
Using mail (2.3.0)
Using actionmailer (3.1.1)
Using arel (2.2.1)
Using tzinfo (0.3.31)
Using activerecord (3.1.1)
Using activeresource (3.1.1)
Using ansi (1.4.1)
Using bundler (1.0.21)
Using faker (0.3.1)
Using gravatar_image_tag (1.0.0.pre2)
Using rack-ssl (1.3.2)
Using json (1.6.1)
Using rdoc (3.11)
Using thor (0.14.6)
Using railties (3.1.1)
Using jquery-rails (1.0.17)
Using pg (0.11.0)
Using rails (3.1.1)
Using sqlite3 (1.3.4)
Using turn (0.8.3)
Using will_paginate (3.0.pre2)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem
is installed.

I'm not sure how to solve this problem.  Is there a specific gem that I need to install in order for the delete method to work?  I appreciate your help!
Here is the rake routes output:
(in C:/rails_projects/sample_app)
      users GET    /users(.:format)          {:action=>"index", :controller=>"us
ers"}
            POST   /users(.:format)          {:action=>"create", :controller=>"u
sers"}
   new_user GET    /users/new(.:format)      {:action=>"new", :controller=>"user
s"}
  edit_user GET    /users/:id/edit(.:format) {:action=>"edit", :controller=>"use
rs"}
       user GET    /users/:id(.:format)      {:action=>"show", :controller=>"use
rs"}
            PUT    /users/:id(.:format)      {:action=>"update", :controller=>"u
sers"}
            DELETE /users/:id(.:format)      {:action=>"destroy", :controller=>"
users"}
   sessions POST   /sessions(.:format)       {:action=>"create", :controller=>"s
essions"}
new_session GET    /sessions/new(.:format)   {:action=>"new", :controller=>"sess
ions"}
    session DELETE /sessions/:id(.:format)   {:action=>"destroy", :controller=>"
sessions"}
 microposts POST   /microposts(.:format)     {:action=>"create", :controller=>"m
icroposts"}
  micropost DELETE /microposts/:id(.:format) {:action=>"destroy", :controller=>"
microposts"}
     signup        /signup(.:format)         {:controller=>"users", :action=>"ne
w"}
     signin        /signin(.:format)         {:controller=>"sessions", :action=>
"new"}
    signout        /signout(.:format)        {:controller=>"sessions", :action=>
"destroy"}
    contact        /contact(.:format)        {:controller=>"pages", :action=>"co
ntact"}
      about        /about(.:format)          {:controller=>"pages", :action=>"ab
out"}
       help        /help(.:format)           {:controller=>"pages", :action=>"he
lp"}
       root        /                         {:controller=>"pages", :action=>"ho
me"}

Here is a partial view file using the delete method:

    <%= micropost.content %>

      Posted <%= time_ago_in_words(micropost.created_at) %> ago.

  <% user = micropost.user rescue User.find(micropost.user_id) %>
  <% if current_user?(user) %>

    <%= link_to "delete", micropost, :method => :delete,
                                     :confirm => "You sure?",
                                     :title => micropost.content %>

  <% end %>

Again, the source code can be viewed on Github https://github.com/railstutorial/sample_app, it just seems to not be running properly on my machine which leads me to believe it is something along the lines as this user's problem.
Comment: What's your output for `rake routes`?
Comment: Also, what is the view code you're using to output the link/button/whatever that deletes the post?
Comment: @sarnold: I was using rake 0.9.2 and running `rake routes` didn't work.  So, I followed this  example and switched to rake 0.8.7 and `rake routes` worked.  I appended it to the question.
Comment: @BrandonTilley:  I added the view partial which is calling the delete function.  Let me know if you need other files.  Thanks for you time!
Comment: http://stackoverflow.com/a/8524693/1092806
Answer: I think you are missing one of these two.
//= require jquery
//= require jquery_ujs

I accidentally removed  //= require jquery_ujs and this gave me the same problem.
Comment: I made the same mistake, saw your pointer here and voila! Problem solved!
Comment: @NickLewis nice, i could help. can you please vote my answer up.
Answer: Are you using both prototype and jquery in your app?
I can see that you are using jquery-rails gem, but is the prototype also present there?
Check if both are being loaded, as they clash with each other.
Comment: I tried switching the microposts_controller method to `delete`, didn't work.  Then I tried switching the views to `:destroy`, didn't work.  Hmm...
Comment: I installed `gem 'prototype-rails' '3.1.0'`, but the delete function didn't work - it gave me the same error message.  I then commented out the jQuery gem and tried running it again but still no success.  Do you think it has to do with the error message I received when attempting to do the `rails server` command early in development stating, ["Could not find a Javascript runtime."](http://stackoverflow.com/questions/8047651/no-javascript-runtime-on-windows-when-running-rails-server)?


Does hand perspiration prevent you from becoming a good guitarist?

Question: My hands have a lot of perspiration (not enough to drop, but enough to become wet). I want to play guitar, but a friend of mine told me that I can't, since my hands are wet. I don't know is it true of not, as I have no idea about playing guitar (or any string-based instrument) yet. He says that my hands would slip on strings especially when playing high tempo pieces like Austrias or Alhambra.
Is he right? Does becoming a gGuitarist depend on dry hands?
Answer: Your friend is incorrect - the only obvious effect sweaty hands will have is that metal strings will rust faster, and nylon strings may stretch.
It can be annoying, sure, but there are ways around it; see the habit of many rock guitarists of wearing  absorbent wristbands. Also you could use climbers chalk if you found you were dropping your plectrum because of sloppy fingers.
Answer: No, that doesn't make any sense.  There's no real way for your fretting hand to slip uncontrollably — if you're chording, you have a firm position without much lateral force, and if you're sliding around then you're, um, sliding around.  If you're not playing with a pick, then you should mostly be using your fingernails to pick the strings and they won't be particularly affected by sweat.  If you are using a pick then it might be slightly harder to hang on to but it won't be a big deal.
You might need to clean your guitar a little better though!
Answer: It might be a problem years from now if you want to be the world's fastest, most technical master of the guitar ever. It won't be a major issue now, at least it probably won't prevent you from enjoying yourself.
If you feel you need to, you might try applying some anti-perspirant to your palm.


lmer or binomial GLMM

Question: I am running a mixed model in R. However I am having some difficulty understanding the type of model I should be running for the data that I have.
Let's call the dependant variable the number of early button presses in a computerised experiment. An experiment is made up of multiple trials. In each trial a participant has to press a button to react to a target appearing on a screen. However they may press the button too early and this is what is being measured as the outcome variable. So for example, participant A may have in total 3 early button presses in an experiment across trials whereas participant B may have 15.
In a straightforward linear regression model using the lm command in R, I would think this outcome is a continuous numerical variable. As well... its a number that participants score on in the experiment. However I am not trying to run a linear regression, I am trying to run a mixed model with random effects. My understanding of a mixed model in R is that the data format that the model takes from should be structured to show every participant by every trial. When the data is structured like this at trial level suddenly I have a lot of 1s and 0s in my outcome column. As of course at a trial level participants may accidently press the button too early scoring a 1, or not and score a 0.
Does this sound like something that needs to be considered as categorical. If so would it then be looked at through the glmer function with family set to binomial?
Thanks
Comment: I would use a binomial GLMM, your data is exactly the same as accuracy data.
Comment: I agree, that seems to make the most sense. Thanks and appreciated @CatM
Answer: In this case, you can think of these data as a number of successes out of a total number of trials for each participant, so you can use a binomial glmm, for example, using lme4:glmer:
model <- glmer(cbind(success, total - success) ~ covariates + (1|ID),
       family = binomial, data = mydata)

Comment: Does this answer your question ? If so, please consider marking it as accepted. If not, please let us know why. Thanks !

lmer or binomial GLMM


Cache for logged-in user?

Question: I have created simple form and page to list records on form via Custom Drupal 8 Module. This form is accessible to only logged-in users with some specific role. It looks like screenshot. Whenever I submit new entry it lists record in via theme table for admin user but it does not appear for other logged-in users until I clear cache manually.
Please suggest, Thanks!
To display Records :
<?php

namespace Drupal\custom_form\Controller;
use Drupal\Core\Controller\ControllerBase;

class DisplayRecords extends ControllerBase {

  public function DisplayCustomRecords() {

    // Display theme table

    $table_header = [
      'name' => t('Name'),
      'mobilenumber' => t('Phone Number'),
      'email' => t('Email'),
      'age' => t('Age'),
      'gender' => t('Gender')
    ];

    $results = \Drupal::database()->select('custom_for_data')
      ->fields('custom_for_data', [
        'name',
        'mobilenumber',
        'email',
        'age',
        'gender'
      ])
      ->execute()
      ->fetchAll();

    $rows = array();
    foreach ($results as $res) {
      $formatted_age = \Drupal::service('date.formatter')->format(
        $res->age, 'custom', 'Y-m-d'
      );
      $rows[] = [
        'name' => $res->name,
        'mobilenumber' => $res->mobilenumber,
        'email' => $res->email,
        'age' => $formatted_age,
        'gender' => $res->gender
      ];
    }

    $form['table'] = [
      '#type' => 'table',
      '#header' => $table_header,
      '#rows' => $rows,
      '#empty' => t('No users found'),
    ];

    return $form;

  }

}

Comment: Please don't add solutions to questions - that's why we have answers :)
Answer: Short version: You need to define a cache tag that you can invalidate when a record is created, updated or deleted.
See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays for a lot of documentation on this.
I'd also recommend to look into using an entity type for this instead of a custom table. A bit of effort at first, but you get a ton of functionality with that, including default cache tags and for example views integration, so you can build searchable, sortable listings like that through views.
Comment: Better depends on the use case. Webform is good at building a public form and then storing submissions that can be viewed by admins. I wouldn't use it for actual content that you want to manage. But yes, webform might be a good alternative for this use case as well but hard to say without knowing the whole use case :)
Comment: I will look into details, thanks. As from your answers it sounds like recommended way is to create entity to store custom records rather than custom tables ? please suggest, that will be great if some more explanation will be added.
Comment: `sounds like recommended way is to create entity to store custom records rather than custom tables` @jas Yes, that is what he is suggesting.
Comment: @jas Better yet, you could build your form using the [https://www.drupal.org/project/webform](https://www.drupal.org/project/webform) and then create a View to display the results of the form.
Comment: Thanks, I was trying to learn how insert and select queries work with custom form so was working this way. By adding `options:no_cache: TRUE` its working now and records display without cache. Update added in my question.
Answer: I was trying to learn how insert and select queries work with custom form so was using this way . By adding options:no_cache: TRUE its working now.
DisplayRecords:
    path: 'list/custom/records'
    defaults:
      '_title': 'Custom Records List'
      '_controller': 'Drupal\custom_form\Controller\DisplayRecords::DisplayCustomRecords'
    requirements:
       _permission: 'access_custom_records_display'
    options:
      no_cache: TRUE // with this line cache stops on page

Cache for logged-in user?


How to print values from multiple for loops in Java

Question: I wish to create a compound interest calculator that calculates how much money a person would make starting with a sum of $1000 for a time of 15 years. I know how to declare and initialize both variables but don't know how to display the results together.
I think that the problem might have something to do with nested for loops but I can't quite put the pieces together. Does anyone have any ideas?
public class tes {
    public static void main(String[] args) {
        System.out.println("NetWorth investing at 15% return per Anum");
        System.out.println("age\t\tInvestment");

        double amount;
        double principle = 100;
        double rate = 0.15;

        for (int age = 23; age < 35; age++) {
            System.out.println(age);
        }

        for (int day = 0; day <= 10; day++) {
            amount= principle * Math.pow(1 + rate, day);
            System.out.println(amount);
        }
    }
}

Comment: Why do you have two `for` loops? Why does neither involve 15 years? Looks like 11 days, and 12 years respectively. Where can I get 115% daily interest?
Comment: Comment/identifier bug: 15% return per Anum, but amount= principle*Math.pow(1+rate, day)? 15% per day? What about interest on interest? And stick to conventions, class name should be Tes. Well, kind of. And where are the 15 years from the introduction? I see 10 and 35-23=12
Answer: How about that? Or did i not get your question correctly?
for (int age = 23; age < 35; age++) {
 System.out.println(age);

 if (day <= 10) {
  amount = principle * Math.pow(1 + rate, day);
  System.out.println(amount);
  day+=1;
 }
}

Comment: My question probably wasn't clear enough. I wanted to print both objects in the same print statement so they were both on the same line.
Answer: From what I can gather you would like to display your age next to your investment. In doing this you don't necessarily need the initial loop. We could just initialise your starting age:
// the starting age
int age = 23;
for(int year = 0; year<=15; year++) {
    amount= principle*Math.pow(1+rate, year);
    System.out.println(age+year + ":"+ amount);
}

So your output should be something similar to this:
Age Investment
23 : 100.0
24 : 114.99999999999999
25 : 132.24999999999997
26 : 152.08749999999998
27 : 174.90062499999993
28 : 201.13571874999994
29 : 231.3060765624999
30 : 266.0019880468749
31 : 305.9022862539061
32 : 351.787629191992
33 : 404.5557735707907
34 : 465.23913960640925
35 : 535.0250105473706
36 : 615.2787621294761
37 : 707.5705764488976
38 : 813.7061629162322


Search API returning no results even though nodes have been indexed

Question: I have a very simple set up as described below.
modules:
Search API 7.x 1-1
Search Pages 7.x - 1.2
Database Search
Devel Generate
I've set up a database server and an index for indexing nodes. The nodes were created using the Devel Generate module. The nodes have been indexed as shown on the Search API ->View->Index Status. On the Nodes->Index->Fields tab I've several options like Node ID, Content Type, Title, Status, etc. In Structure->Blocks I've added the Search Index to the page in the sidebar.
I also set permissions so anonymous users can administer  search.
But when administering a search nothing is returned.  For test purposes, when entering in the same search term ('Amet') in the default search, results are being returned.
How do I troubleshoot this? What is the problem here? Anyone help would be appreciated.
Answer: What type have you selected for your indexed fields?
I think search_api_page only handles fields using fulltext indexing, and wouldn't be so useful for numeric fields like nid, or text fields indexed with the string type.
You could also try using Views with search_api
Comment: i checked and have the field Title type set as Full Text.


How to allow default value selection in a @select helper?

Question: In my form, I've defined a drop-down:
@select(
myForm("category_id"),
options(Category.options()),
'_label -> "Category",
'_default -> "-- Choose a Category --",
'_showConstraints -> false
)

in my controller code:
Form<Category> catForm = form(Category.class).bindFromRequest();
if(catForm.hasErrors()) {
return badRequest(categoryEdit.render(catForm));
}

The form submission does not allow me to select the default value and catForm.hasErrors() is true if I make no selection. Two questions:

How do I allow default value to be selected in the dropdownlist?
I want the default value to be -1, where to set it? (Maybe this is where the problem is, there is no value associated with -- Choose a Category -- option?)
Answer: aviks suggestion is working. Maybe you have not imported the template correctly.
I did it like this. First I created a customSelectField.scala.html in views/helper/ as avik suggested:
@(field: play.api.data.Field, options: Seq[(String,String)], args: (Symbol,Any)*)(implicit handler: FieldConstructor, lang: play.api.i18n.Lang)

@getAsTuple(x : Any) = @{
    x match {
        case (value: String, text: String) => (value, text)
        case _ => ("-1", "Select")
    }
}

@input(field, args:_*) { (id, name, value, htmlArgs) =>
    <select id="@id" name="@name" @toHtmlArgs(htmlArgs)>

@args.toMap.get('_default).map { dv =>
    <option class="blank" value="@getAsTuple(dv)._1">@getAsTuple(dv)._2</option>
}

@options.map { v =>
    <option value="@v._1" @(if(value == Some(v._1)) "selected" else "")>@v._2</option>
}
</select>
}

and then in my template e.g index.scala.html where I want the select I do:
@import helper._

@helper.customSelectField(
 field = proposeNewTimeForm("selectTime"),
 options = times.get,
 '_label -> "Category",
 '_default -> ("-1" -> "-- Choose a category --"),
 '_showConstraints -> false
)

Remember you should NOT do:
@implicitField = @{
        FieldConstructor(helper.customSelectField.f)
    }

because this will cause your error.
If you would like to format the html surrounding the select somehow you could do as I with
a customField.scala.html in views/helper/:
@(elements: helper.FieldElements)

@elements.input
@elements.errors.mkString(", ")
@elements.infos.mkString(", ")

and then in the top of index.scala.html:
@import helper._
@implicitField = @{
    FieldConstructor(helper.customField.f)
}

Hope this helps!
Comment: Thanks Jakob,i'll try & get back if any further help is needed.
Answer: You could write an alternative to Play's HTML select helper that accepts a Tuple for the default option. This way you can specify both the underlying value and the text that should be displayed.
Here's a first effort, some of the Scala here is admittedly a little amateur:
app/views/_my_select.scala.html
@(field: play.api.data.Field, options: Seq[(String,String)], args: (Symbol,Any)*)(implicit handler: helper.FieldConstructor, lang: play.api.i18n.Lang)

@import helper.input

@getAsTuple(x : Any) = @{
  x match {
    case (value: String, text: String) => (value, text)
    case _ => ("-1", "Select")
  }
}

@input(field, args:_*) { (id, name, value, htmlArgs) =>
  <select id="@id" name="@name" @toHtmlArgs(htmlArgs)>

    @args.toMap.get('_default).map { dv =>
      <option class="blank" value="@getAsTuple(dv)._1">@getAsTuple(dv)._2</option>
    }

    @options.map { v =>
      <option value="@v._1" @(if(value == Some(v._1)) "selected" else "")>@v._2</option>
    }
  </select>
}

Usage
@_my_select(
  myForm("category_id"),
  options(Category.options()),
  '_label -> "Category",
  '_default -> ("-1" -> "-- Choose a category --"),
  '_showConstraints -> false
)

Comment: I am getting this error--> type mismatch; found : (play.api.data.Field, Seq[(String, String)], Array[(Symbol, Any)]) => play.api.templates.Html required: views.html.helper.FieldElements => play.api.templates.Html Note: implicit method implicitFieldConstructor is not applicable here because it comes after the application point and it lacks an explicit result type
Answer: I had a similar problem and found a simpler solution.
Instead of Play! helpers try this inside of your form:
<select name="category_id">
    <option value="-1">-- Choose a Category --</option>
    @(for((key, value) <- Category.options()){
        <option value="@value"> @key </option>
    }
</select>


NuGet pack and msbuild - how can pack reference assemblies in another location?

Question: I am using NuGet pack for the first time, using the AfterBuild target in the .csproj file.
<Target Name="AfterBuild">

  <Exec WorkingDirectory="$(BaseDir)" Command="$(NuGetExePath) pack -Verbose -OutputDirectory $(OutDir) -Symbols -Prop Configuration=$(Configuration)" />
</Target>

This works fine when building the project itself with msbuild ("msbuild MyProj.csproj"). NuGet is able to find the compiled assemblies in projectdir/bin/Release or projectdir/bin/Debug.
But, this project is one of many in a solution and there is a build file dedicated to building the entire solution.  The directory tree is like this:
- project root
  - build
  - src
    - MyProj
      - MyProj.csproj
      - MyProj.nuspec
    - AnotherProj
      - AnotherProj.csproj
      - AnotherProj.nuspec
  - project.proj (msbuild file)

This msbuild file overrides the output path of the Visual Studio build.
<PropertyGroup>
  <CodeFolder>$(MSBuildProjectDirectory)\src</CodeFolder>
  <CodeOutputFolder>$(MSBuildProjectDirectory)\build\$(Configuration)</CodeOutputFolder>
</PropertyGroup>

<Target Name="Build" DependsOnTargets="CleanSolution">
  <Message Text="============= Building Solution =============" />
  <Message Text="$(OutputPath)" />
  <Message Text="$(BuildTargets)" />
  <MsBuild Projects="$(CodeFolder)\$(SolutionName)"
           Targets="$(BuildTargets)"
                 Properties="Configuration=$(Configuration);RunCodeAnalysis=$(RunCodeAnalysis);OutDir=$(OutputPath);" />
</Target>

Now that the build redirects the assemblies to the build directory, when I run pack, NuGet can't find them.  How do I get NuGet to find the assemblies in the build directory?
Answer: Giving NuGet a TargetPath property for where to find the assembly works for this.
<Target Name="AfterBuild" Condition="'$(Configuration)' == 'Release' ">

  <Exec WorkingDirectory="$(BaseDir)" Command="$(NuGetExePath) pack -OutputDirectory $(OutDir) -Symbols -Prop Configuration=$(Configuration);TargetPath=$(OutDir)$(AssemblyName)$(TargetExt)" />
</Target>

Answer: Try to define files section in your *.nuspec files, set copy Copy to Output Directory property to Copy always or Copy if newer for them in VS properties. After that all you compiled files and nuspecs will be in $(OutputPath). And then change AfterBuild to:
<Target Name="AfterBuild">
  <PropertyGroup>
    <NuspecPath>$([System.IO.Path]::Combine($(OutputPath), "$(ProjectName).nuspec"))</NuspecPath>
  </PropertyGroup>

  <Exec WorkingDirectory="$(BaseDir)" Command="$(NuGetExePath) pack $(NuspecPath) -Verbose -OutputDirectory $(OutDir) -Symbols -Prop Configuration=$(Configuration)" />
</Target>

Comment: I did get it working like this, but it loses the conventions of using the .csproj for replacement tokens.  I've added an answer too, how do you think it compares?
Comment: Your solution looks better and absolutly right in this situation. I forgot about replacement tokens. But I didn't find documentation about TargetPath property except few discussions on codeplex. Is it documented anywhere?
Comment: It's not documented well, I think I tracked it down with codeplex, some blog posts, the nuget targets file and source code.


The result of json_decode is valid but individual fields are nulls in PHP?

Question: In the following PHP code
<?php
$in = json_decode(file_get_contents('php://input'), true);

$out->captcha = $in->captcha_code;
$out->name = $in->name;
?>

$in has the following value:
"in": {
  "name": "John Smith",
  "captcha_code": "03AL4dnxpzq1_rgDGri__waXDSp-951zkitA33V3LQ4kU7kDpsC_tKWK23Z_wyQXdAatEK_Nju1rHVfB4l2IRc8cofCNeSscIvAEC4VeSzgRa45x5d-GWXnAxdgSKQd8MkiUYaZw8h8ECjBLgWthseFd1L4YAPqAT893SOuHLQPd5z9JhJuNgPMcEPuAuBkYCIALcSzR0k6OHwMfgAaNvJ3nMYH2H6iRZeGnWDvXUfCE13w_VGSV3453I7qg3HqhB3t6W2fsH-I034ei0HG_PwMmB0blYNPTcTHA"
};

but $in->captcha_code and $in->name (and so $out) are nulls. What is wrong?
Comment: what does `$in['in']['name']` produce?
Comment: `captcha_code` does not exist in your object.
Comment: @u_mulder it exists, I corrected the text.
Comment: Then see anwser below.
Comment: @whitelined yes, even $in['name'] works fine.
Answer: You decode json as array and captcha_code not exist in json, Use this:
$out->captcha = $in['in']['captcha_code']; // not exist. just email and name is exist
$out->name = $in['in']['name'];

Answer: The second parameter for json_decode is for assoc, 'When TRUE, returned objects will be converted into associative arrays.'.
Since you're trying to access the data as an object, remove the 'true' from json_decode. If you leave it as true, treat the return as an array, so you would access the data using square brackets.
e.g.
$in = json_decode(file_get_contents('php://input'), true);
You would treat the data as an array
$out->captcha = $in['in']['captcha_code']
$in = json_decode(file_get_contents('php://input'));
You would treat the data as an object
$out->captcha = $in->in->captcha_code
Answer: PHP function json_decode accepts two parameters, number one being the JSON (string) you want to decode, and the other one (boolean) tells the function do you want to return it as an associative array or an object of type stdClass, it defaults to false, true means that you want it as an array.
Since you added the second parameter as true it will return it as an array, so you cannot use -> to access parameters in that JSON.
So, the correct code for your problem is
<?php
    $in = json_decode(file_get_contents('php://input'), true);

    $out->captcha = $in['in']['captcha_code'];
    $out->name = $in['in']['name'];
?>

Also, usually the best way to see what a variable holds is to print it's contents using var_dump or print_r like so:
<?php
    $in = json_decode(file_get_contents('php://input'), true);

    echo '
'; var_dump($in); die();
    //OR what I prefer
    //echo '
'; print_r($in); die();

    //$out->captcha = $in['in']['captcha_code'];
    //$out->name = $in['in']['name'];
?>


parameters passed when clicking a point on a NVD3 line chart or a slice in a pie chart

Question: I have just started using NVD3 for drawing simple charts such as line/pie/bar and such.
I would like to add some mouse interactivity to these charts but cannot find specific documentation nor example code:

allow user to click a specific line point, pie slice, bar component
receive in my program notification of the click with details of the series and point/data row pertinent to the click.

E.g., if I drew sales versus years, I would like user to be able to drill down to sales of a particular year. The line graph onclick example I have seen here are way too coarse for such detailed interaction.
Is there a relevant page(s) that documents the mouse click specifications for these types of charts?
Is it even possible with NVD3?
Thanks.
Comment: I'm not sure nvd3 offers that functionally (it might!). If you're just wanting to show standard 'line/bar/pie' charts that drill down, dc.js might be what you're looking for http://nickqizhu.github.io/dc.js/
Comment: @Adam this looks quite interactive and worthy of exploring. Thanks!
Answer: here you can see the plunker example ,may be you can get some help .
this example is for the pie chart drill down using angularjs and Nvd3 charting lib.
http://plnkr.co/edit/UjOP0k5Jo3OvQ6A79Qv9?p=preview


Determining which AdWords have the highest amount of user click throughs

Question: Possible Duplicate
First, I am not a statistician (though I'd like be one) but I am trying to understand how different tests can be utilized to examine samples.
Let's say that I have five of Google AdWords ads and I'm trying to develop a test to show which has been more effective at getting users to click on that ad.
<code>     January   February
 Ad A - 850       5000

 Ad B - 900       5300

 Ad C - 880       5100

 Ad D - 880       5100

 Ad E - 800       5000
</code>
In terms of frequency, Ad B has the highest amount of user click throughs in both January and February. (Is it fine just to say that one has a higher freqency and is therefore the more effective ad without relying on any significance test)
However, for each month, I want to use a statistical test to determine which ad was more effective. Initially, I assumed a chi-square (pearsons) test would be appropriate, but with five seperate ads, I'm not sure if that's the appropriate plan of action.
Can anyone help me understand what action to take and why, or is it enough just to rely on the frequency distribution of the five ads.
Comment: Thanks for the link to a possible duplicate.  The questions are related but they are not duplicates: here, you are asking for how to analyze the data, not for a sample size.
Comment: To calculate chi-square paired tests you need impressions and clicks for each ad.
Answer: I'm presuming the test you really want is whether B's apparent greater success can be regarded as statistically significant evidence that B generates more clicks in general; compared to a null hypothesis that all ads are effectively equal and B just had a lucky couple of months.  Because if you just want to say "which ad had the most clicks?" the answer is trivial and is "B".
One standard way of testing this is through fitting a statistical model of some sort.
Your data show signs of increasing variance as their means increase, which suggests transforming it to a log scale.  Then you can fit a model which assumes normal distribution of number of clicks, and use an ANOVA table and F test to test whether the "ad" factor is significant, or the variation seen between different ads may be due to chance.
Some code that does this in R is pasted below, and concludes that with a p value of 0.088 there is a reasonable chance that the data seen could have been generated from a random process where ad type does not influence the result.
<code>> ad <- rep(LETTERS[1:5],2)
> mon <- rep(c("Jan", "Feb"),c(5,5))
> clicks <- c(850,900,880,880,800,5000,5300,5100,5100,5000)
>
> model <- lm(log(clicks) ~ mon + ad)
...
> par(mfrow=c(2,2))
> plot(model) # check diagnostics
...
> summary(model)
...

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   8.5204     0.0171  497.23  9.8e-11 ***
monJan       -1.7784     0.0140 -127.10  2.3e-08 ***
adB           0.0577     0.0221    2.61    0.059 .
adC           0.0272     0.0221    1.23    0.286
adD           0.0272     0.0221    1.23    0.286
adE          -0.0303     0.0221   -1.37    0.242
---
...

Residual standard error: 0.0221 on 4 degrees of freedom
Multiple R-squared:    1,       Adjusted R-squared: 0.999
F-statistic: 3.23e+03 on 5 and 4 DF,  p-value: 2.67e-07

> anova(model) # F test suggests p value of 0.088 for ad, so maybe difference is due to chance
Analysis of Variance Table

Response: log(clicks)
          Df Sum Sq Mean Sq  F value  Pr(>F)
mon        1   7.91    7.91 16155.25 2.3e-08 ***
ad         4   0.01    0.00     4.49   0.088 .
Residuals  4   0.00    0.00
</code>
Comment: Your answer is ok if we are talking clics. Chi-square is more appropiate for CTR (clicks/impressions).


Advanced Custom Fields and functions

Question: I'm quite new to php and Advanced Custom Fields (ACF). I want to display a static banner on all pages except on the homepage which has a video. How do I use the if main function?
Answer: try this
<code>     <?php if (is_home()) { //check is home page
     //not show
     } else { //if not home page
     //show ACF
    the_field('field_name'); //replace ACF field name
   }
   ?>
</code>
Good Luck

Advanced Custom Fields and functions


Using Android vibrator seems a bit slow, what's a good strategy?

Question: I am trying to make a relatively simple game in Kotlin with force feedback. Every time an object hits a wall I want the phone to vibrate.
Here is my code, which generally works:
val vibT = 0L
val vibrator: Vibrator by lazy {
    getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
}

and then:
fun bump() {
    var now = System.currentTimeMillis()
    if ( vibrator.hasVibrator() && now>vibT+51) {
        vibrator.cancel()
        vibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE))
        vibT = now
    }
}

It seems that when the code runs the bump() function in rapid succession (for example, when several objects hit the wall), it gets rather sluggish with the redraws. If I comment out the line vibrator.vibrate(...) then the game runs smoothly.
At first, I thought maybe I was just trying to call the function while it was still vibrating, hence causing a backlog of vibration requests, but even after adding in the timing check with now and vibT it's still a bit sluggish when a lot of calls are made to the function.
I'm assuming this is not a synchronous call, and that the code continues executing as soon as I've requested a vibration, but I can't find documentation to back that up.
Is there a better strategy? Maybe there are some gotcha's that I ought to be aware of when doing this?
Answer: After testing, I saw that calls to Vibrator::vibrate can take up to 5 milliseconds. If you're doing it in rapid succession, this can cause slowdown, as in your case.
I wrote a helper class that moves the calls to Vibrator::vibrate to a background thread to avoid blocking the UI thread:
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import java.util.concurrent.ArrayBlockingQueue

/**
 * @author https://github.com/gottagofaster236
 */
class AsyncVibrator(context: Context) {
    private val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator

    private val vibrationRequestsQueue = ArrayBlockingQueue<Long>(VIBRATOR_QUEUE_CAPACITY)

    private var vibrationThread: Thread? = null

    fun vibrate(lengthMs: Long) {
        vibrationRequestsQueue.offer(lengthMs)
    }

    fun start() {
        stop()
        vibrationThread = Thread(::processVibrationRequests).apply(Thread::start)
    }

    fun stop() {
        vibrationThread?.interrupt()
        vibrationThread = null
    }

    private fun processVibrationRequests() {
        while (!Thread.currentThread().isInterrupted) {
            val lengthMs = try {
                vibrationRequestsQueue.take()
            } catch (e: InterruptedException) {
                break
            }

            if (Build.VERSION.SDK_INT >= 26) {
                vibrator.vibrate(
                    VibrationEffect.createOneShot(
                        lengthMs,
                        VibrationEffect.DEFAULT_AMPLITUDE
                    )
                )
            } else {
                @Suppress("DEPRECATION")
                vibrator.vibrate(lengthMs)
            }
        }
    }

    private companion object {
        const val VIBRATOR_QUEUE_CAPACITY = 10
    }
}

Usage in an Activity:
// import ...

class MainActivity : Activity() {
    private val asyncVibrator = AsyncVibrator(this)

    // ...

    override fun onResume() {
        super.onResume()
        asyncVibrator.start()
    }

    override fun onPause() {
        asyncVibrator.stop()
        super.onPause()
    }

    fun testVibration() {
        // Vibrate for 100 milliseconds.
        asyncVibrator.vibrate(100L)
    }
}

Answer: Try this.
// this initiates the android vibrator [ put this on the onCreate ]
val vibe = firstname.lastname@example.com(Context.VIBRATOR_SERVICE) as Vibrator

then
// put this where you want the vibrator to activate (fun bump*())
val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibratorService.vibrate(40)


How to render a weight element?

Question: I'm trying to render a weight element but it doesn't works I just have as output an empty string. But when I try to render a checkbox I get the correct output.
For the weight element:
$weight = array(
  '#type' => 'weight',
  '#title' => t('Weight'),
  '#default_value' => 1,
  '#delta' => 10,
);

// For Drupal 7.
dpm(drupal_render($weight));
// For Drupal 8.
kint(\Drupal::service('renderer')->render($weight));

Output: An empty string.
For the checkbox element.
$check = array(
  '#type' => 'checkbox',
  '#title' => t('Dry run'),
  '#description' => t('Test run without deleting revisions but seeing the output results.'),
);
// For Drupal 7.
dpm(drupal_render($check));
// For Drupal 8.
kint(\Drupal::service('renderer')->render($check));

Output:

 <input type="checkbox" value="1" class="form-checkbox" />  Dry run

Test run without deleting revisions but seeing the output results.

So, I think that the drupal_render() function and renderer service are working fine because the checkbox is rendered, but the weight element not, I'm missing something here?
Answer: The select element is built in Weight::processWeight():
  /**
   * Expands a weight element into a select element.
   */
  public static function processWeight(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#is_weight'] = TRUE;

    $element_info_manager = \Drupal::service('element_info');
    // If the number of options is small enough, use a select field.
    $max_elements = \Drupal::config('system.site')->get('weight_select_max');
    if ($element['#delta'] <= $max_elements) {
      $element['#type'] = 'select';
      $weights = [];
      for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
        $weights[$n] = $n;
      }
      $element['#options'] = $weights;
      $element += $element_info_manager->getInfo('select');
    }
    // Otherwise, use a text field.
    else {
      $element['#type'] = 'number';
      // Use a field big enough to fit most weights.
      $element['#size'] = 10;
      $element += $element_info_manager->getInfo('number');
    }

    return $element;
  }

Which is only called in form building, not in normal rendering.
Comment: So, there is not possible to render it if you are not rendering a form?
Comment: This is probably not a good idea for any form element, rendering when building a form. The rendered form elements won't get processed (this is why the mentioned process method is not called) and at this time there is no render context to catch the bubbleable metadata, so you loose attachments, caching ...
Comment: Do you think that this should be changed in Core? Is weird that ymou can't do it in a normal way.
Comment: No, although there are form elements which can be used in a normal render context, most prominent is `table` (don't know if there are more), in this case it wouldn't make much sense to use it outside of a form.
Comment: Sometimes I need to render elements in a table, this is the problem that I have, take a look at http://cgit.drupalcode.org/node_revision_delete/tree/src/Form/NodeRevisionDeleteAdminSettings.php?h=8.x-1.x#n149 here a dropbutton is rendered in a table row, but when I need to renden a weight element is not possible.
Comment: Take a year but I found how don't render the element inside the table, this is the commint and was as easy as use the 'data' index to add the element. :-)

How to render a weight element?


Dm9 chord - the fifth and the seventh

Question: I'm looking for the naming background behind the Dm9 chord (perhaps some others also but this one got me confused).
Here is the example:

This translates to:

d2 - root (for the D in the chord)
f2 - minor third (for the m in the chord)
c3 - minor 7
e3 - ninth (for the 9 in the chord)

I'm confused by two things:

Why isn't there a 5th?

was under the impression it defaults to being there unless stated otherwise

Why isn't the 7 explicitly stated in the chord name?
Answer: First question: the 5th is often left out of chords, particularly on guitar, for a couple of good reasons. Often, a note contained in a full chord cannot be fingered with a good voicing, and in any case, the sound of the 5th is implied in an overtone produced by the root. In chords containing many notes, some need to be sacrificed when played on guitar.
Second question: after a chord has a 7th (of any kind), the next interval is usually the 9th. It's accepted that any 9th chord will have the 7th in there as well, so it doesn't need stating. It's implicit in the '9th' name. Obviously if the chord is 'add9', then it's just the triad, and no 7th is there anyway.
It might be interesting for you to try finding other voicings for Dm9, using D F A C and E. You will find out that when four out of the five notes are under your fingers, that elusive fifth is just out of reach ! Although a couple do exist which contain all the notes.
Comment: If desired, for the given voicing the fifth could be added without much effort on the fifth fret of one of the two E (e) strings.
Comment: @MattL. - you could indeed. That's the trouble with blindly using chord shapes  someone else has made up, and the reason for my last paragraph.
Answer: I would add something to the above statement.  While fingering is the key to understanding guitar chord forms in harmony theory we are taught that the 5th of just about any chord can be sacrificed, it rarely serves a purpose in movement from one chord to another.  It is often deleted fro the dominant 7 chord and all of its extensions.  So, even if you had enough fingers and strings to grab it, it isn't necessary.
Comment: Ask any guitarists who uses 'power chords' and they will disagree.
Comment: Look at classical and modern music theory.  Guitar habits don't rule the world.  The Powerless Chord (no harmonic content), :-D

Dm9 chord - the fifth and the seventh


Composition of Cowell's "rhythmic key changes"

Question: I'm currently reading Henry Cowell's New Musical Resources and
On page 98, Section 6,(TEMPO) in part 2 (RHYTHM),
is a paragraph of for instances. Directly, I'm grappling with the SECOND FOR INSTANCE ...
"By the correct application of a change of tempo, a change of the rhythmic key of time or metre can be made.
For instance, if a quarter-note at M. M. 96 equals (C), it is evident that if the tempo is changed to M. M. 72, the quarter note will be of different value, namely the equivalent of (G). In this way the key tone of the whole time or metric system can be changed at will, and many simplifications of practice can be made.
if, FOR INSTANCE, the rhythmic chord of C (in the the ratio of 4:5:6) has been struck, and it is desired to strike the chord of (F), this can be done in the key of (C) only by the use of three-sixteenths notes against three twentieths notes against eighth notes. If, however the tempo be changed from M. M. 96 to M. M. 64, the chord of (F) can be expressed by quarter notes, since by means of the change of tempo the key will have been changed to that of (F) "
I understand the striking of the Rhythmic (C) Chord and it's ratio (5:6:4) and my grasp of the Whole note Series (3/16 . 3/20 . 2/8) concept is fairly solid.
the bit I'm slightly confused by is the striking of the Rhythmic (F) chord
in the Rhythmic key of (C).
How is it that the Ratio for the (F)Chord (3:5:2) ..
and, I'm assuming this Ratio after a good stare at the Scale Rhythm Chart on Page 99.
[C:C-1:1 . C:C#-14:15/(C:Db-15:16) . C:D-8:9 . C:Eb-5:6 . C:E-4:5 .
C:F-3:4 . C:Gb-5:7 . C:G-2:3 . C:Ab-5:8 . C:A-3:5 . C:Bb-8:15 . C:C-1:2],
. .arrived at using the Overtone Ratios and or the Simple Overtone Ratios?
Also .. in the ratio relationship of (3:5) why , again [according to the chart on p.99], is the (C) given as the (3rd)partial and the (A) as a (5th)partial in regard to the Overtone Series?
Lastly..
The Changing of the Tempo from MM96 to MM64 with the Key change to (F),
again out of confusion I'm guessing the Tempos are related by 16 as a base?
and the Rhythmic Chord of (F) expressed by quarter-notes, against fifth-notes, against sixth-notes(4:5:6) in the rhythmic key of (F) is now the Tonic key conducted by the tempo MM64?
This Post is mostly Directed at Pat Muchmore, but I will be super grateful to anyone willing to help.
Comment: Well I'm looking forward to the answer to this one.  I've read it four times and I still don't understand what it says!
Comment: @JimM My thoughts exactly :) I bet it will end up being a good question, though.
Answer: I don't own this book, so I unfortunately can't consult the page references you gave. But I'll try to offer some insights, at least until Pat gets here :-)

If, however the tempo be changed from M. M. 96 to M. M. 64, the chord of (F) can be expressed by quarter notes, since by means of the change of tempo the key will have been changed to that of (F) "

This is done because of the ratio between C and F. Since C is a perfect fifth above F, C is a 3:2 relationship to F. Another way of thinking of it is that, in the harmonic series of F, F is the second partial and C is the third partial. So he's able to switch from "the key of C" to "the key of F" by creating tempos in a 3:2 relationship of 96:64. The music at MM=64 is thus in the key of F.

Also .. in the ratio relationship of (3:5) why , again [according to the chart on p.99], is the (C) given as the (3rd)partial and the (A) as a (5th)partial in regard to the Overtone Series?

He has apparently switched to the F overtone series of F, F (an octave higher), C, F, A; hence C and A are the third and fifth partials.
Comment: All very well and good, but the point is..?
Comment: @Tim Cowell was just theorizing some possible avenues of composition, that's all. Ideas like this one can be traced back at least to Helmholtz.
Comment: PDF of the book can found here (link to PDF is contained on this page, but it takes a long time to open, at least on my phone): http://ubu.com/historical/cowell/
Comment: @ richard cheer for the insight... i have another fairly straight forward conundrum. on page 100 in cowell's book(see attached PDF)  there is an explanation centered around C-C# ... (C#) contained  with in a whole note  has four and two-seveths vibrations per second and it will be found that a seven-thirtieths note, which is the corresponding time-value of (C#)  will be contained in a  whole note four and two-sevenths times , in other words, four seventh-thirtieths notes  ..  What is  a seven-thirtieths note? how does it relate to this Ratio (14:15) ?


Android onClickListener works only once, Button does not works for second time

Question: I am new in android Programming , Here is the code in which checkButton works only for once . Nothing happens when I click it for the second time. I can't seem to find problem.

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    ProgressDialog progress;
    Button checkButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkButton = (Button) findViewById(R.id.button);
        checkButton.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v){

                    EditText aNumber = (EditText) findViewById(R.id.editText);
                    String aCount = aNumber.getText().toString();
                    boolean totalDigit = aCount.length()==16;
                    if(totalDigit){
                     if(checkConnectivity()) {
                       progress = new ProgressDialog(v.getContext());
                       progress.setTitle("Validating Number");
                       progress.setMessage("Processing...");
                       progress.setCancelable(true);
                       progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                       progress.show();
                       new Thread(new Runnable() {
                           public void run() {
                               try {
                                   Thread.sleep(5000);
                               } catch (Exception e) {
                                   e.printStackTrace();
                               }
                               progress.dismiss();
                               MainActivity.this.runOnUiThread(new Runnable()
                               {
                                   public void run()
                                   {
                                       //Do your UI operations like dialog opening or Toast here
                                       showAlert();
                                   }
                           });
                       }
                       }).start();

                   }else{
                       Toast.makeText(MainActivity.this,"Internet Connection is not Available",Toast.LENGTH_SHORT).show();
                   }}else {
                         Toast.makeText(MainActivity.this, "Please enter correct 16 digit number",Toast.LENGTH_SHORT).show();
                        }

                }
            });
         }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
         private void showAlert(){
             AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

             builder.setMessage("Number not found!");
             builder.setCancelable(true);

             //Creating dialog box
             AlertDialog alert = builder.create();
             //Setting the title manually
             alert.setTitle("Number Status");
             alert.show();
             setContentView(R.layout.activity_main);

         }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
       private boolean checkConnectivity(){
           ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
           if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                   connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
               return  true;
           }
           else {
               return false;
           }
       }

    }

My Check Button works for only once. After I press it for second time nothings happen. I have looked all previous answer related to this in stackoverflow but nothings helped me. Please someone tell me what is going wrong.
Comment: How do you know that it even works the first time?  You never explained to us what this code actually does.
Answer: I think the problem is you call setContentView(R.layout.activity_main); twice. setContentView will override the layout and replace it with the new one. You should only one call it in onCreate. That's why you should remove this line in showAlert() method.
private void showAlert(){
         AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

         builder.setMessage("Number not found!");
         builder.setCancelable(true);

         //Creating dialog box
         AlertDialog alert = builder.create();
         //Setting the title manually
         alert.setTitle("Number Status");
         alert.show();

         // remove this line below
         //setContentView(R.layout.activity_main);

     }

You will get the message warning Attempted to finish an input event but the input event receiver has already been disposed if you debug your code. The reason is you call setContentView twice so that the input event receiver of previous view is not free. That's why you can not click your button in the second times.
Try my solution, remove setContentView in showAlert and see the result.


Como criar registros na tabela MYSQL de acordo com o valor da variável $nregistros PHP

Question: Tenho uma variável $nregistros que define o valor de registros a ser inserido na tabela "formularios".
Se o $nregistros for igual a 4 por exemplo, ele deve inserir 4 linhas da seguinte forma:
formularios
id|campo
6 | 1
7 | 2
8 | 3
9 | 4

o campo "id" é autoindex, e o campo "campo" deve iniciar em 1 e ir até o valor final da $nregistros, no caso aqui, 4
Como posso fazer isso?
Answer: Para esse feito, um simples for pode resolver.
Tente algo como :
<?php
    $nregistros = 4;
    for($n = 1; $n <= $nregistros; $n++) {
        echo "INSERT INTO formularios SET campo = $n; ";
    }
?>

No lugar do echo entraria sua query de inserção no banco.
Dessa forma, obtive a seguinte saída:
INSERT INTO formularios SET campo = 1; INSERT INTO formularios SET campo = 2; INSERT INTO formularios SET campo = 3; INSERT INTO formularios SET campo = 4;

Vale lembrar que caso o número que estiver na variável $nregistros
  for muito longo, haverá perda de performance, pelo fato da realização
  de múltiplos insert.
Comment: isso mesmo que precisava, valeu!
Comment: Fico feliz em ter ajudado. :)


Qual é a diferença entre angular.extend e angular.merge?

Question: No angular, para estender um objeto, costumo usar `angular.exted
var obj = {nome: "wallace"}
angular.extend(obj, {idade: 26})

Resultado:
Object {nome: "wallace", idade: 26}

Porém, percebi que, ao usar angular.merge, o resultado é o mesmo:
angular.merge(obj, {idade: 26})

Resultado:
Object {nome: "wallace", idade: 26}

Qual é a diferença entre ambos?
Comment: http://davidcai.github.io/blog/posts/copy-vs-extend-vs-merge/
Answer: As duas funções fazem a mesma coisa com uma sútil diferença. Ambas copiam as propriedades de um ou mais objetos fontes para um objeto destino.
A diferença
angular.merge
Faz uma cópia "profunda" (cópia recursiva) das propriedades, ou seja, propriedades que são objetos serão re-criadas de forma que não apontem para as mesmas referências da(s) base(s).
angular.extend
Faz uma cópia simples (ou rasa) das propriedades, ou seja, as propriedades que são objetos apontarão para a mesma referência da(s) base(s).
Exemplo:

angular.module('app', []);

angular.module('app').controller('mainController', mainControllerFn);

function mainControllerFn(){
  /* ***** merge ***** */

  var mPessoa1 = { nome: 'Joaquim', email: 'email@example.com' };
  var mPessoa2 = { sobrenome: 'Soares', usuario: {username: 'joaquim1', isAdmin: false } };

  angular.merge(mPessoa1, mPessoa2);

  console.log(mPessoa1);
  console.log(mPessoa1.usuario === mPessoa2.usuario);
  // mPessoa1.usuario e mPessoa2.usuario não apontam para a mesma referência

  /* ***** extend ***** */

  var ePessoa1 = { nome: 'Joaquim', email: 'firstname.lastname@example.com' };
  var ePessoa2 = { sobrenome: 'Soares', usuario: {username: 'joaquim1', isAdmin: false } };

  angular.extend(ePessoa1, ePessoa2);

  console.log(ePessoa1);
  console.log(ePessoa1.usuario === ePessoa2.usuario);
  // ePessoa1.usuario e ePessoa2.usuario apontam para a mesma referência
}

Comment: Cara, então é muito sério a escolha de qual usar. O framework que eu uso trabalha relacionamentos como "subobjetos" (objetos dentro do outro). Então em alguns casos, vai ser preferível usar `merge`, para não ter problema com referências de objetos.
Answer: Extend:

angular.extend(dst, src1, src2, ...) is to shallow copy the properties
  of the source objects from right to left, all the way to the
  destination object.

Traduzindo: angular.extend(dst, src1, src2, ...)  é a cópia simples das propriedades dos objetos de origem da direita para a esquerda, todo o caminho para o objeto de destino.
var src1 = { name: 'David', age: 30 }; // source 1
var src2 = { age: 26, skill: {} }; // source 2
var dst = {}; // destination

console.log(angular.extend(dst, src1, src2));
// Output: { name: 'David', age: 26, skill: {} }

console.log(src2.skill === dst.skill);
// Output: true
// src2 and dst share the same skill object due to shallow copy.

Merge:

angular.merge is an Angular 1.4+ API that is to deep (recursively)
  copy the properties of the source objects to the destination object.

Traduzindo: angular.merge é profunda (de forma recursiva), copia as propriedades dos objetos de origem para o objeto de destino.
Aqui usamos mesmo exemplo substituindo angular.extend por angular.merge:
var src1 = { name: 'David', age: 30 };
var src2 = { age: 26, skill: {} };
var dst = {};

console.log(angular.merge(dst, src1, src2));
// Output: { name: 'David', age: 26, skill: {} }
// It seems to the same result as the previous example's, however, ...

console.log(src2.skill === dst.skill);
// Output: false
// src2.skill and dst.skill point to different skill objects due to deep copy.

Referência: Copy vs. Extend vs. Merge


Java - Select All GUI Components of Type

Question: I'm trying to code my program so that all the components on my JFrame have a consistent colour scheme. To be able to do this, I wanted to use Java's for-each loop to affect each component of the same type. I have tried it like this to colour the JPanels, but it has had no affect.
public void colourGUI()
{
    for (Component comp : this.getComponents())
    {
        if (comp instanceof JPanel)
        {
            ((JPanel) comp).setOpaque(true);
            comp.setBackground(Color.gray);
        }
    }
}

I would have imagined this would work, but when I loaded the application it hadn't taken affect.
I'm reasonably new to Java, and I have previously used C# for programs like this where I would have used C#'s OfType<> method. I was hoping Java would have some kind of equivalent but I haven't found anything yet.
Would anyone be able to point me in the right direction to accomplish what I'm looking to do? I imagine I'm missing something really obvious!
Thanks,
Mark
Comment: I've only just seen your last post, I'll test now and let you know. Thanks @Dan
Comment: Could it be you are not using `repaint()` and `revalidate()`?
Comment: Hi, like I say I'm not overly familiar with Java's methods. When are where would I need to use these? @Dan
Comment: I just posted an answer. If it doesn't work drop a comment
Comment: Responded to your post. Think it's almost there but something is still just not firing for some reason. @Dan
Comment: As camickr pointed out my first answer was completely wrong. Can you post some more code? I posted some example code below of your code + implementation
Comment: @marcuthh Accordingly to my past experience, for loop and for-each loop does have a difference. Try changing your for-each loop to a normal for loop and test again. Let me know whether it works.
Comment: Have you had any luck?
Comment: Done with a regular for-loop. Works as expected! Thanks a lot @Dan
Comment: You're not going to find an `OfType<>` in Java, since it has no extension methods and even if it did, its generics are not strongly typed at runtime. -- Generally, you see methods take an instance of a class with the parameter named `clazz` (this is equivalent to the `System.Type` in C# -- except they pass it around like a parameter named `clazz` instead of just inferring it from the object).
Answer: I apologise for my first answer. As shown in this example your code,
public void colourGUI()
{
    for (Component comp : this.getComponents())
    {
        if (comp instanceof JPanel)
        {
            ((JPanel) comp).setOpaque(true);
            comp.setBackground(Color.gray);
        }
    }
}

, does work without change.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.Color.*;
import java.io.IOException;
import java.lang.*;
import java.util.*;

public class Test extends JFrame {
    private Box boxHolder;
    private JPanel scrollPaneContainer;

    Test(int i) {
        super("Test Frame");
        this.setLayout(new BorderLayout());
        this.getContentPane().add(initScrollPane(),BorderLayout.CENTER);
        this.getContentPane().add(initButtonAdd(),BorderLayout.SOUTH);

        for(int j = 0; j < i; j++) {
            boxHolder.add(createPanel());
        }

        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);
    }

    private Component initButtonAdd() {
        JButton button = new JButton("Recolour");
        button.setBackground(Color.green);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (Component comp : boxHolder.getComponents())
                {
                    if (comp instanceof JPanel)
                    {
                        ((JPanel) comp).setOpaque(true);
                        comp.setBackground(Color.gray);
                    }
                }
            }
        });
        return button;
    }

    private Component initScrollPane() {
        scrollPaneContainer = new JPanel( new BorderLayout() );
        boxHolder = Box.createVerticalBox();
        scrollPaneContainer.add(boxHolder, BorderLayout.PAGE_START);
        JScrollPane jSP = new JScrollPane(scrollPaneContainer);
        jSP.getVerticalScrollBar().setUnitIncrement(16);
        return jSP;
    }

    private Component createPanel() {
        JPanel panel = new JPanel();
        panel.setBackground(randomColor());
        panel.setPreferredSize(new Dimension(100,50));
        panel.add(new JLabel("a colored Panel"));
        panel.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int indexPosition  = boxHolder.getComponentZOrder(panel);
                try
                {
                    boxHolder.remove(indexPosition);
                }
                catch(Exception ex){}
                try //Will only add here if you have a component in index position 1
                {
                    boxHolder.add(createPanel(),indexPosition);
                }
                catch(Exception ex){}
                scrollPaneContainer.revalidate();
            }
            @Override public void mousePressed(MouseEvent e) {}
            @Override public void mouseReleased(MouseEvent e) {}
            @Override public void mouseEntered(MouseEvent e) {}
            @Override public void mouseExited(MouseEvent e) {}
        });
        return panel;
    }

    private Color randomColor() {
        Random rand = new Random();
        float r = rand.nextFloat() / 2f ;
        float g = rand.nextFloat() / 2f;
        float b = rand.nextFloat() / 2f;
        Color randomColor = new Color(r, g, b);
        return randomColor;
    }

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

Can you post some more code from your GUI?
Comment: Just tried this and no change at all, is there anything more fundamental than this that it could be?
Comment: First of all the order should be revalidate() and repaint(). However, there is no need to do this as Swing components do this automatically whenever the property of a component is changed.
Answer: When you ask a question post a proper SSCCE that demonstrates the problem. The basic code looks reasonable, but without the SSCCE we can't tell the context of how this code is being used. For example we don't know what this.getComponents() refers to.
I would guess the problem is that your code doesn't use recursion so you are not actually getting a list of all the components on the frame. This is easy enough to test, just add a display statement in your loop to see how many panels you actually find.
The structure of a frame is more complex than you think. Take a look at Using Top Level Containers for a better description of the structure.
You can use the Swing Utils class which does use recursion to get all the child components of a given type.


CFAdmin keeps on kicking back to login screen

Question: We just got a new CF 10 VPS with Hostek.  All seems well but in cfadmin we keep on kicked back to the login screen. I know that you can't have more than one user logged in at a time but even with just one user, it keeps on kicking us out.  We're not doing any particular action (ex. posting a form) when this occurs.  It seems to be randomly occurring after a few clicks here and there.  In the blog I linked to, some in the comments were having this problem too but there isn't a solution posted.
Thanks
Comment: I remember a cookies issue in Internet Explorer when sub-domains include a dash (-).
Answer: This might be a cookies issue.  Check your cookies settings and make sure your browser is accepting cookies from that domain.
Answer: For us the problem goes away when we access ColdFusion administrator using a numeric IP address (eg https://22.214.171.124/CFIDE/administrator instead of https://example.com/CFIDE/administrator).
But I don't know why.
Answer: A couple of possibilities.

As other have suggested you might be having trouble with cookies. But if this were the case I would sort of expect that you would not be able to log in at all.
Your assumption that only 1 login at a time is a possibility. Check the server admin logs to see if that is true.
Your Cf server might be restarting. A restart would kill your session causing you to have to login again. Check the event logs, the out logs and the runtime/bin directory (where you will see hot spot errors).
Your default session timeout might be set to draconian levels. The default is typically 20 minutes, but if someone has changed it to (for example) 2 minutes you would get logged out any time you took too long to click on something.

That's all I can think of :)
Comment: Thanks for the useful suggestions, unfortunately nothing helped.  I'm sure it's only one user logged in at a time
Answer: Did you ever solve this (since posting back in 2012)? Either way, I'll offer some thoughts in case others may find the question and still seek an answer.
Thanks for the link to my blog post, btw. Sorry it didn't help then.
You refer to other comments reflecting the problem with no solution. Did you happen to revisit the comments since then? You may find new info.
In addition, did you happen to have more than one browser open looking at the Admin? That could cause the problem (as each browser creates different cookies to track the "user" who is logged in).
Or did you happen to have more than once instance of CF against which you were logging in, but using perhaps the same IP address (but different ports) for their CF Admin? That would cause even one browser to send the same cookies to the different instances, which may cause the instance to reject/rotate them to protect against session fixation.
Indeed, to that point, did you ever try using the coldfusion.session.protectfixation jvm flag to see if that helped (https://www.petefreitag.com/item/815.cfm), though it may be overkill to solve this one problem.
FInally, did you happen to see the later post I did, which showed how some problems are due to duplicate cookies? (http://www.carehart.org/blog/client/index.cfm/2014/4/10/CF_Admin_error_about_error_accessing_this_page)


Quadratic formula for $z^2 + (\alpha + \beta i)z + \gamma + i\delta = 0$ where $z\in\mathbb{C}$

Question:
The problem statement is to solve the quadratic equation
  $$
z^2 + (\alpha + i\beta)z + \gamma + i\delta = 0.
$$

I took the standard approach of $\frac{-b\pm\sqrt{b^2 - 4ac}}{2a}$ but I am not not sure if this is the best way to approach the problem. I though about writing $z$ as $z = x + yi$, grouping, and completing the square either in reals/imaginary part or completing the square for $x$ and $y$. With the standard approach, I have
$$
z = \frac{-\alpha - \beta i\pm\sqrt{\alpha^2 - \beta^2 + 2\alpha\beta i - 4\gamma - 4i\delta}}{2}
$$
Now I could say $a + bi = \sqrt{\alpha^2 - \beta^2 + 2\alpha\beta i - 4\gamma - 4i\delta}$ and determine the complex number $a + bi$.

Is there a better way to do this problem? I feel like the above is too tedious. It is doable but I don't think it is optimal.
Comment: It seems you did not compute $(\alpha +i \beta)^2$ correctly. Other than that this is the common approach, IMO. Do you know how to calculate the sqrt of a complex number in algebraic form?
Comment: The one you used $x + i y$ with real $x,y,$ incontrast to the trigonmetric form $r e^{i\phi}$
Comment: @quid I know how to do that. I just thought there would be a better approach to this problem or was at least hoping there would be.
Comment: Good. I would not know a general approach that it is better. But perhaps somebody else knows something.
Answer: You will not be able to get a simpler expression for $\sqrt{\alpha^2 - \beta^2 + 2 \alpha \beta i - 4 \gamma - 4 i \delta}$.  Leave it in that form.
Comment: Is there another method to approach this problem though?