Combinatorics Example Problem

Question: Ten weight lifters are competing in a team weightlifting contest. Of the lifters, 3 are from the United States, 4 are from Russia, 2 are from China, and 1 is from Canada.
Part 1
If the scoring takes account of the countries that the lifters represent, but not their individual identities, how many different outcomes are possible from the point of view of scores?
This part I understand:  10! / [ 3! 4! 2! ]  = 12,600
Part 2 (don't understand this part)
How many different outcomes correspond to results in which the United States has 1 competitor in the top three and 2 in the bottom three?
This part I'm confused.  Here you have 10 slots.
The first three slots must be of some order:  US, US, or [Russia, China, Canada].
The last three slots must be of some order US, [Russia, China, Canada], [Russia, China, Canada].
I thought the answer would be this:
$\binom{3}{2} \binom{1}{1} * \frac{7!}{4!\ 3!\ 2!} $
My reasoning:  In the first 3 slots, you have to pick 2/3 US people.  Then you only have one remaining.  You have 7! ways to organize the rest but have to take out repeats so you divide by factorials of repeats which is 4,3, and 2.  But my middle term is wrong....
My research shows me answers of 2 forms but I can't understand it:
Method 1:  $\binom{3}{1} \binom{3}{2} * \frac{7!}{4!\ 3!\ 2!}$
This case, I don't understand why there's a 3 in the second binomial, $\binom{3}{2}$.  We already selected ONE US person so shouldn't it be $\binom{2}{2}$?
Method 2: $ \binom{7}{2} \binom{3}{1} \binom{5}{4} \binom{3}{2} \binom{1}{1} $
?
Sorry for the long post.  Thanks again.
Answer: Part 2 is solved in two stages (using Method 1):
Stage 1: Let U represent a slot holding a US competitor, and let _ represent a slot holding a non-US competitor.  The first three slots must be one of the following:

U _ _
_ U _
_ _ U

This is where the $\binom{3}{1}$ comes from, since we are choosing one of three slots to be the U slot.  The middle four slots have to be _ _ _ _.   There is only one way to do this—we could write this as $\binom{4}{0}$ since we are choosing zero of the four slots to be U slots, or we could simply omit this factor.  The last three slots must be one of the following:

U U _
U _ U
_ U U

This is where the $\binom{3}{2}$ comes from: we are choosing two of three slots to be U slots.
Stage 2: We now have a slot arrangement, of which _ U _  _ _ _ _  U U _ is an example.  (There are a total of nine possibilities.)  We now have to fill the blank slots with the three non-US nationalities.  There are $\frac{7!}{4!\,2!\,1!}$ ways to do this.
Note: Since we only care about which nationality occupies which slot, and not which individual competitor, at no stage should we be selecting individual competitors from the set of competitors of a given nationality.  I think this is where you went wrong.  (You selected two particular US competitors from the set of three US competitors.  There is no reason to do this.)
Alternative solution: I think Method 1 is a bit confusing because in Stage 1 we are choosing slots, whereas in Stage 2 we are permuting nationalities and dividing out repeats.  A more uniform method would be to think of the entire process as one of choosing slots.  If we take this point of view, there there are

$\binom{3}{1}$ ways to choose one of the first three slots for the US.
$\binom{3}{2}$ ways to choose two of the last three slots for the US.
$\binom{7}{2}$ ways to choose two of the slots not yet assigned for China.
$\binom{5}{4}$ ways to choose four of the slots not yet assigned for Russia.
$\binom{1}{1}$ way to choose the remaining unassigned slot for Canada.

I believe this is what's going on in Method 2, although they wrote the factors in an unnatural order.
Comment: It, in fact, does not matter in which order you place the nationalities, but if you do it in your order: Russia, China, Canada, then the expression would be $\binom{7}{4}\binom{3}{2}\binom{1}{1},$ which does equal $\binom{7}{2}\binom{5}{4}\binom{1}{1}$.  This is because the products "telescope" so that there is systematic cancellation between the denominator and numerator of successive factors.  So, for example, the expression $\binom{7}{2}\binom{5}{4}\binom{1}{1}$ can be written $\frac{7!}{2!\,5!}\frac{5!}{4!\,1!}\frac{1!}{1!\,0!}=\frac{7!}{2!\,4!\,1!}$ where we have cancelled factors$\ldots$
Comment: $\ldots$of $5!$ and $1!$, and dropped the factor of $0!$ in the denominator.  The expression $\binom{7}{4}\binom{3}{2}\binom{1}{1}$ telescopes similarly: $\frac{7!}{4!\,3!}\frac{3!}{2!\,1!}\frac{1!}{1!\,0!}=\frac{7!}{4!\,2!\,1!}$.  You always get $\frac{7!}{2!\,4!\,1}$ with the denominator factors permuted depending on which nationality gets placed first.  So if we do Canada, China, Russia, we get $\binom{7}{1}\binom{6}{2}\binom{4}{4}=\frac{7!}{1!\,2!\,4!}$.
Comment: @user1527227 : Basically the second denominator factor in each binomial coefficient cancels with the numerator of the next binomial coefficient, except for the last one, where this factor is always $0!$.  Therefore you always get the same answer as you get by the divide-out-repeats method.  Also, you aren't "allowing China to have 7 slots".  What you're doing is giving 2 out of 7 slots to China.  I also give 4 of those slots to Russia, but if since I do Russia second, I can't give them the 2 slots I already gave China.
Comment: Thanks Will.  I understand your stage 1 explanation--its fantastic.  However, your Alternative Solution is not entirely clear to me.  From your explanation, I now understand the terms $\binom{3}{1}$ and $\binom{3}{2}$. However, the rest of the terms are still not clear to me.  For instance, **why did choose to fill in the slots in the order that you did**:  China, Russia, and then Canada.  What if someone wanted to fill in the slots in this order:  Russia, China, and Canada.  Then it would be $\binom{7}{4}\binom{5}{2}\binom{1}{1}$.  Right?  Then you wouldn't get the same answer.
Comment: Basically, why do you allow China to have 7 slots?  Why not give the 7 to Russia first if someone wanted to fill in Russia?
Comment: GREAT!!!!  Thank you so much Will.  You explain so well.  I did a test run on another sequence and got the right answer:  Canada, China, and Russia:  $\binom{3}{2}\binom{3}{1}\binom{7}{1}\binom{6}{2}\binom{4}{4}$  Thanks again  :)
Answer: For the second, you pick the slots (not the people-we said all the people from one country were interchangeable) for the two US people in the bottom ${3 \choose 2}$ ways, but then have to pick which slot the US person in the top is in, which adds  a factor ${3 \choose 1}$.  Then of the seven left, you just have $\frac {7!}{4!2!}$ as there are no Americans among them.  So Method 1 is off by the $3!$ in the denominator.  I don't understand the terms in Method 2.
Added:  One way to look at the first part, which I think is the way you did, is to say there are $10!$ orders of the people, but if the Americans are interchangeable you divide by $3!$, for the Russians you divide by $4!$ and for the Chinese you divide by $2!$.  Another way would be to say we pick three slots for Americans in ${10 \choose 3}$ ways, then pick slots for the Russians in ${7 \choose 4}$ ways, then pick slots for the Chinese in ${3 \choose 2}$ ways, giving ${10 \choose 3}{7 \choose 4}{3 \choose 2}=120\cdot 35 \cdot 3=12600$.  Of course the answer is the same, but the approach is better suited to the second part.  Now if you think of choosing slots for nationalities you get what I did before.
Comment: I'm still lost...
Comment: Can anyone else explain the second part of the question?  I still don't understand.  Thanks.

Combinatorics Example Problem


Difference in randomForestSRC and randomForest package / increasing OOB-Error curve

Question: Probably this is related to randomForest vs randomForestSRC discrepancies.
When training this dataset it seems, that concerning the mean missclassification error less trees are better than more in the R-package RandomForestSRC. Is there a specific reason for this? Until now I thought that more trees are always better.
# Installation of OpenML
install.packages(c("mlr", "checkmate", "data.table", "digest", "RCurl", "stringi", "XML", "RWeka", "devtools"))
devtools::install_github("openml/r")
library(OpenML)
saveOMLConfig(apikey = "put_here_your_key_from_openml.org")

task = getOMLTask(task.id = 3595, verbosity=0)
library(randomForestSRC)
run = matrix(NA, 1000, 2000)
set.seed(105)
for(i in 1:1000){
  print(paste(i))
  run[i,] = rfsrc(binaryClass ~., data = task$input$data.set$data, ntree = 2000, importance="none", mtry=2, nodesize = 1)$err.rate[,1]
}
runs = apply(run, 2, mean)
quant1 = apply(run, 2, function(x) quantile(x, 0.25))
quant2 = apply(run, 2, function(x) quantile(x, 0.75))
plot(runs, type="l", ylim = c(min(runs, quant1, quant2), max(runs,quant1, quant2)))
lines(1:2000, quant1, col = "red")
lines(1:2000, quant2, col = "green")

I tried to calculate the same thing with randomForest package, but the results were quite different. Here the curve continues to decrease with adding more trees.
library(randomForest)
run = matrix(NA, 1000, 2000)
set.seed(105)
for(i in 1:1000){
  print(paste(i))
  run[i,] = randomForest(binaryClass ~., data = task$input$data.set$data, ntree = 2000, mtry=2, nodesize = 1)$err.rate[,1]
}
runs = apply(run, 2, mean)
quant1 = apply(run, 2, function(x) quantile(x, 0.25))
quant2 = apply(run, 2, function(x) quantile(x, 0.75))
plot(runs, type="l", ylim = c(min(runs, quant1, quant2), max(runs,quant1, quant2)))
lines(1:2000, quant1, col = "red")
lines(1:2000, quant2, col = "green")

edit: A growing Errorrate-curve is also possible with the randomForest package. See this example:
library(OpenML)
task = getOMLTask(task.id = 3548, verbosity=0)
library(randomForest)
run = matrix(NA, 1000, 2000)
set.seed(108)
for(i in 1:1000){
  print(paste(i))
  run[i,] = randomForest(Type ~., data = task$input$data.set$data, ntree = 2000)$err.rate[,1]
}
runs = apply(run, 2, mean)
quant1 = apply(run, 2, function(x) quantile(x, 0.25))
quant2 = apply(run, 2, function(x) quantile(x, 0.75))
plot(runs, type="l", ylim = c(min(runs, quant1, quant2), max(runs,quant1, quant2)))
lines(1:2000, quant1, col = "red")
lines(1:2000, quant2, col = "green")

Answer: I think I found the solution to the problem, see the code below.
With more trees (e.g.3000), RF is more sure about the classification in a specific class, in comparison with RF with 100 trees.
So in some specific data cases this can lead to the case, that RF with 3000 trees is always wrong while RF with 100 trees sometimes is correct.
The underlying problem is also, that not probabilities are considered but only the most probable case in the majority vote (as well in the trees as in the whole forest).
library(OpenML)
task = getOMLTask(task.id = 3548, verbosity=0)
library(randomForest)
set.seed(108)

preds = list(matrix(NA, 200, 27), matrix(NA, 200, 27))
set.seed(123)
for (i in 1:200){
  print(i)
  preds[[1]][i,] = randomForest(Type ~., data = task$input$data.set$data, ntree = 100)$predicted
  preds[[2]][i,] = randomForest(Type ~., data = task$input$data.set$data, ntree = 3000)$predicted
}

sum(apply(preds[[1]], 2, function(x) names(table(x))[which(table(x) == max(table(x)))] ) == apply(preds[[2]], 2, function(x) names(table(x))[which(table(x) == max(table(x)))] ))

erg = list(matrix(NA, 27, 4), matrix(NA, 27, 4))
for (i in 1:4){
  for (j in 1:27){
    erg[[1]][j, i] = sum(preds[[1]][, j] == i)
    erg[[2]][j, i] = sum(preds[[2]][, j] == i)
  }
}

erg_ges = data.frame(erg[[1]], erg[[2]], task$input$data.set$data$Type)
colnames(erg_ges) = c(paste("100", c("a","b","c","o")), paste("3000", c("a","b","c","o")), "real_value")
erg_ges
   #    100 a 100 b 100 c 100 o 3000 a 3000 b 3000 c 3000 o real_value
#1     88     5   107     0     18      0    182      0          a
#2    173    27     0     0    200      0      0      0          a
#3    200     0     0     0    200      0      0      0          a
#4     84   116     0     0     45    155      0      0          a
#5      4   196     0     0      0    200      0      0          a
#6    176    24     0     0    200      0      0      0          a
#7      2   198     0     0      0    200      0      0          b
#8    199     1     0     0    200      0      0      0          b
#9    103    97     0     0    152     48      0      0          b
#10     0   200     0     0      0    200      0      0          b
#11     0   200     0     0      0    200      0      0          b
#12     0     0   200     0      0      0    200      0          b
#13     2   198     0     0      0    200      0      0          b
#14     0   200     0     0      0    200      0      0          b
#15     3   197     0     0      0    200      0      0          b
#16     0   198     2     0      0    200      0      0          b
#17     0     2   198     0      0      0    200      0          c
#18     0    10   190     0      0      0    200      0          c
#19     0   171    29     0      0    200      0      0          c
#20     0    94    66    40      0    188     12      0          c
#21     0    23   177     0      0      0    200      0          c
#22     5   195     0     0      0    200      0      0          b
#23     0   107    93     0      0    134     66      0          c
#24     0   198     1     1      0    200      0      0          b
#25   198     2     0     0    200      0      0      0          a
#26    31   155     0    14      0    200      0      0          o
#27     0   200     0     0      0    200      0      0          o


About Clojure's Laziness

Question: I feel curious about clojure's lazy sequence. In REPL, I defined a variable foo:
user> (def foo (map println [1 2 3]))
#'user/foo

At the first time evaluating foo, it seems to work:
user> foo
1
2
3
(nil nil nil)

But after the first time, why it becomes lazy?
user> foo
(nil nil nil)

Answer: println is not a pure function, what you're seeing in the first time you evaluate foo is the side effect of println. When you evaluate foo for the second time println is not called again, because the result of (map println [1 2 3]) is cached.
And you can see that map is lazy because when you defined foo nothing gets printed in the console. Only when evaluating foo something is printed.
Please see Laziness in Clojure.
If you use a pure function like inc:
(def foo (map inc [1 2 3]))

> foo
(2 3 4)

> foo
(2 3 4)

The result is always the same without any side effects. map, filter, etc in Clojure are designed to be used with pure functions but the language doesn't forbid you from using them with functions with side effects. In Haskell, for example you can't even write an equivalent expression, the code won't compile.
Comment: The result is a `seqable` that contains the result of applying `println` to every element of the sequence `[1 2 3]`. But `println` returns `nil` so the `seqable` returned by `map` is `(nil nil nil)`.
Comment: So, the result of (map println [1 2 3]) is cached after the first run; the cached result is not the sequence itself, but is a seqal object. Is my understanding right?
Answer: Collections hold values. The value returned by println is nil. The side-effect of println is to make something show up on your screen.
The values created by mapping println are stored in your var. This is a lazy-seq of nil values, which were returned by println.
Answer: In addition to what has been pointed out by others, note that experimenting with laziness within the repl is a little problematic. Lazy sequences don't actually have values until they are realised by some action that uses the value. The repl has an implicit doall to do this when printing results. This means the sequence is often realised when your using it in the repl, but may not be when using it in your real code.  When you run your code, you get an unexpected result because the sequence has not been realised at a point where you expected it to be because the repl implicit doall has not been called. As an example of how this can cause moments of confusion, have a look at http://nicksellen.co.uk/2013/10/26/clojure-lazy-repl.html
Comment: This post is pretty important for new clojure developers. Thank you very much!
Answer: Just to elaborate on your question.
println is only having a side effect on the *out* stream which is bound by default to the standard output.
You can have both the printing and some value returned from the function you map, e.g.
user> (defn print-and-inc [n]
        (do
          (println "called with n= " n)
          (inc n)))
#'user/print-and-inc

do will execute each expression in sequence and return the result of the last, (inc n) in this case.
If you define now foo as a mapping of print-and-inc over a vector of int
user> (def foo (map print-and-inc [1 2 3 4 5]))
#'user/foo
user>
user> foo
called with n=  1
called with n=  2
called with n=  3
called with n=  4
called with n=  5
(2 3 4 5 6)
user>
user> foo
(2 3 4 5 6)

And you see the lazyness of map, since the printing occurs only the first time foo is called.  But now foo holds the results which are the incremented values of the initial collection.
Note : this can be used to log/trace infos into your code, but there is a standard library tools.logging

About Clojure's Laziness


Lie Group of $C^k$-curves?

Question: Is there a $k \in \mathbb{N}\cup \{\infty\}$ such that $C^k(\mathbb{R})$ forms an infinite-dimensional Lie group?  In general I'm assuming they form a Lie-Groupoid with point-wise multiplication?
If so, for which of these $k$ is there a well-developed theory and where could I find some references?
Thank you.
Comment: What is $C^k(\infty,\infty)$? Do you mean $C^k(\mathbb{R})$?
Comment: Yes, sorry morning typo
Answer: Infinite-dimensional Lie groups are usually required to be Banach manifolds, which $C^k(\mathbb{R})$ isn't. In any case, pointwise multiplication cannot be used to give a group structure, unless you only take the non-vanishing functions (and get an abelian topological group). Pointwise addition gives $C^k(\mathbb{R})$ the structure of an abelian topological group.
Also, pointwise multiplication does not make $C^k(\mathbb{R})$ into a groupoid, as there is no object inclusion map.

Lie Group of $C^k$-curves?


Does a solution with a minimal norm mean it is a solution that minimizes the residuals?

Question: I have an under-determined system of linear equations, which is not full rank (i.e. one or more column vectors are linearly dependent) and has more equations than unknowns.Here is just one example of this:
$$
  {\begin{bmatrix}
    6 & 40 \\
    6 & 40 \\
    3 & 20 \\
  \end{bmatrix}}
  \begin{bmatrix}
  \beta_{0} \\
  \beta_{1}
  \end{bmatrix} \approx
  \begin{bmatrix}
  0.5 \\
  0.2 \\
  0.6 \\
  \end{bmatrix}
$$
If I solve the above example for the least squares solution (i.e. solve $A\vec{x}\approx\vec{b}$), the solution produced will come from a set of solutions $S$ that is infinite in length (i.e. $|S| = \infty$). However, is it possible to minimize the residuals (i.e. get the best model that minimizes the error) from this infinite set of solutions $S$?
This question is sparked from a response I got on StackOverflow (SO) and from what I read on this forum. For example, on my SO post, user @AGN Gazer says the following:

"A solution with a minimal norm does not mean a solution that minimizes residuals. [...] Having a solution with a minimal norm means nothing to me[.] [...] I want the "best" solution - the one that minimizes the residuals but I cannot get it with an underdetermined system."

However, on the accepted answer on this Math Exchange post, it appears that @Brian Borchers says otherwise:

"[We're] often interested in the minimum norm least squares solution. That is, among the infinitely many least squares solutions, pick out the least squares solution with the smallest $∥x∥_{2}$ [(i.e. euclidean norm: $\| x \|_{2} =\sqrt{\sum_{i=1}^{n}x_{i}^{2}}$)]. The minimum norm least squares solution is always unique."

I must be misunderstanding something! In relation to my question above, what even is the distinction between minimizing the residuals and minimizing the norm?
Comment: @RodrigodeAzevedo I thought that too, but was told that is incorrect. If you have more equations than unknowns, but one or more of the column vectors is linearly dependent, then it is no longer full rank is thereby **under**determined.
Comment: @RodrigodeAzevedo Take a look at my SO post above, which gives an example of this! I am now extremely confused by all the conflicting information I am getting.
Comment: Least-squares minimizes $\| A x - b \|_2^2$. Least-norm minimizes $\|x\|_2^2$ subject to $A x = b$. Combining the two, minimize $\| A x - b \|_2^2 + \gamma \|x\|_2^2$ with $\gamma > 0$. What exactly do you want?
Comment: If I use `ordinary least squares` (`OLS`) on the system I described above, can I *minimize the residuals*? Are you saying that *minimizing the norm* and *minimizing the residuals* are two separate operations, with *minimizing the norms* meaning finding the smallest norm for the **parameters** and *minimizing the residuals* meaning finding the smallest error of the output?
Comment: Does $A x = b$ have zero or infinitely many solutions? If zero solutions, use least-squares. If infinitely many, use least-norm. However, the fact that $A$ does not have full column rank means that there will be infinitely many $x$'s that produce minimal $\| A x -b \|_2^2$.
Comment: So you are saying that I **can** minimize the residuals with under-determined systems? I want the model that produces the highest $R^2$ and thereby minimum residuals.
Comment: Least-norm is about finding the shortest input $x$ that solves $A x = b$ (zero error). Least-squares is about finding the input $x$ that minimizes the output error $\| A x - b \|_2^2$.
Comment: @RodrigodeAzevedo So the user on SO that said the above comment is grossly incorrect?
Comment: What solution? Does $A x = b$ even have a solution? Note that in the context of least-squares, one has the original linear system $A x = b$ and the **normal equations** $A^\top A x = A^\top b$ (a linear system that always has at least one solution). Please edit your question and specify what exactly you want. Quoting other people only adds noise to the discussion.
Comment: @RodrigodeAzevedo I quoted people because I believe they are two contradicting answers to the same question. I have stated my question multiple times in the question above and even in the comments. In my question I said "I will be pulling from a set of solutions that is infinite in length." So yes, it has many solutions. Did you read my entire question instead of just skimming it?
Comment: Which set is that? The solution set of $A x = b$ or the solution set of $A^\top A x = A^\top b$ ?
Comment: @RodrigodeAzevedo Take a look at my question above. I have re-edited it.
Comment: The example you gave ($3 \times 2$) is infeasible. The set of solutions is empty.
Comment: @RodrigodeAzevedo What? I am finding a plane that goes through this data. To say no solutions exists is impossible because I can plot these equations and draw a plane at random. There is a solution! If you use any least squares solver, you WILL get a solution. I heavily disagree with you.
Comment: Subtract the first two equations and you get $0 = 0.3$. Infeasible. The good news is that least-norm is no longer an option. All least-squares solutions (and there are infinitely many of them) produce the same error norm and none of them solve the original system, of course.
Comment: You have a severe misunderstanding. A *solution* is an assignment of values *that satisfies the equations*. There is no assignment of values to $\beta_0$ and $\beta_1$ that satisfies all three equations, so there is no solution. You cannot take an arbitrary assignment of values at random and say it is a solution. Otherwise, I could solve any complicated equation just by picking some random numbers.
Answer: In your example, there is no exact solution of $Ax = b$. Because $A$ is not full rank, the least squares solution is not unique.
The minimum 2-norm least squares solution is that least squares solution for which $\|x\|_2$ is minimum among those least squares solutions.  I.e., consider all least squares solutions achieving the same sum minimum squared residuals value, $(Ax-b)^T(Ax-b)$, then minimizing 2-norm of x among those solutions can serve as a tie-breaker to choose from among the solutions achieving the minimum sun squared residuals value.  The minimum 2-norm solution can be found using the pseudoinvserse (pinv in MATLAB) of $A$, as shown below.  Note that if $A$ is full rank, then the least squares solution is unique, and therefore, is the minimum 2-norm least squares solution.
Here is an illustration in MATLAB on your example.  As can be seen, in this example, the QR and SVD (minimum 2-norm) solutions have the same residuals, but $\|x||_2$ is smaller for the SVD solution than the QR solution.
<code>>> disp(A)
     6    40
     6    40
     3    20
>> disp(b)
   0.500000000000000
   0.200000000000000
   0.600000000000000
>> QR_solution = A\b
Warning: Rank deficient, rank = 1, tol =  2.307555e-14.
QR_solution =
                   0
   0.011111111111111
>> A*QR_solution - b
ans =
  -0.055555555555556
   0.244444444444444
  -0.377777777777778
>> norm(QR_solution)
ans =
   0.011111111111111
>> SVD_solution = pinv(A)*b
SVD_solution =
   0.001629991850041
   0.010866612333605
>> A*SVD_solution - b
ans =
  -0.055555555555556
   0.244444444444444
  -0.377777777777778
>> norm(SVD_solution)
ans =
   0.010988181698537
</code>


Open a pop up for a single item in the list

Question: I have the list of items. But i am showing one of the sample code.
I have the following HTML code

Refer your friends

".elgg_view("addthis/extend", $vars)."

This is repeating for ten times but i have the different id for all buttons like id="39342"
So when i click the refer your friends button the strapline_share_buttons is opening for all items so i need to show for one item.
My jQuery:
$("a.refer_freinds").click(function(){
        var item_id =  $(this).attr("id");
        //$( ".strapline_share_buttons").toggle();
        $(this).$( ".strapline_share_buttons").toggle();
        });
        $(".strapline_share_buttons").popup("open", {
            "transition": "pop"
        });

So how to do it?
Comment: $(this).$( ".strapline_share_buttons").toggle(); what is this ..remove $
Comment: No after removing its not working
Answer: If I right understood question and html layout, this code must be working.
$("a.refer_freinds").click(function () {
    var item_id = $(this).attr("id");
    //go to parent and next element in DOM and show that
    //
".elgg_view("addthis/extend", $vars)."

    $(this).parent().next().show()
        .popup("open", {
        "transition": "pop"
    });
});

http://jsfiddle.net/9H9jq/2/
Comment: For example, may add this event listener $(this).parent().next().click(function(){$(this).hide();}); this hiding  when that clicked.
Comment: Okay its working fine but can we again toggle that if outside cliking the box or inside clicking the box ?? Box means which was toggled earlier...
Comment: May change $(this).parent().next().show() to $(this).parent().next().toggle() this will toggle element then we clicked to  link.
Comment: No we need to use the mouse up fuction...any way thnx for ur effort & time.....here your first answer will be accepted...
Comment: @Magistr_AVSH how would you do that in this very same example, that "Refers your friends" only shows the actual referral number? I mean, if there are other shown referral numbers, then it closes them in parallel with showing it's own ref num? thank you in advance


CART - Classification And Regression Trees

Question: I try to prune one regression tree build with the rpart function in R.
To decide where to prune the tree I used the plotcp function. But I noticed that if I use the same predictor variables and in the same order the plotcp graph always change? How is this possible?
Thank you for your explanation in advance.
Comment: @whuber, I recommend to make "cart" tag a junior synonym of "decision-tree" or "classification-tree". Because, often CART acronym is regarded to be just a particular _method or algorithm_ of the tree, along with other methods such as CHAID or QUEST.
Answer: If you re-run just plotcp you should get the same exact plot. But if you re-run rpart you will get different fits because randomization is involved. You can avoid this by setting a seed before each run of rpart.
e.g.
fit1 <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis)
plotcp(fit1)

fit2 <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis)
plotcp(fit2)

will yield two different trees and thus two different fits, and the plot will reflect that. But
plotcp(fit2)
plotcp(fit2)
plotcp(fit2)

should be identical, as should,
set.seed(10020101)
fit1 <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis)
plotcp(fit1)

set.seed(10020101)
fit2 <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis)
plotcp(fit2)

Comment: I have found out: for computation of the xerror and xstd it uses cross validation and splitting data set to folds for CV is random. So decision tree is indeed computed in exact way, but estimation of error and its std is random.
Comment: Where is the random part in RPART algorithm? I thought that the splits are computed in exact way. What is random?
Comment: I am not sure where the random part comes in, but it must be there, as keeping the seed constant makes the output constant. However, the rpart part stays the same; the random element is somewhere in plotcp.
Answer: This analysis may be done when regression trees include controls which allow you to limit which variables are allowed to enter the tree at any specified depth of the tree. Suppose we had the example of students in schools in districts with variables relevant to each level in the data. Then we might organize a tree so that it follows a pattern like:
Depth 0 through 2: splitters are district characteristics
Depth 3 and 4: splitters are school characteristics
Depth 5 and below: splitters are student characteristics
Of course we cannot know in advance where to draw the boundaries in the tree so experimentation would be mandatory....and I would invite more people from the forum to jump in and share with us views about statistical rules of thumb of how to solve this...
With regular CART you could start three analyses each using the relevant predictors for that level.
So start with district predictors and build tree. Save predicted scores and residuals.
Take residuals as new dependent variable and use only school variables. Save predicted vales and residuals.
Take second stage residuals as dependent variable and use student vars as predictors. Save predictions and residuals.
Final predictions are sum of the predictions of the three trees.
I welcome ideas and corrections about this...


How can I remove an entry from the blog front page?

Question: If you enable the Blog core module in D7, you have a multiuser blog. It will produce a blog front page for all blog entries published at the path /blog.  It is just like the ordinary front page <front>, but only show nodes of type "blog".  By default, all published blog nodes appear on the blog front page.
For the site's default front page there is checkbox "Promoted to front page" under "Publishing options". Unchecking that prevents the node from appearing on the default front page.
Adding a similar checkbox field named "Promoted to blog front page" to the "blog" content type will of course do nothing by itself.
I want to use this field to control whether a blog node appear on blog front page, but have not found a "hook" or a "preprocess-function" or similar Drupal-thing that let me do so with the view of blog teasers that the core blog module produces.
I know I can do this by replacing the blog core module with my own, using Views to produce the list of teasers for the blog front page.
But in this question, I am looking for a way to do this with the view produced by the core blog module?
Is this possible, or must I use Views if I want this?
Answer: The blog module builds this page in the function blog_page_last().
The query in blog_page_last() does have a node_access tag so you could use hook_query_TAG_alter() to add a condition but may be tricky to just target that one query on that page.
I think a better option would be to use hook_menu_alter() to change the callback for the blog menu item to a function in your own module. In this function you can just copy the code from blog_page_last() but add a additional condition for your new promoted field.


find the key of songs related to theory of music

Question: How can we find the key of any song? If we know the key then it might be easy to find the chord progression, but if we don't know whether that particular song is in major or minor or blues then how do we know the chords? So how can I find the key of any song?
Comment: We usually know if a song is in major, minor or blues by listening to what  sort of chords are in the song. I'm pretty sure the other part of the question has been answered before. See the list on the right of the page.
Answer: There is a technical, and a non-technical answer to this question.
Ill do the non-technical one, because I would assume that since you are asking, then you would prefer a simpler less technical answer.
Listen to the song and discover the point in which the song seems to "Resolve".
To use an example.
"London bridge is faling down...falling down , falling down...
London bridge is falling down....( And here you "feel it resolve)
"My fair Lady"....
The last syllable.."Lady" specifically,the "Dy"... is the tonic or first note , the scale key note you're looking for.
Most songs have this effect. and discovering the note that determines the scale is a similar process. Getting the "Feel" for that resolving note, is only attained with practice. I suggest sitting next to a keyboard and listening to several songs and practicing the process. Eventually it will become second nature, and then the next step is to be able to recognize what the pitch of that note is without the piano! good luck
Comment: Ya sir i can find it by keyboard..bt if the song is on c key..bt how can i find tht its mjor or minor or any scale??by practice i can find this..bt can you plz tell me the technical theroy..or jst point down the step from basic to advance..bcz in youtube..there is lots of theory related to music.like dominant agmented or etc.so i cant find it whts the perfect series to understand music..plzz help me..thanks
Answer: Having read your comment - When you've found the key note/root note, if the thing's in major, try playing the third note of that particular scale. For example, let's say you find a piece is in C. The third note of that scale is E or Eb. If the E sounds like the last chord, it'll be in C major. If Eb fits better, it'll be C minor.
I hope that's solved what you're looking for, although the majority of players would be aware if it's major or minor as a matter of course.A session with a teacher will sort it out, as we say often on this site!


URLs aren't working after site migration

Question: My problem is two fold:

After migrating my site, many of the URLs aren't working, and producing 404 errors. But the main landing page is working, and so are most/all of the features on the main page.
My configuration for custom 404 error pages are being ignored, and were working before copying the root of the web server files over. This I'm not so worried about.

These are the steps I used to migrate the site:

mysqldump the database from the originating server.
Import the database to the new server, using the same mysql credentials.
Copy the root of the web server files over to the new location.

This is my setup:
CentOS6
nginx
MySQL
php, php-fpm
Drupal 7
The only real difference between the originating server and the target server is that the originating server is centos5.
I am not a drupal expert, but I did some searching and I keep coming across "clean urls". I'm not exactly sure what that is.
Is there a better way to migrate a drupal site, or is there something I did wrong?
Comment: Have you set up nginx specifically for Drupal? eg. as recommended here: http://wiki.nginx.org/Drupal
Answer: This indeed sounds like a clean URL problem.
Standard Drupal URLs use query strings like: www.example.com/?q=string/string/site
Clean URLs rewrite this to www.example.com/string/string/site which is better for SEO.
Check the browser's adress bar to see if clean URLs are working. If not and if you used them on the previous install, you need to either deactivate them in drupal or get them working again. You need to activate it in settings and use correct .htaccess with Clean URLs rewrite rule.
The reason why the home page is working is that there is no query string in www.example.com/
Answer: I'm sure there are different ways to do this, but I've been successful using the Backup and Migrate project. Follow the directions in this great article: http://www.seascapewebdesign.com/blog/how-transfer-your-website-one-server-another


how can we deploy xap file directly to windows phone?

Question: i have an app which is ready to test on device but neither i have unlock device nor i want to install zune software on system.
I just want to send xap file to a device & then want to test on it.
is it possible ?
Look guys i am new in Windows phone development.
i don't have any developer account & also any unlocked device.
i just made a new app & now i want to test it on a device..
please tell me the process how to do that ?
Comment: [How to deploy XAP file](http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402565(v=vs.105).aspx)
Answer: The device has to be developer unlocked or the .xap file has to be downloaded from the store.
You can submit the app to the store as a private beta - only the users which emails you specify will be able to install the app. The app doesn't go through certification and is ready for download in a couple of hours.
Comment: @ToniPetrina AFAIK the beta tester's phone doesn't need to be unlocked.
Comment: @user3349583 If you have an unlocked phone, then you can connect it via USB and deploy App directly. If you have developer account then you can publish beta version of the App and add your friends e-mail to beta testers list, then he will be able to download the App from the link you will receive from Windows Store.
Comment: is it possible that i directly send xap file to windows phone device & then test it because i don't have device to test right now & one of my friend have Windows phone but the device is not unlocked...
Comment: @user3349583 no. if that was possible, the option of unlocking the device would be useless..
Comment: @user3349583 It is like lisp has said - if you don't have a phone, you will have to find a beta tester. For that purpose you have to have a developer account. The friend's phone then doesn't need to be unlocked. Thought developing this way can be hard. [More information about beta testing](http://msdn.microsoft.com/en-us/library/windowsphone/help/jj215598(v=vs.105).aspx).
Comment: @user3349583 No, the device **must** be unlocked.
Comment: But you have to have an account for beta testing, isn't that correct?
Comment: if i have a developer account & i give my credentials to a tester then  it would be possible to send xap directly to windows phone which is unlocked ?
Comment: for beta testing, it is necessary to unlock device or just install app from beta account?
Comment: @user3349583 the device deosn't have to be unlocked. During submision you specify the microsoft-account-email that beta-tester's device is connected to and that's all - he can download and install.


How to render MIDI stems through a single intrument track in Reaper?

Question: I have a project in Reaper with 255 individual MIDI tracks, all nested under a folder track on which I added a Virtual instrument to avoid configuring each track individually.
This way, I can play any track, and since they all route to the instrument track, I can listen to their sound.
However, when I try to render the project as stems, all 255 stem files are mute, and the instrument track is rendered as if it contains all the tracks.
How can I produce these stems with the actual sound generated by the instrument, as I hear them in Reaper?
Answer: That is very easy, batch rendering is very flexible and powerful in Reaper.

Select all stems you want to render.
Open Menu -> File -> Render
In Source: Selected media items via master
In Output: Select the desired wildcards option for output file names (since you will have a lot of them, it is good to create meaningful names).
Click Render Files at the bottom.

If each track were to contain several stems, select the tracks instead of the stems, and in step 3: Selected tracks via master.


Padronização de Controller Web API

Question: Gostaria de saber o seguinte.
Imaginem as seguintes URI:
(1) api/pedidos
(2) api/pedidos/10
(3) api/pedidos/10/itens
A URI (1) e (2) estou certo de que estariam dentro de um classe chamada PedidosController, já a (3), estou com dúvida se seria na mesma ou em outra classe chamada ItensController.
Qual o correto?
Answer: Como esta trabalhando micro serviço acredito que melhor maneira seja deixar separado mesmo
PedidoController
api/pedidos
api/pedidos/10
ItemController
api/item // todos itens
api/item/{id} // item com determinado id
artigo falando sobre assunto :
https://msdn.microsoft.com/pt-br/library/dn376303.aspx
Comment: Eduardo, boa tarde e obrigado pelo retorno.

Então, mas se você olhar o artigo que você citou, ele faz diferente do que você recomendou, pois:

O método de recuperar os álbuns dos artistas está no ArtistasController e não no AlbunsController.

E entendo que isso é a mesma lógica do meu exemplo, assim como pedidos tem itens, artistas tem álbuns.

Padronização de Controller Web API


Regression Using Surveys with Unequal Number of Responses

Question: I am trying to figure out how to properly do regression analysis on a data set from a peer-review survey where individuals in the survey have an unequal number of responses. Below is description of my actual problem.
Consider a population consisting of $N$ individuals. You send a survey out to all $N$ individuals asking them to rank the quality of everyone (including themselves) in that population wrt some property based on a scale from NR (not rated) to 2,3,4,5. The NR responses are not counted. Suppose that $n$ of the $N$ individuals respond.
Some individuals in this population are of very high quality and so receive rankings from almost everyone in the population that respond (i.e. most of the $n$ responses are not NR). Conversely, some of the individuals are not of high quality and do not receive many rankings. For individual $i$, let $S_i$ denote the sum of all the rankings from the surveys received which are not NR and let $n_i$ denote the number of surveys received for individual $i$ which do not have NR rankings, from which we compute its overall score as $r_i$ = $S_i/n_i$.
Suppose you $only$ know $r_i$ for each individual and do $not$ have access to the original data (and so you do not know $n_i$ for each individual) and want to perform a regression analysis on the scores for some given set of covariates. My question is: how can one compensate or take into account the differences in the number of responses? Would weighted least squares naturally take into account that the individuals with more NR responses should "fit" the data better?
Thank you,
Matt
Answer: First of all, this is a painful situation to be in, and if there's any chance you can get the original $n_i$s (or $i_i$s), then by all means pursue that before continuing. (You should also get the original number of people who received surveys, so you can distinguish missingness due to non-response from missingness due to choosing "NR".) You probably already knew that, but I figured it's worth being explicit.
It doesn't look you have any way to estimate the $n_i$s directly. You said you expect that people who get higher ratings on average will have been rated by more people, but that fact alone doesn't get us very far without an $n_i$ for anybody. So it looks like the most you can do is use a regression method that resists heteroscedasticity. Some suggestions can be found here and here.

Would weighted least squares naturally take into account that the individuals with more NR responses should "fit" the data better?

Not automatically. Weighted least squares requires specifying the weights (in this case, the $n_i$s).
Comment: I appreciate your comments and concur with everything you've said. Unfortunately, the institution holding the data (which is U.S. News and World Report, FWIW) will not release the original data to me and mathematically, I can obtain the $n_i$ from the data itself. I actually did a trial run to try and see if the residuals showed evidence of heteroscedasticity (both by visual inspection and using White's test) and they did not, so my original idea will not apply to the data set with which I am working. Thanks again.
Comment: If you felt my answer was satisfactory, remember to accept it by clicking on the check mark under the voting arrows.


What does it mean to factor a joint distribution?

Question: A book I'm reading (Hogan & Mason, 2012, p37) contains the following passage:

The joint distribution can be factored in two different ways into
  conditional and marginal probabilities that reveal different aspects
  of forecast quality. The calibration-refinement factorization is given by
  $p\left ( \hat{x},x \right) = p\left (x\mid \hat{x}\right)p\left (\hat{x}\right)$
  [...]
  The second way of factoring the joint distribution is known as the likelihood-base rate factorization and is given by
  $p\left ( \hat{x},x \right) = p\left (\hat{x}\mid x\right)p\left (x\right)$

The context for this passage is the discussion of 2 × 2 contingency tables, where the rows represent binary forecasts and the columns represent binary outcomes. On p32 of the same book a schematic table of this sort is provided.

Ideally I'd hope for an answer that doesn't just provide a correct definition, and which also helps to build intuitions about what factorization means and what the point of it is.
Hogan, R. J., & Mason, I. B. (2012). Deterministic forecasts of binary events. Forecast Verification: A Practitioner's Guide in Atmospheric Science, Second Edition, 31-59.
Comment: @GeoMatt  Very nicely done! (+1).  Your clear and focused exposition, including appropriate links to terms you use, makes for an admirable answer.
Comment: As far as I know, it is *literally* expressing a probability distribution as a product of factors, i.e. $p=p_1p_2\ldots$. More helpfully, it usually refers to something called graphical models. Wikipedia has some OK examples [here](https://en.wikipedia.org/wiki/Bayesian_network) and [here](https://en.wikipedia.org/wiki/Factor_graph). (The ones with pictures near the top of the articles. The equations are fine too, but a lot more opaque!)
Comment: If I had to guess it''s saying something about how the joint distribution for two discrete random variables $X$ and $Y$ can be written as $p(x|y)p(y)$ and also $p(y|x)p(x)$. I have no idea what $X$ and $Y$ are, though
Comment: @GeoMatt Usually it's more than that: the factors need meaningful interpretations as marginal and conditional probabilities or probability densities.
Comment: @whuber yes, I was sloppy. The links I gave explain it better. In areas I run into, the term "factor" would usually not be used for something like Taylor's example, which always holds for any $p(x,y)$. It would normally be associated with conditional independence relationships, I believe?
Comment: @GeoMatt I'm not quite following what "always holds" means.  As the quotation indicates, a factorization of a joint distribution into a marginal and conditional distribution is not unique.  Often this can be done in a great many ways. For example, the standard binormal distribution factors into a Uniform$(0,2\pi)$ distribution and a $\chi^2(2)$ distribution (which in this case are independent).
Comment: @whuber point taken. Below I actually tried to answer the question that was asked :)
Answer: If I am understanding the passage and table correctly, there are essentially two answers: mathematical and qualitative.
Qualitatively, the "different aspects of forecast quality" is essentially the idea of false positives vs. false negatives, or precision vs. recall. (I will come back to this.)
Mathematically, the table is comparing two binary variables
$$F =\text{Was an event forecast?}\quad\text{vs.}\quad O =\text{Did an event occur?}$$
and tallying their co-occurences.
The empirical joint distribution of these variables would be
$$
\begin{bmatrix}
p(\phantom{\sim}F,O) & p(\phantom{\sim}F,\sim\!O) \\
p(\sim\!F,O) & p(\sim\!F,\sim\!O) \\
\end{bmatrix}
=
\frac{1}{n}
\begin{bmatrix}
a & b \\
c & d \\
\end{bmatrix}
$$
where
$$\sim\!F=\text{not }F \quad,\quad \sim\!O=\text{not }O$$
and $n=a+b+c+d$.
The marginal probabilities appear in the margins of the table, and give the total probabilities for forecasts (row sums)
\begin{align}
p(\phantom{\sim}F) &= p(\phantom{\sim}F,O) + p(\phantom{\sim}F,\sim\!O) = \frac{a+b}{n} \\
p(\sim\!F) &= p(\sim\!F,O) + p(\sim\!F,\sim\!O) = \frac{c+d}{n}
\end{align}
and observations (column sums)
\begin{align}
p(\phantom{\sim}O) &= p(F,\phantom{\sim}O) + p(\sim\!F,\phantom{\sim}O) = \frac{a+c}{n} \\
p(\sim\!O) &= p(F,\sim\!O) + p(\sim\!F,\sim\!O) = \frac{b+d}{n} \\
\end{align}
What is not shown in the table are the conditional probabilities. For example what is the probability of an event given that one was forecast? This is given by
$$p(O\mid F)=\frac{p(F,O)}{p(F)}=\frac{a}{a+b}$$
(which could be called the precision). The complement of this would be the fraction of false alarms $p(\sim\!O\mid F)$ (or false positives, more generally).
Another perspective would be to condition on $O$. For example the fraction of events that were forecast is given by
$$p(F\mid O)=\frac{p(F,O)}{p(O)}=\frac{a}{a+c}$$
(which could be called the recall). The complement of this would be the fraction of false negatives $p(\sim\!F\mid O)$.
Mathematically, these perspectives correspond to two different ways of factoring the joint probability
$$p(O\mid F)\,p(F)=p(F,O)=p(F\mid O)\,p(O)$$
(Due to this, a punny personality such as myself might describe the joint probability as the "missing link" in Bayes theorem!)
Comment: For intuition I think "forecast" vs. "observed" is better than $\hat{x}$ vs. $x$ (or is it the other way?), so the table is clearer for me :)
Comment: Thanks! Prior to reading your answer I added a few more lines from the original source, since I realised that amount of context I initially provided was perhaps insufficient.


Using pairwise comparision on gls object

Question: I have one factor (tree genotype) and I analyse its influence on soil content.  I used gls to aply weights on my data because it's a better fitted model.
Here is an exemple of my data with one variable (potassium) :
> dataK <- structure(list(Genotype = c("PB08", "PB08", "PB08", "PB09", "PB09",
+                                      "PB09", "PB10", "PB10", "PB10", "PB13", "PB13", "PB13", "PB16",
+                                      "PB16", "PB21", "PB21", "PB21", "PB23", "PB23", "PB23", "PB25",
+                                      "PB25", "PB25", "PB29", "PB29", "PB29", "PB33", "PB33", "PB33"
+ ), K = c(0.85299241359094, 0.465133054980756, 0.00690267582675159,
+          1.01673068757058, 1.030275834371, 0.834524714326693, 1.03316209040447,
+          1.10298412805863, 1.18155841491109, 0.838705999451807, 0.883919392948746,
+          0.901960535626635, 0.75594651348742, 0.756023068853717, 0.958311561443041,
+          0.673810456005313, 1.08746537546638, 0.960314352517763, 1.0648664379158,
+          1.00746055772745, 0.847776805354443, 1.03812953182887, 0.919747454011172,
+          0.632561226408033, 0.664781889579858, 0.833083943531637, 0.92164628717724,
+          0.622415179403636, 1.03783101178149)), class = "data.frame", row.names = c(1L,
+                                                                                2L, 3L, 11L, 12L, 13L, 21L, 22L, 23L, 30L, 31L, 32L, 39L, 40L,
+                                                                                46L, 47L, 48L, 55L, 56L, 57L, 65L, 66L, 67L, 74L, 75L, 76L, 83L,
+                                                                                84L, 85L))

I know there's a significative difference between my groups so I wanted to do a pairwise comparision with emmeans() but I get an error when I try to look at the output :
> model <- gls(K~Genotype, weights=varIdent(form=~1|Genotype), data=dataK)
> means <- emmeans(model, ~Genotype)
> pairs(means, simple="Genotype")
 contrast    estimate     SE   df t.ratio p.value
 PB08 - PB09  -0.5188 0.2525 2.37 -2.054  0.6378
 PB08 - PB10  -0.6642 0.2483 2.25 -2.676  0.4608
 PB08 - PB13  -0.4332 0.2452 2.14 -1.766  0.7402
 PB08 - PB16  -0.3143 0.2445 2.11 -1.285  0.8970
 PB08 - PB21  -0.4649 0.2734 2.98 -1.701  0.7626
 PB08 - PB23  -0.5692 0.2464 2.17 -2.310  0.5631
 PB08 - PB25  -0.4935 0.2507 2.31 -1.968  0.6683
 PB08 - PB29  -0.2685 0.2523 2.42 -1.064  0.9545
 PB08 - PB33  -0.4190 0.2741 3.06 -1.529  0.8276
 PB09 - PB10  -0.1454 0.0763 3.53 -1.906  0.6793
 PB09 - PB13   0.0856 0.0659 2.37  1.300  0.8960
 PB09 - PB16   0.2045 0.0631 2.01  3.241  0.3631
 PB09 - PB21   0.0540 0.1375 3.33  0.393  1.0000
 PB09 - PB23  -0.0504 0.0700 2.89 -0.720  0.9954
 PB09 - PB25   0.0253 0.0840 4.03  0.301  1.0000
 PB09 - PB29   0.2504 0.0886 3.92  2.826  0.3479
 PB09 - PB33   0.0999 0.1389 2.99  0.719  0.9956
 PB10 - PB13   0.2310 0.0468 2.75  4.936  0.1254
 PB10 - PB16   0.3499 0.0429 2.00  8.164     NaN
 PB10 - PB21   0.1994 0.1295 2.77  1.540  0.8217
 PB10 - PB23   0.0950 0.0525 3.60  1.812  0.7179
 PB10 - PB25   0.1707 0.0701 3.80  2.434  0.4717
 PB10 - PB29   0.3958 0.0755 3.37  5.241  0.0799
 PB10 - PB33   0.2453 0.1310 2.43  1.873  0.7002
 PB13 - PB16   0.1189 0.0188 2.00  6.319  0.1170
 PB13 - PB21  -0.0317 0.1236 2.33 -0.256  1.0000
 PB13 - PB23  -0.1360 0.0356 3.35 -3.820  0.1882
 PB13 - PB25  -0.0604 0.0586 2.50 -1.030  0.9615
 PB13 - PB29   0.1647 0.0650 2.28  2.536  0.4949
 PB13 - PB33   0.0142 0.1252 2.07  0.114  1.0000
 PB16 - PB21  -0.1505 0.1222 2.23 -1.232  0.9133
 PB16 - PB23  -0.2549 0.0302 1.99 -8.432     NaN
 PB16 - PB25  -0.1792 0.0555 2.04 -3.230  0.3624
 PB16 - PB29   0.0458 0.0622 1.93  0.737     NaN
 PB16 - PB33  -0.1046 0.1237 1.98 -0.846     NaN
 PB21 - PB23  -0.1044 0.1259 2.50 -0.829  0.9875
 PB21 - PB25  -0.0287 0.1342 3.08 -0.214  1.0000
 PB21 - PB29   0.1964 0.1371 3.29  1.432  0.8634
 PB21 - PB33   0.0459 0.1739 4.21  0.264  1.0000
 PB23 - PB25   0.0757 0.0632 3.16  1.197  0.9322
 PB23 - PB29   0.3007 0.0691 2.78  4.350  0.1651
 PB23 - PB33   0.1502 0.1274 2.22  1.180  0.9266
 PB25 - PB29   0.2251 0.0833 3.87  2.701  0.3845
 PB25 - PB33   0.0746 0.1356 2.78  0.550  0.9992
 PB29 - PB33  -0.1505 0.1385 2.88 -1.087  0.9542

P value adjustment: tukey method for comparing a family of 10 estimates
Warning message:
In ptukey(sqrt(2) * abst, fam.size, zapsmall(df), lower.tail = FALSE) :
  production de NaN

I tried to do the same without the weights and it worked :
> model <- gls(K~Genotype, data=dataK)
> means <- emmeans(model, ~Genotype)
> pairs(means, simple="Genotype")
 contrast    estimate    SE df t.ratio p.value
 PB08 - PB09  -0.5188 0.148 19 -3.505  0.0560
 PB08 - PB10  -0.6642 0.148 19 -4.488  0.0073
 PB08 - PB13  -0.4332 0.148 19 -2.927  0.1649
 PB08 - PB16  -0.3143 0.165 19 -1.899  0.6697
 PB08 - PB21  -0.4649 0.148 19 -3.141  0.1124
 PB08 - PB23  -0.5692 0.148 19 -3.846  0.0282
 PB08 - PB25  -0.4935 0.148 19 -3.334  0.0780
 PB08 - PB29  -0.2685 0.148 19 -1.814  0.7200
 PB08 - PB33  -0.4190 0.148 19 -2.830  0.1944
 PB09 - PB10  -0.1454 0.148 19 -0.982  0.9900
 PB09 - PB13   0.0856 0.148 19  0.579  0.9998
 PB09 - PB16   0.2045 0.165 19  1.236  0.9565
 PB09 - PB21   0.0540 0.148 19  0.365  1.0000
 PB09 - PB23  -0.0504 0.148 19 -0.340  1.0000
 PB09 - PB25   0.0253 0.148 19  0.171  1.0000
 PB09 - PB29   0.2504 0.148 19  1.691  0.7873
 PB09 - PB33   0.0999 0.148 19  0.675  0.9994
 PB10 - PB13   0.2310 0.148 19  1.561  0.8506
 PB10 - PB16   0.3499 0.165 19  2.114  0.5394
 PB10 - PB21   0.1994 0.148 19  1.347  0.9291
 PB10 - PB23   0.0950 0.148 19  0.642  0.9996
 PB10 - PB25   0.1707 0.148 19  1.153  0.9714
 PB10 - PB29   0.3958 0.148 19  2.674  0.2512
 PB10 - PB33   0.2453 0.148 19  1.657  0.8050
 PB13 - PB16   0.1189 0.165 19  0.718  0.9990
 PB13 - PB21  -0.0317 0.148 19 -0.214  1.0000
 PB13 - PB23  -0.1360 0.148 19 -0.919  0.9937
 PB13 - PB25  -0.0604 0.148 19 -0.408  1.0000
 PB13 - PB29   0.1647 0.148 19  1.113  0.9771
 PB13 - PB33   0.0142 0.148 19  0.096  1.0000
 PB16 - PB21  -0.1505 0.165 19 -0.910  0.9941
 PB16 - PB23  -0.2549 0.165 19 -1.540  0.8596
 PB16 - PB25  -0.1792 0.165 19 -1.083  0.9807
 PB16 - PB29   0.0458 0.165 19  0.277  1.0000
 PB16 - PB33  -0.1046 0.165 19 -0.632  0.9996
 PB21 - PB23  -0.1044 0.148 19 -0.705  0.9991
 PB21 - PB25  -0.0287 0.148 19 -0.194  1.0000
 PB21 - PB29   0.1964 0.148 19  1.327  0.9347
 PB21 - PB33   0.0459 0.148 19  0.310  1.0000
 PB23 - PB25   0.0757 0.148 19  0.511  0.9999
 PB23 - PB29   0.3007 0.148 19  2.032  0.5895
 PB23 - PB33   0.1502 0.148 19  1.015  0.9874
 PB25 - PB29   0.2251 0.148 19  1.521  0.8679
 PB25 - PB33   0.0746 0.148 19  0.504  0.9999
 PB29 - PB33  -0.1505 0.148 19 -1.017  0.9873

P value adjustment: tukey method for comparing a family of 10 estimates

Since I whan to consider the weights, what can I do to solve this issue?
Comment: The problem is that the ptukey() function kind of goes belly-up when the df are too small. You might try using `adjust = "mvt"`.
Comment: Or try `mode = "df.error"` to disable using the Satterthwaite method.
Answer: Rather than emmeans I would recommend that you use the predictmeans::predictmeans() function in R- It will allow you to do pairwise comparisons, and allow you to correct your family-wise error rate for these additional p-values. I believe it is also fine with weights.
Comment: I verified that if you run `predictmeans(..., adj = "tukey", Df = 1.9)` you get NaNs as well. This is because the R function `ptukey()` does not work for df < 2 (and those are exactly the cases where `emmeans()` produced NaNs. Also, just try `ptukey(1,4,1.9)`; you'll get `NaN` and a warning message. Thus, this answer does not solve the problem in any real sense, though it might hide the issue behind a different d.f. calculation.


Using recursive functions in C, why is the output of the following program 012345?

Question: I used the concept of recursive function in the following but from my understanding of the concept, the output of the code should be 0, but the output here is 012345 and I'm not sure how it is working.
Could someone please explain it to me as my College Professor couldn't do so.
#include<stdio.h>
#include<conio.h>

int yo(int a)
{
    if(a>0)
    {
        yo(a-1); //using recursion function
    }

    printf("%d",a); //printing value
}

void main()
{
    yo(5);
    getch();
}

Comment: It helps us believe you're serious if you post code that compiles.  The ```\\``` 'comment' markers won't compile — you meant `//` I assume.  `void main()` also raises hackles; see [What should `main()` return in C and C++](https://stackoverflow.com/questions/204476/) for lots of information.
Comment: Possible duplicate of [How Recursion works in C](https://stackoverflow.com/questions/5631447/how-recursion-works-in-c)
Comment: follow the call step by step on paper ...
Comment: If your professor couldnt explain this then he should probably get fired.
Answer: The printf is after the recursive call; Hence, the "stack" of a-values with which yo is called is 5,4,3,2,1,0, before the last yo-call with parameter value 0 begins to print; then 1,2,...
Use a debugger and try it out!
Answer: first the value of a is 5 when function is called, so this value is stored into stack and condition is checked (5>0) which is true, so next time yo() is called with value 4 and same procedure is repeated until the value of a becomes 0.
now condition is false (0>0), so next statement will be printed with value of a in stack and in stack value is pop like last in first out and will print 012345.


Problemas ao manipular Vector Asset

Question: O Android Studio tá retornando esse erro quando adiciono imagens ao meu projeto, mas as imagens selecionadas são os ícones nativos da IDE.
Answer: Você pode colocar esse valor como default no seu build.gradle:
defaultConfig{
   vectorDrawables.useSupportLibrary = true
}

e coloca também o appcompact nas dependências:
dependencies {
  compile 'com.android.support:appcompat-v7:26.1.0'
}

Comment: ``

Consegui resolver dessa forma. Será q posteriormente ele dá erro novamente dessa forma que fiz? Essa é uma boa prática?
Comment: Da forma que você fez está correto. Você está definindo o xml no drawable e depois colocando como source em um imageview e definindo a cor. Não tem problema nenhum nisso e provavelmente vai funcionar tranquilamente! ;)
Comment: Obrigada pela ajuda :D
Answer: Consegui resolver meu problema desse jeito. Primeiro eu coloco a imagem pra poder setar a cor dela. Espero que não dê mais problema :D

Problemas ao manipular Vector Asset


How to capture HTTP request / response headers with mitmproxy?

Question: I have been able to capture the HTTP(s) traffic from a smartphone and also stored this traffic using mitmdump using the command
mitmdump -w outfile

This seems to dump the HTTP body along with the headers as well. I am interested in capturing only the headers, prefarably as a single csv row (or json string). How can I do that?
Comment: did you try a filter already ? https://mitmproxy.org/doc/features/filters.html
Answer: Yet another derived snippet based on previous responses and updated to python3:
def response(flow):
    print("")
    print("="*50)
    #print("FOR: " + flow.request.url)
    print(flow.request.method + " " + flow.request.path + " " + flow.request.http_version)

    print("-"*50 + "request headers:")
    for k, v in flow.request.headers.items():
        print("%-20s: %s" % (k.upper(), v))

    print("-"*50 + "response headers:")
    for k, v in flow.response.headers.items():
        print("%-20s: %s" % (k.upper(), v))
        print("-"*50 + "request headers:")

Command line:
mitmdump -q -v -s parse_headers.py -R http://localhost:9200 -p 30001
Output:
==================================================
GET / HTTP/1.1
--------------------------------------------------request headers:
CONTENT-TYPE        : application/json
ACCEPT              : application/json
USER-AGENT          : Jakarta Commons-HttpClient/3.1
HOST                : localhost
--------------------------------------------------response headers:
CONTENT-TYPE        : application/json; charset=UTF-8
CONTENT-LENGTH      : 327

Comment: Very nice. I've written up some instructions on how to deploy this and tidied up a few small things in your script: https://gist.github.com/tomsaleeba/c463550b43eb9c58d8b415523c49f70b
Answer: You can extract any header fields you need, e.g., with mitmdump and the flow object (python inline scripts). Inline scripts are documented here: https://mitmproxy.org/doc/scripting/inlinescripts.html
To extract all headers, I used the following command:
$ mitmdump -n -q -s parse_headers.py -r <file>.mitm

The parse_headers.py inline script is as follows:
def response(context, flow):
    request_headers = [{"name": k, "value": v} for k, v in flow.request.headers]
    response_headers = [{"name": k, "value": v} for k, v in flow.response.headers]
    print request_headers
    print response_headers

Comment: I got no output other than `Script error: too many values to unpack Script error: too many values to unpack`... :(
Answer: U was using @rvaneijk, but I was getting the following error:
Script error: too many values to unpack
Script error: too many values to unpack

I found a solution at 'too many values to unpack', iterating over a dict. key=>string, value=>list and changed the code as follows:
[root@npmjs npmo-server]# cat parse_headers.py
def response(context, flow):
  request_headers = [{"name": k, "value": v} for k, v in flow.request.headers.iteritems()]
  response_headers = [{"name": k, "value": v} for k, v in flow.response.headers.iteritems()]
  print "################################"
  print "FOR: " + flow.request.url
  print flow.request.method + " " + flow.request.path + " " + flow.request.http_version
  print "HTTP REQUEST HEADERS"
  print request_headers
  print "HTTP RESPONSE HEADERS"
  print response_headers
  print ""

The output of this is as follows:
10.137.66.4:63870: clientdisconnect

################################
FOR: http://pe2enpmas300.corp.company.net:8081/csv-stringify
GET /csv-stringify HTTP/1.1
HTTP REQUEST HEADERS
[{'name': 'accept-encoding', 'value': 'gzip'}, {'name': 'authorization', 'value': 'Bearer d2e0770656a9726dfb559ea2ddccff3078dba9a0'}, {'name': 'version', 'value': '2.11.2'}, {'name': 'accept', 'value': 'application/json'}, {'name': 'referer', 'value': 'install restify'}, {'name': 'npm-session', 'value': 'a9a4d805c6392599'}, {'name': 'user-agent', 'value': 'npm/2.11.2 node/v0.10.25 linux x64'}, {'name': 'if-none-match', 'value': 'W/"43fb-8/w7tzRZ9CvawCJo5Uiisg"'}, {'name': 'host', 'value': 'registry-e2e.npmjs.intuit.net'}, {'name': 'Connection', 'value': 'keep-alive'}, {'name': 'X-Forwarded-For', 'value': '10.181.70.43'}]
HTTP RESPONSE HEADERS
[{'name': 'X-Powered-By', 'value': 'Express'}, {'name': 'ETag', 'value': 'W/"43fb-8/w7tzRZ9CvawCJo5Uiisg"'}, {'name': 'Date', 'value': 'Tue, 18 Oct 2016 08:04:45 GMT'}, {'name': 'Connection', 'value': 'keep-alive'}]

You can use Docker as follows:

Create the file locally
Run the following

Make sure you have read permission on the file.
docker run -ti -p 8080:8080 -v $PWD/parse_headers.py:/tmp/parse_headers.py
    mitmproxy/mitmproxy mitmdump -s /tmp/parse_headers.py
    -R http://npmjs.corp.company.net:8081 8080


Master-Slave replication with additional selective replication

Question: Using MySQL 5.6 Enterprise is it possible to have a normal master/slave replication between a master and slave with full replication then a second slave server to only have certain tables?
Answer: In MySQL, the binary log that is used for replication always contains all statements for given databases. By default binlog-do-db configuration option on master tells that all databases should be replicated.
On slave side, there is option to only apply binlog statements for certain tables.
Specifying
replicate-do-table=database.table

will only do replication on that specific table.
In your case, you should use the default binlog-do-db statement to log all databases to binary log. On the second slave, you should apply the option above for all tables you want to replicate.


Listar mensagens de usuário logado usando Laravel

Question: Boa tarde.
Tenho em meu Controller o método abaixo:
public function lista () {
    $mensagens =  Auth::user()->mensagens()->get();
    $title= "Mensagens";
    return view('auth.mensagens.lista',compact('mensagens','title'));
}

Ele retorna uma lista de mensagens do usuário logado.
Acontece que em minha modelagem de dados, cada mensagem possui um status boolean 0 ou 1.
Como eu faço para que só retorne as mensagens com o status 1 ?
Deve ser algo bobo, mas hoje não consegui ver uma solução pra isso.
Grato
Comment: Por estar usando Laravel, acredito que você deva saber qual é o retorno de `Auth::user()->mensagens()`, correto? Se não sabe, comece pesquisando isso.
Comment: Obrigado pela ajuda.
Answer: Você pode adicionar um where na sua consulta.
public function lista () {
    $mensagens =  Auth::user()->mensagens()->where('status', 1)->get();
    $title= "Mensagens";

    return view('auth.mensagens.lista', compact('mensagens', 'title'));
}

Comment: Caramba... era isso que eu estava errando: where('status', 1)->get();


Android build.gradle bracing style bug

Question: This is my top-level "build.gradle" file for my Android Studio (2.1.2) project, which I'm developing on a Mac.
buildscript
{
    repositories
    {
        jcenter()
    }

    dependencies
    {
        classpath 'com.android.tools.build:gradle:2.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects
{
    repositories
    {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Everything works fine until I change that bottom "task clean" block to use the same bracing style, like so.
task clean(type: Delete)
{
    delete rootProject.buildDir
}

If I make this change and click on "sync now" in the upper-right corner, I get a syntax error on the left curly-brace line below the word "task".

Error:(28, 0) Cause: startup failed:
  build file 'build.gradle': 28: Ambiguous expression could be a parameterless closure expression, an isolated open code block, or it may continue a previous statement;
     solution: Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...}, and also either remove the previous newline, or add an explicit semicolon ';' @ line 28, column 1.
     {
     ^

Is this a bug in Android Studio, Gradle, or...?
Answer: As noted in this stack overflow post, the problem is semicolon inference.
Simple gradle build file build error
So the solution in my case is to use this syntax.
task clean(type: Delete) \
{
    delete rootProject.buildDir
}

Android build.gradle bracing style bug


What is the name of the guitar accompaniment in this song?

Question: I'm a beginner in guitar playing. I come across this type of accompaniment (specifically the rhythm on the right hand) frequently in songs and really like it but don't know what it's called to search for tutorials. Can I get help to point me in the right direction? Thanks.
Comment: Try "fingerstyle slapping".
Comment: do you mean the chords and how he works with the right hand or with the left?
Comment: What makes you think you need a tutorial? Have you _tried_ doing something similar? Slow down the video to 0.5x speed?
Comment: That's a valid point. I have tried to do that of course. It's faster to reach for the guitar than typing a question. But there are different variations far as I can see, so I think knowing what it is can help me get a bigger picture.
Answer: There are a few things he's doing with the rhythm. I'm not sure if there's a name for the whole effect, though.
The slaps happen on beats 2 and 4, constituting a backbeat.
There's a chord on beat 1 and a staccato chord on the last 16th note of beat one. This is sometimes called an anticipation.
The bass thumps are on the last 2 16ths of beat 2, stopping just before beat 3 which would normally be the second strongest beat after beat 1. This could be considered a syncopation, having a rest where you would expect a note. You can kind of feel a beat here even though you don't hear anything.
Answer: Did you look up fingerstyle slapping as piiperi suggests:
I'found this video that teaches, how to master finger style slapping (10 exercises):
Answer: If you mean the rhythmic accompaniment of the right hand:
On certain beats, instead of a full strum of the strings, we mute all the strings with our strumming hand, and simply run the pick across the dead strings, creating a "blip" kind of sound. This sound creates a very pleasing rhythmic contrast to the rest of the strums, which carry a full tone. The key to its effectiveness is that it is creating an accent on the beat it falls on.
It is called the slap strum.
https://www.guitarprinciples.com/guitar-principles-slap-strum/
But there may be different names like this link  shows:
https://goodguitarist.com/the-strum-slap-add-some-percussion-to-your-strumming/
Searching for "slap strum" you will find plenty of tutorials.
Comment: Sorry I wasn't clear in the question. I edited the question to specify the rhythm he uses, kind of making use of the percussive slap and bass note ornaments.


How do I change a node ID?

Question: I have a node whose ID is 548754. I need it to be 301.
Is there a safe way to do this? There are a lot of tables related to 548754.
What if I export the database, open the SQL file, replace the number, and then import the database. Will this work?
Comment: The easiest would be something like: `drush sql-dump --ordered-dump | sed s/548754/301/g > new.sql; cat new.sql | drush sqlc` (assuming 301 doesn't exist and nothing else conflicts with 548754). This won't be bullet-proof for serialized data which would break in that case (if serialized data is cache, can be removed).
Comment: it should work if you change `nid` and `entity_id` in all tables, but you can not know if some modules didn't named it just `id`. There yould be a problem if you replace it in editor like a string.
Comment: I understand...
Comment: Not possible, unless want to re-import/re-write your whole database. If you consider that, I could answer how potentially this can be done in few commands.
Comment: Why do you need to change the nid? It's better don't do that imho, if you explain the problem because you want to change maybe we can find a workaround.
Read [this](http://www.drupal.org/node/256676)
Comment: @kenorb Not really true, all you actually need is a list of the table and field names that make reference to the node ID. Don't need to re-import or rewrite for that, just needs some domain knowledge and perserverence
Comment: It all depends on the complexity. So it could, but on clean-like Drupal installation, on matured project with hundred of modules, extra links in the content, the nids are spread everywhere - it's few hour work (very specific work depending which modules are used). Not to mention some content links, serialized data (in case some components stores it in this way) which could have some references to it.
Comment: @chefnelone Run: `drush sql-dump --ordered-dump | grep -w 548754 | grep -o '\`.*\`' | sort | uniq -c | sort -nr` and paste the results please (which should list all the tables which references to `548754`.
Comment: @chefnelone Btw. Are you really have over 0.5mln nodes in the database, or it's just an example? Are you asking for the production or some testing db which you assume it won't work for the first time and you've the proper CI/tests in place?
Comment: @kenorb it is a production site. It doesn't have that amount of nodes, but I got huge nid values because I'm using feeds to import external content. I will try your method, I need some time...
Comment: @chefnelone Test it on local of course and check which tables are affected (by above cmd) and if matches any serialized data, then you've to exclude that + ignore [some common tables](http://drupal.stackexchange.com/a/176926/1908). Once you know the list of tables which have this nid, then you could also consider to write some SQL queries to ALTER these values manually.
Answer: A solution is using these two contrib modules:

https://www.drupal.org/project/custom_nid
https://www.drupal.org/project/quick_node_clone

They turn out to work together nicely. "Custom nid" only works for new nodes.. however "Quick node clone" takes you to an unsubmitted "new node" form... as such you can change the nid of the clone before saving it.
After cloning you can throw away the original.

How do I change a node ID?


jQuery API architecture choices: why return single value instead of arrays for attr(), val(), ...?

Question: I am curious about the reasoning behind some of jQuery API architecture choices.
FROM THE DOCUMENTATION
attr():

Get the value of an attribute for the first element in the set of matched elements.

val():

Get the current value of the first element in the set of matched elements.

Even if I have many objects:
$('div').val()

would only return the value of the first element.
But SETTING works differently:
val(value):

Set the value of each element in the set of matched elements.

attr(attributeName, value):

Set one or more attributes for the set of matched elements.

So my questions:

Why decide that getter operations like val() should return only the first value instead of an array of values?
(The user has to use a map operation if he wanted all of them in an array)

Why not do the same with setter operations like .val(value)?

I can see a use case (with $('div').first()) where we expect the call to val() to return the value (we know there is only one dom element in the matched set) instead of an array of length 1. But why not handle it with a concept of a "single dom element query object" (that only gets created after calls to methods like first() or eq())?
Comment: Modify or create custom methods that fulfill requirements utilizing `$.fn.extend`, or modifying the source itself ?
Comment: I don't have such requirements, just curious why such a decision was made when it seems counter-intuitive to me to have different behavior for getters and setters.
Answer: Caveat: I do not take part in the jquery development, so these thoughts may be entirely off the actual design decisions.
Anyway, imho your proposal does not seem to offer any advantage:

to process an array of data gleaned from the elements of a jquery collection the user would have to iterate over this array anyway - this can be done using jquery's each method in the first place which has the additional benefit of immediate access to the element carrying the attribute:
$("my_spiffy_selector").each( function ( idx, e ) {
    $(e).attr("blarf").whatever();
});
Otoh it would complicate matters (at least the jquery code base), if the getters return type would be polymorphic or if there were different getters.
The arguably most common use case would entail at least an additional .first() call.
Comment: (1) is only true if you do need a each loop yourself. Often, you don't or rely on existing operators, e.g you could doMath.min($(".blabla".attr("price")). Also this point could also apply to setters but somehow the API decision was different there.
(2) is a very valid concern. (3) Why do you say the most common use case? If I KNOW for certain (I called first() or eq()) there is only one element, I expect 1 result and not an array. If I have many objects, why should I want to only get the first val()? I would say my most common use case is to actually call map() as this is what I want.
Comment: ad (1) the situation for setters is different: here you distribute _identical values_ to a number of elements. the looping argument seems valid, though in many cases you'd still have to do some conversions as the attr values are returned as strings (eg. your min price detection will fail on `['100','99']`). ad (3) point taken. i can't be sure of course. however, bulk processing of data stored in the dom using javascript sounds like a suboptimal choice to me, i'd expect xslt or comparable technology to be better suited in most cases (i'm aware of the fact that you can't always choose freely).
Comment: re (1) and (3), my example was poorly chosen. Think about collecting values for jQuery methods like width(), height(), offset(), position(), scrollLeft(), ... I am unclear why it only returns the value for the first element and not an array of all width, height, offset, ... for all elements.
Comment: while i see valid scenarios for your latter examples, i still doubt that these data will be bulk-processed frequently (eg. i'd rather expect positional data to be processed for a single container widget instead, the respective attributes on descendants being defined relative to this container). this is just guesswork, of course, i have no hard statistics on that.


spin.js não é exibido quando a página é carregada

Question: Estou usando Spin.js para exibir um load até que página toda seja carregada, feito isso, a execução do spin deve ser encerrada. Mas o load nem está aparecendo na tela. Criei um jsfiddle como exemplo:

       Content

Script.js
var mySpinner = null;

function setupLoading() {
    $('
').appendTo(document.body);

    var target = document.getElementById("divSpin");

    var opts = {
        lines: 13, // The number of lines to draw
        length: 20, // The length of each line
        width: 10, // The line thickness
        radius: 30, // The radius of the inner circle
        corners: 1, // Corner roundness (0..1)
        rotate: 8, // The rotation offset
        direction: 1, // 1: clockwise, -1: counterclockwise
        color: '#000', // #rgb or #rrggbb or array of colors
        speed: 1, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'mySpin', // The CSS class to assign to the spinner
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        top: '50%', // Top position relative to parent
        left: '50%' // Left position relative to parent
    };

    mySpinner = new Spinner(opts).spin(target);
}

function removeLoading() {
    mySpinner.stop();
}

    function showLoading() {
        mySpinner.spin();
    }

Comment: Falta vc carregar as bibliotecas .js e .css.
Answer: Vamos lá:
Bug #1: Chamar o script
o código javascript que cria o spinner não existe na página. é necessário referenciá-lo no HTML, senão as funções showLoading e removeLoading não existirão.
para isso é preciso chamar seu script (deduzo que esteja salvo no mesmo diretório do index.html, com um nome tipo "meuSpin.js"):

No caso do JSFIDDLE, o javascript é inserido automaticamente no resultado.

Mas, neste caso, seu script serve para mostrar um loading ENQUANTO a pagina está carregando, portanto a primeira coisa que deve aparecer na página é seu script de loading. Chamar uma referência a um script externo implica em uma requisição extra, e alguns navegadores podem decidir chamá-lo após o conteúdo ser exibido, portanto seu script poderia não servir para nada.
Neste caso, o mais sábio seria deixar o código junto com a chamada do showLoading.

Bug #2: Scripts que manipulam o DOM fora do HTML
No seu script, na função setupLoading (que, veja bug #3, não é chamada), você manipula o DOM, criando um elemento para conter o spinner:
$('
').appendTo(document.body);

document.body ainda nem existe.
a solução neste caso é deixar o script logo após abrir a tag :

      ...
      ...
      </script>
        // esconde o loading
      </script>

O JsFiddle automaticamente insere o conteudo da aba HTML dentro do body do resultado, portanto a tag  é ignorada.
Como contrapartida, eles disponibilizam opcões dentro da area de Javascript sobre como seu código será inserido.
Clique em "Javascript ▼", e em LOAD TYPE, selecione No Wrap - Bottom of HEAD
Isso significa que irão colocar seu script no final de . Portanto ainda precisaremos do jQuery on("ready"

Bug 3: Uso da livraria Spin.js
A função showLoading chama o spin do mySpinner. Portanto ela espera que mySpinner seja uma instancia de new Spinner(opts).
Para isto precisamos chamar a porção de código mySpinner = new Spinner(opts) antes de chamar mySpinner.spin(target).
isso tudo acontece apenas dentro de setupLoading().

Bug #4: Dependências
Spin.js não tem nenhuma dependencia, portanto deve funcionar naturalmente. Seu código por outro lado depende de jQuery.
Para isto você precisa inserir o jQuery antes de chamar $()
Deduzo que no seu código já exista uma tag chamando o Spin.js:

No caso do JSFIDDLE, é necessário configurar seu fiddle com as dependencias:
Clique em "Javascript ▼", em Frameworks and Extensions, abra o dropdown e selecione jQuery (edge)
Para adicionar o Spin.js, clique em Resources logo abaixo do logo azul do JsFiddle, escreva "spin.js" na caixa de texto, e selecione spin.js da lista de autocomplete. Em seguida clique no + no círculo para adicioná-lo ao seu fiddle.

Bug #5: Uso do jQuery
Se a intenção do loading é mostrar enquanto o conteúdo não carrega, saiba que ele não vai aparecer até, ao menos, o Spin.js e o jQuery.js tenham sido carregados.
Se ainda quiser usar o jQuery, apenas precisa ajustar o jeito que chama as funções.
    $(document).ready(function () {
      ...
    })

$() chama o seletor do jQuery, envolvendo o elemento como um objeto jquery.
document é uma variavel global do js, representa o documento da página.
.ready(fn) é um método do jquery que chama uma função fn quando o objeto jquery do qual foi chamado (no caso $(document)) estiver pronto, carregado.

Portanto apenas será chamada quando todo o documento, a tag , estiver completamente carregada e pronta para ser manipulada.

Devido a isto, é necessário inserir uma tag  dentro da area HTML do JsFiddle para conseguir chamar as funções.

Em outro lugar, existe a chamada $(document).on(removeLoading).
jQuery().on(event, callback) chama o callback quando event acontecer. (ou seja, jQuery.ready(fn) é um atalho para jQuery.on("ready",fn))
Se você desejava chamar a função showLoading ou hideLoading quando a página estiver pronta, o código deve ser:
    $(document).ready(function() {
      showLoading()
    })

Final:
Considerando todos os fixes, seu código final deve ficar assim:

        <title>Minha Pagina com Spinner</title>

        <link rel="stylesheet" href="spin.min.css" />

        ...

Observe que neste código não utilizo jQuery.ready()

Bom,
Parece lindo
Mas não vai funcionar.
Mesmo que insira milhares de dados entre os dois scripts, e faça um site com tanta coisa que demore pra carregar o suficiente pra conseguir ver o loading, ainda vai ficar frustrado, porque o loading não vai aparecer.
O navegador precisa do inicio e do fim do html para conseguir exibi-lo. Ou seja, só vai aparecer alguma coisa na sua tela depois que o último  ser enviado. Os scripts também só serão executados depois disso.
Se você precisa mostrar um loading, enquanto o conteúdo é carregado, precisa obter este conteúdo por uma requisição Ajax.
Isso implica em ter no mínimo um servidor HTTP local rodando, para conseguir fazer a requisição na sua própria máquina.
Minha sugestão é buscar como fazer isso com React ou outra ferramenta, que cria um servidor local, facilita a criação de templates e chamadas de código, e não precisa de jQuery mais.
Mas, se não é urgente, é melhor tentar entender o fluxo do DOM, como e quando as funções são chamadas, como o HTML é renderizado, procurar como funcionam os servidores e passar pelo aprendizado de instalar um Nginx ou Apache na sua máquina, entender chamadas AJAX, a API Fetch, e ver como é possível inserir HTML assíncronamente na sua página, para só assim conseguir ver o loading.


Como enviar e receber dados para BD MySQL usando PHP em Objective-C?

Question: Cenário:
 Enviar e receber formulários para um banco de dados MySQL usando PHP.
Gostaria de saber se alguém sabe ou tem algum link para um tutorial didático e claro sobre esses procedimentos, de envio e recebimento usando JSON.
Pode ser em inglês ou português, e preferência para a transferência Assíncrona.
Comment: Onde entra o "Objective-c" da pergunta?
Comment: O Objective-C entra no meu trabalho de elaborar uma atividade com web service e PHP no meu projeto! Não entendi o pq da tua negativação, se não entendeu não precisa negativar, basta fazer um comentário.
Comment: Tiago, a gente não tem como saber quem negativos, pode não ter sido ele.
Comment: Ah nao, tranquilo, não estou acusando ele, na verdade são duas respostas em um comentário, como o sistema remove as linhas vazias, não separou as frases. :D
Comment: Tenta isso: https://www.youtube.com/watch?v=9x47niEJk_M
Comment: Kkkkk muito bom!!! A cara do Jason no splash do video!!!@touchmx
Comment: Encontrei outro video muito bom e ja construi o codigo ( PHP e Objective-c), vou postar pra galera aqui!!! Mas obrigado assim mesmo!
Answer: A solução que encontrei foi essa! Posso enviar um argumento para um php e ele me retorna o resultado da query:
<code>// FUNCIONA PODE SER USADO PARA ENVIAR OS ARGUEMENTOS E RECEBER O RETORNO DA QUERY DO PHP

    NSMutableString* strURL =[[NSMutableString alloc]initWithFormat:@"http://localhost/testesPHP/buscaFuncionarios.php?numero=%@",nomeCadastro.text];

    NSURL* url = [NSURL URLWithString: strURL];

    NSData* data = [NSData dataWithContentsOfURL:url];

    NSError*erro;

    NSMutableArray* oabsRecebidas;

// Recebe o retorno vindo do arquivo PHP buscaFuncionarios.php (no caso usando Json)
    oabsRecebidas = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&erro];

// Escreve na tela o retorno
    NSLog(@"%@", oabsRecebidas);
</code>


Annuity/Perpetuity problem

Question: (Repost but with a proposed solution) Mary-Jane, a $20$-year-old woman, purchases a perpetuity-due as a pension benefit that begins when she is $60$ years old. The benefit pays an annual total of $48000$ with level payments at the start of every month. To purchase this benefit, she has to make $40$ annual premium payments, the first of which will be at the time of the policy purchase i.e. her $20$th birthday. Every payment after the first will increase by $6$%. Assuming a flat term structure and annual effective interest rate of $8$% for all valuations, what should be the amount of the initial payment?
My attempt:
Notice that the first $40$ payments (time $0$ to time $39$) form an annuity due whereas the payments from payment $41$ (time 40 onwards) form a perpetuity due. Suppose Mary-Jane pays $P$ as her first payment.
$t = 0 \rightarrow P$ (just turned 20)
$t = 1 \rightarrow P(1.06)$
$t = 2 \rightarrow P(1.06)^2$
.
.
$t = 39 \rightarrow P(1.06)^39$ (just turned 59)
$t = 40 \leftarrow 48000$ (just turned 60)
$t = 41 \leftarrow 48000$
.
.
The present value of the pension plan is $48000 \hat{a}_{\infty, 0.08}$, where $\hat{a} = \frac{1}{d}$ and $d$ is the discount rate. Hence $PV = 48000 \cdot \frac{1}{d} = \frac{48000}{0.0741} = 648000$.
This should be equal to the future value of the premiums at $t = 40$. This is given by:
$FV = P \cdot (1+i)(\frac{(1+i)^n - (1+g)^n}{i - g})$, where $i$ is interest and $g$ is the growth rate. Hence $FV = P \cdot (1.08)(\frac{(1.08)^{40} - (1.06)^{40}}{0.02}) = 617.6954P$
This gives $P = \frac{648000}{617.6954} = 1049.0608$.
Is this correct? I did quite a bit of research but I am still unsure as to whether this is the right way to do such a problem. Any assistance is much appreciated.
Answer: $\require{enclose}$
When the perpetuity begins to pay out when the annuitant turns $60$ years of age, the schedule of payments is monthly, not annually.  I quote:

The benefit pays an annual total of 48000 with level payments at the start of every month.

The $48000$ is therefore divided into $12$ equal payments of $4000$.
Consequently, the equation of value at the time that she turns $60$ is:
$$P(1+i)^{40} + (1.06)P(1+i)^{39} + \cdots + (1.06)^{39}P(1+i) = 4000 + 4000v^{1/12} + 4000v^{2/12} + \cdots,$$
where $v = 1/(1+i)$ is the annual present value discount factor.  The first thing to note is that I set the valuation time at age $60$, rather than at age $20$, because this makes the calculation a little cleaner.  On the left-hand side is the accumulated value of a geometrically increasing annuity-due with annual payments.  On the right-hand side is the present value of a perpetuity-due with monthly payments.
The geometric annuity-due is expressible as a level payment annuity-due with modified interest rate; e.g. factoring out $(1.06)^{40} P$, we get $$P(1+i)^{40} + (1.06)P(1+i)^{39} + \cdots + (1.06)^{39}P(1+i) = (1.06)^{40} P \left( \left(\frac{1+i}{1.06}\right)^{40} + \left(\frac{1+i}{1.06}\right)^{39} + \cdots + \frac{1+i}{1.06}\right).$$  So if $i = 0.08$, the factor in parentheses is a level-annuity-due with effective annual interest rate $$j = \frac{1.08}{1.06} - 1 \approx 0.01887,$$ and the level payment is adjusted to be $(1.06)^{40}P$.  Thus this side of the equation of value is $$(1.06)^{40} P \ddot s_{\enclose{actuarial}{40}j} = (1.06)^{40} P (1+j) \frac{(1+j)^{40} - 1}{j}.$$
Meanwhile, the right-hand side is a perpetuity-due with effective monthly rate $$k = (1+i)^{1/12} - 1 \approx 0.00643403,$$ which you can verify yields an effective annual rate of $i$, since $(1+k)^{12} = 1+i$.  So the equivalent monthly present value discount factor is $$v^{1/12} = \frac{1}{1+k} \approx 0.993607.$$ Then the right-hand side has present value
$$4000 \ddot a_{\enclose{actuarial}{\infty} k} = 4000 \left(1 + \frac{1}{k}\right).$$
Hence the required level payment is $$P = \frac{4000 \left(1 + \frac{1}{k}\right)j}{(1.06)^{40} (1+j)((1+j)^{40} - 1)} \approx \frac{4000 (156.424)(0.01887)}{(10.2857)(1.01887)(1.11211)} \approx 1012.9496.$$
Comment: Thank you for noticing that! So would it suffice to simply replace my PV of annuity due with $4000 \cdot a_{\infty, 0.03031}$ as it comes to the same answer?
Comment: @SupremePickle I'm not sure how you got $0.03031$?  In any case, the effective monthly interest rate is $k = 0.00643403$, instead of $0.08$, so the present value of the perpetuity should be $(4000)(156.424) \approx 625694$.
Comment: Edit: My bad, $0.03031$ was a typo. I meant to write $0.006434$. Thank you!
Comment: @heropup You seem to be extremely helpful with OPs post. Could you kindly take a look at: https://math.stackexchange.com/q/4122665/902292

Annuity/Perpetuity problem


Trill in Chopin Nocturne

Question: Chopin's nocturnes have always been some of my favorite pieces of music to play. However, I was working through No. 17 when I came across this particular complex couple of bars.

Particularly, the trill that is played over most of the notes in the picture. I'm really not sure how I'm supposed to play this. Do I continue to play the trill with my 4th and 5th fingers and leave only the remaining 3 fingers to play the rest of the notes in the right hand?
I've attempted this for a quite a while now, but even after having played piano for 14 years Im having trouble. I suspect that my 4th and 5th fingers are just too weak for this kind of fast action. I have no problem playing trills with my 1st, 2nd and 3rd fingers.
This is driving me nuts not being able to play this.
Answer: Other editions make it clearer: trill each note, starting on the note rather than the auxiliary (where he specifies it with an accacciatura). You can see it in Scharwenka's edition here.
Edit: I should clarify this a bit: Chopin is using accacciature in this passage to specify the starting notes of the trills.

Trill in Chopin Nocturne


Cloud Functions for Firebase for existing data

Question: How can I use Cloud Functions for Firebase database triggers to edit/update existing data?
My Use Case:
I have existing data in my Firebase database, say a/{uid}/b, at the time of writing, I have 14-15 uids in the db where b is already defined. Now I want to use cloud function to listen to write to b and add some more data based on that.
The database trigger functions.database.ref('/a/{uid}/b').onWrite will only execute for new writes/updates to the specific path, not for existing writes/updates.
How can Cloud Functions for Firebase help when I want to update all the data at once for existing write logics?
Comment: I'd create a separate function (HTTP or Database triggered, doesn't really matter) purely for the migration. Then again: you could also simply do that with a local node script.
Answer: I had a similar situation. I found a workaround to get the function executed. This is not ideal for production database but worked for me for a small database.
Export existing data from a collection ( or entire database ) into a file on which you have trigger functions.
Then delete the data that is exported from the database. ( Please be aware if you have onWrite function, it gets executed on delete as well. Make sure code handles it properly )
Command to export a collection
firestore-export --accountCredentials=/path/credentials.json --nodePath collectionName

Then import the backup data in the same collection using the command below.
firestore-import --accountCredentials=/path/credentials.json --backupFile /path/backupFilename.json --nodePath collectionName

More information about firebase-export npm package @
https://www.npmjs.com/package/node-firestore-import-export


PowerEdge 2800, PERC 6e, MD1000, 4 Member Raid 5 2TB Disks Windows 2008 R2

Question: When write are performed to the Virtual Disk Windows 2008 R2 crashes and reboots leaving no error enrties can be found in any LOG File.
Has anybody encountered this problem and if so is there any recommendations,
Answer: I recommend:

Making sure that your server has the very latest PERC 6e drivers for your exact operating system and hardware architecture.
Ensure that your Windows server has all the latest hotfixes, updates and patches. If there are some that are not installed, make sure that you have a documented reason why they weren't. Check hidden updates to make sure.
Update to the latest PowerEdge BIOS. That can have some effect on hardware problems. Educate yourself on what the update does and if it has known issues with any applications and services that you are running on the server.
Turn off auto rebooting upon a system failure. Make sure that you are seeing the "Blue Screen of Death" and write down the error code.
Perform an analysis on the dump file created by the BSoD.


How to get pdf code using iText

Question: anyone have any idea how to use itext to get a output of a pdf codes, just like when you drag a pdf into Notepad++? Thanks!
Answer: Just open the PDF like any other textfile, e.g. with FileReader/BufferedReader. No need for iText here.

How to get pdf code using iText


Running Python on a module with relative imports from another directory

Question: Say that under /path/to/foo I have package with a python module:
/path/to/foo:
           | my_package
                        | __init__.py
                        | my_module.py

           | my_other_package
                        | __init__.py
                        | my_other_module.py

The file my_module.py does a relative import of my_other_module.py as follows:
  from ..my_other_package import my_other_module

I understand that I can do the following from the shell:
> cd /path/to/foo
> python -m my_package.my_module

But what if I don't want to change my current directory? Is there any way to run my module from the shell without having to change PYTHONPATH?
I tried the following:
python -m /path/to/foo/my_package.my_module

but that didn't work. I got: Import by filename is not supported.
Comment: Have you tried using a symlink from my_package to my_other_package/my_other_module.py?
Comment: Have you tried adding a `__init__.py` to `/path/to/foo` as well? I don't think you can do this if `foo` is not a package in itself.
Answer: Get the relative path:
base_path = os.path.abspath('../my_other_package/')  #or any relative directory
append this to the system path (only temporary, will be deleted after execution):
sys.path.append(base_path)
import the file you need in that path:
import my_other_module.py
I believe it you may need a file named __init__.py (with nothing in it) if you wanted to import the file as import directory.file (correct me if I'm wrong).
This thread shows alternate approaches.
Comment: Thanks. I have read that tampering with `sys.path` is not a good idea, but I guess this the best I could do..