Conflict in confidence intervals for mean difference and confidence interval for Cohen'd effect size

Question: I run an experiment to compare the performance of two algorithms. The design of my experiment is paired comparisons. I'm reporting my results in this way:

There were no outliers in mean differences data as assessed by inspection of boxplot. The assumption of normality was not violated as assessed by skewness of 0.2276 (SE = 0.4405) and kurtosis of -0.2766 (SE = 0.8583). The performance was higher in algorithm A (M = 0.3876, SD = 0.3138) than in algorithm B (M = 0.2241, SD = 0.3476), a statically significant mean increase of 0.1635, 95% CI [0.0393, 0.2877], t(27) = 2.7007, p = 0.0118, d = 0.4938, 95% CI for d [-0.0501, 1.0378].

Note that the 95% confidence interval for mean difference does not include zero but the 95% confidence interval for Cohen'd includes zero. I was about to conclude that algorithm A has better performance than algorithm B with statistical significance and medium effect size, but I got confused about how to interpret the confidence interval for Cohen's d.
What can I say about the effect size with this data?
Below is my data and how I compute the values using R.
Thanks for your attention.
a = c(0.40000000, 0.44011976, 0.72727273, 0.50000000, 0.00000000, 0.07692308, 0.00000000, 0.00000000, 0.00000000, 1.00000000, 0.50000000, 0.91666667, 0.19354839, 0.74883721, 0.50000000, 0.50000000, 0.55000000, 0.17142857, 0.50000000, 0.51351351, 0.68000000, 0.85714286, 0.03703704, 0.05454545, 0.54219949, 0.44444444, 0.00000000, 0.00000000)
b = c(0.00000000, 0.54491018, 0.72727273, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 1.00000000, 0.00000000, 0.00000000, 0.00000000, 0.33953488, 0.00000000, 0.00000000, 0.00000000, 0.48571429, 0.00000000, 0.83783784, 0.80000000, 0.57142857, 0.00000000, 0.00000000, 0.06393862, 0.90476190, 0.00000000, 0.00000000)
mean(a)
sd(a)
mean(b)
sd(b)
t.test(a, b, paired=TRUE)

library(compute.es)
mes(mean(a), mean(b), sd(a), sd(b), length(a), length(b), dig=4)

Answer: There are analogous effect size measures to Cohen's for paired data, sometimes called the "standardized mean change" or "standardized mean gain". This is computed with $$d = \frac{\bar{x}_1 - \bar{x}_2}{SD_D} = \frac{\bar{x}_D}{SD_D},$$ where $\bar{x}_1$ is the mean at time 1 (or under condition 1), $\bar{x}_2$ is the mean at time 2 (or under condition 2), $\bar{x}_D$ is the mean of the change/differences scores, and $SD_D$ is the standard deviation of the change/differences scores.
This is the standardized mean change using "change score standardization". There is also the standardized mean change using "raw score standarization", but the former more directly relates to your use of the dependent samples t-test.
You can use the metafor package to compute this (and the corresponding CI):
summary(escalc(measure="SMCC", m1i=mean(a), sd1i=sd(a), m2i=mean(b), sd2i=sd(b), ni=length(a), ri=cor(a,b)))

yields:
      yi     vi    sei     zi  ci.lb  ci.ub
1 0.4961 0.0401 0.2003 2.4769 0.1035 0.8886

So, now the CI doesn't include 0 anymore, which is consistent with the results from the t-test. (Note: the value under yi is the d-value above, but after using a slight bias correction).
Some references if you want to read more about this:
Morris, S. B., & DeShon, R. P. (2002). Combining effect size estimates in meta-analysis with repeated measures and independent-groups designs. Psychological Methods, 7, 105–125.
Viechtbauer, W. (2007). Approximate confidence intervals for standardized effect sizes in the two-independent and two-dependent samples design. Journal of Educational and Behavioral Statistics, 32, 39-60.
Update: Getting the exact CI for d.
In rare cases, it can happen that the results of the t-test (and the CI for the mean difference) yields a different conclusion than the CI for d obtained above (i.e., the CI for the mean difference includes the value 0, while the CI for d does not, or vice-versa). This is due to the fact that the CI for d is based on an asymptotic approximation using the normal distribution.
One can compute an exact CI for the standardized mean change, but this requires iterative methods (see Viechtbauer, 2007, and the references given therein). The advantage of the exact CI is that it will always agree 100% with the results from the t-test and the CI for the mean difference in its conclusion.
Instead of letting the computer do the iterative work for us (which can be done in a few lines of code), one can also just do this manually by trial and error. For the data given in http://pastebin.com/12J7UghC, the bounds of the exact CI for d can be obtained with:
tval <- t.test(a, b, paired=TRUE)$statistic
pt(tval, df=length(a)-1, ncp=-0.00265265 * sqrt(length(a)), lower.tail=TRUE)
pt(tval, df=length(a)-1, ncp=-0.77193310 * sqrt(length(a)), lower.tail=FALSE)

Essentially, we just need to find those two values of the non-centrality parameter of the t-distribution, so that the observed t-value cuts off .025 in the lower and upper tails of the distribution. With a bit of trial and error (and starting with the CI bounds obtained earlier), we find the exact 95% CI for d is $(-0.003, -0.772)$. And now things are consistent again: The t-test rejects (just barely, with $p=.048$), the CI for the mean difference excludes 0 (just barely), and the CI for d exclude 0 (just barely).
Comment: You are welcome. Aside from accepting an answer (if you find that it answers your question), you should also consider upvoting answers that are useful. For example, Peter's response was useful in pointing out the source of the inconsistency.
Comment: I'm sorry. I didn't know that because this was my first question here. Upvoted both answers.

I still have data that shows inconsistency between the two confidence intervals, even using the correct method: 95% CI for mean difference [-0.222368907, -0.000822525] and 95% CI for Cohen's d [-0.7632, 0.0038]. I guess this is because -0.000822525 is too close to zero and I should not reject the null hypothesis based on CI for Cohen's d. Data is available here: http://pastebin.com/12J7UghC Thanks again!
Comment: No problem. Just wanted to bring this to your attention. And I'll update my answer to deal with the issue you are encountering now.
Comment: Thank you for the patience, Professor Viechtbauer. Your answer was clear and to the point. I'll look the cited references. Note: I could reproduce your results using `pt(tval$statistic, ...)` instead of  `pt(tval, ...)`.
Comment: Ah, right, forgot the `$statistic` part in the code. Updated my answer.
Comment: I think the first pt should say lower.tail=F and the second should say lower.tail=T
Answer: mes does not account for the paired-ness of the data, so, it is a different test; usually, paired tests are more powerful, so it is not surprising that the paired test was significant and the unpaired was not.
Comment: Here is the reference: Dunlap, W. P.; Cortina, J. M.; Vaslow, J. B. & Burke, M. J. Meta-Analysis of Experiments With Matched Groups or Repeated Measures Designs Psychological Methods, 1996, 1, 170-177. https://www.dropbox.com/s/1bbz20lehbff1cc/dunlap-1996%20Meta-Analysis%20of%20Experiments%20With%20Matched%20Groups%20or%20Repeated%20Measures%20Designs.pdf
Comment: Hi, Peter, thanks for your reply.

I read somewhere that the correct way to calculate Cohen's d is using the result of t-test for unpaired data. Whenever I find the reference I'll post here.


How to prove $\sum_{n=1}^{\infty} \frac{1}{\sqrt{n+1}+\sqrt{n}} $ diverges using the comparison test.

Question: Question:
I'm having difficulty proving the series $$\sum_{n=1}^{\infty} \frac{1}{\sqrt{n+1}+\sqrt{n}}$$ diverges using the comparison test with with the series $\sum_{n=1}^{\infty} \frac{constant}{\sqrt{n}}$ for comparison.
Where I am at so far:
The comparison test states if 0 ≤ $a_n$ ≤ $b_n$ for all natural numbers and $\sum_{n=1}^{\infty} a_n $ diverges, then $\sum_{n=1}^{\infty} b_n $ diverges.
Let $b_n$ = $\frac{1}{\sqrt{n+1}+\sqrt{n}}$
Observe that $b_n$ = $\frac{1}{\sqrt{n+1}+\sqrt{n}}$ ≤ $\frac{1}{\sqrt{n}}$ for all natural numbers.
But the thing is, I know that if I had "$b_n$ = $\frac{1}{\sqrt{n+1}+\sqrt{n}}$ ≥ $\frac{1}{\sqrt{n}}$ for all natural numbers" I would be fine because if we let $a_n$ = $\frac{1}{\sqrt{n}}$ then I know that $\sum_{n=1}^{\infty} \frac{1}{\sqrt{n}} $ diverges so by the comparison test, $\sum_{n=1}^{\infty} \frac{1}{\sqrt{n+1}+\sqrt{n}} $ diverges.
Where am I going wrong?
I have to use $\sum_{n=1}^{\infty} \frac{constant}{\sqrt{n}}$ as a comparison.
Comment: start with this: $\sqrt{n+1}+\sqrt{n} < 2\sqrt{n+1}$
Comment: $  \frac{1}{\sqrt{n+1}+\sqrt{n}}\ge\frac12 \frac{1}{\sqrt{n+1}}$
Answer: Note that
$$
\sqrt{n+1}+\sqrt{n}\leq 2\sqrt{n+1}
$$
(for $n\geq 1$ say) whence
$$
\frac{1}{\sqrt{n+1}+\sqrt{n}}\geq \frac{1}{2\sqrt{n+1}}
$$
from which one can conclude that $\sum \frac{1}{\sqrt{n+1}+\sqrt{n}}$ diverges using the comparison test.
An alternative which does not use the comparison test is to observe that
$$
b_n=\frac{1}{\sqrt{n+1}+\sqrt{n}}=\frac{1}{\sqrt{n+1}+\sqrt{n}}\times \frac{\sqrt{n+1}-\sqrt{n}}{\sqrt{n+1}-\sqrt{n}}=\sqrt{n+1}-\sqrt{n}
$$
whence
$$
\sum_{n=1}^k b_n=\sqrt{k+1}-1\to \infty
$$
as $k\to \infty$.
Answer: Use that $$\frac{1}{\sqrt{n+1}+\sqrt{n}}\geq \frac{1}{n}$$ this is
$$n^4-4n^3-2n^2+1\geq 0$$ if $n$ is large enough.
Answer: Use the comparison test with
$$\frac1{2\sqrt{n+1}}\lt\frac1{\sqrt{n+1}+\sqrt{n}}$$
The sum over the LHS diverges by the integral test hence the sum in question also diverges.


Simplify chords

Question: I'm currently working on a website and I would like to find a way to simplify chords by removing the non essential parts (to make it easier for beginners).
For example: Am7/C => Am.
Removing the bass note is easy but for the rest it's giving me a hard time cause there are too many chord qualities.
First, I know that I have to keep the minor, diminished and augmented notations (cannot do Cm => C; Cdim => C; C+ => C). And I also have to keep suspended notation (cannot do Csus2 => C). But I can remove 7, 9, 11, 13,... So I could do C7sus2 => Csus2.
But what about: CMb5, Cm#5, Cmbb5, Csus4#5,...
How can I do this the right way (if there is a right way)?
Thanks
Comment: IMO, it might be good to split this to two parts: how would a HUMAN do this in the first place, and then maybe as a separate question, how to model that process into a computer program. :) If you don't understand the process even "manually", how could you make a program that does it automatically? :)
Comment: Two clarifications: 1) are you looking to do this programmatically or by hand? 2) Are you looking always to produce a three-note chord?
Comment: I'm not so sure that considering the 7 in a 7th chord "non-essential" will really benefit whatever your target audience is. What's your target audience?
Comment: My idea was to reduce every chord to their triad. I can't transform Csus2 to C cause it might be a Cm. Same for Aug and dim chords cause the "base" triad is not the same.
Comment: The idea, in theory, is a good one. I considered something similar about 50 years ago. Then reasoned that certain pieces (chord wise) were (or weren't) appropriate for students at whatever stage they were. In other words, if there were certain chords, that a student wasn't able to play, then that's next week's target! Watering down *certain* chords is something that always happens,but I'm not at all sure it's the way forward,and may well be feeding inaccurate information on the way.Plus - context is always important, so calling a chord simpler something will not always be appropriate, or work.
Comment: Making it easier for beginners? CMb5, Cmaug5 etc are certainly not beginner (or any usual) chords. What are you thinking? -1.
Comment: Yo @Tim, the whole point of the program is to turn ("reduce") those complex symbols into beginner-friendlier chords, no? Or are you saying that this program shouldn't even be used on music that uses those chord symbols?
Comment: My bigger concern is that the way the chords are being reduced seems quite arbitrary. Above answers note that the program intends to reduce C7 to C, but Csus2 is apparently "simplest form"... seems strange to me. Is it by any chance being optimized specifically to reduce the number of *notes played* in the output chord?
Answer:
How can I do this the right way

The right way is to take context into account, and the note reduction decisions are usually somewhat artistic choices. Your program has to be able to look at the song and understand what the essential point is. What does the picture represent?
Context means things like:

What key is it in? How does each chord turn the harmonic balance away from the tonic, or back to tonic?
What comes before and after each chord? Is there a voice stepping/leading going somewhere. Like Am - Ammaj7 - Am7 - Am6. If you reduce this to Am - Am - Am - Am, you keep the bass, but lose the descending A - G# - G - F# line. A reduction to Am - E - C - D has an aspect of that line, but not the bass.
Is there a chord-rhythm pattern, or song form of some kind? If the changes or harmonic turns form e.g. an A-A-B-A structure, you might want to keep that intact. Is it a 12-bar blues? Sometimes, there's a chord change such as C - Csus - C - Csus just to have a chord change, any change as long as there is a change. If you remove such changes in the name of simplification, you throw away the rhythmic events that harmonic changes have. If you have to "simplify" the Csus, then maybe even a Dm would do the job, even though normally you wouldn't consider Dm a substitute for Csus.
What does the melody do? If there is a melody. Maybe the melody handles some of the chord tones, so you can leave such a note out somewhere, if it allowes you to use a simpler chord.
Are there "out-of-scale" notes in the chords, perhaps doing a modulation or modal interchange? Is your "Gm7" really just a fancy C7 chord? Or is it better to replace it with Gm?
If there's a dim7 chord, what is it essentially doing, if you had to explain it in terms of tonic-subdominant-dominant? Is it a jazzy substitution for a dominant chord, or maybe a minor chord? (Try to do this for example with Chaplin's "Smile") Dominant-tonic kind of motion of a different key, like a secondary dominant?

Do you want the generated reduction to (a) be easy to play, or (b) sound right and truthful to the original? What elements of the original song do you want to preserve? Which elements are essential to that song?
I would think that plain and simple C might be a better three-note reduction of Am7/C than your suggested Am. If someone wrote a bass inversion, maybe they did it for a purpose. The lowest note might be important to preserve, particularly if there's a bass motion. If there's a progression like: Am7 - Am7/C - D - E, then Am - C - D - E is a much better reduction than Am - Am - D - E. The original had a steady equal-time-per-chord chord rhythm, but Am - Am - D - E has the same chord stay for two steps! So it's missing a chord change. Different chord rhythm and different bass motion.
If there's Am - Bm7-5 - E - Am, then you have two possible reductions for the Bm7-5 chord: Dm and Bdim. "Bm" would be WRONG because it has an F# note. It is absolutely essential to keep the "-5", which is an F. It would be nice to keep the B bass note too, so Bdim would be better. But maybe it's a strange chord for your "beginners"? In that case, Dm is the only correct choice for an easier reduction. In the key of Am.
To sum this up: to make a good chord simplification/reduction, you need to look at the whole harmonic progression, how it turns. You select the most important harmony-turning notes from each chord and select a "simple" chord which preserves these important notes.
It might be possible to program this as a very large bank of special case rules, if you can figure out the key. If you can create an engine where it's easy to add more refined logic rules, then ... why not. But still, you'd have to add some sort of heuristic factors and fuzzy stuff like "what is the song structure", and write an evaluation function which assigns a "beauty factor" for each candidate reduction choice. :) Might be a fun project for a computer science student?
Algorithm sketch
The algorithm could be something like:

"Realize" each chord symbol as notes. From now on you'll be handling chords as note combinations (like note stacks in staff music), not textual symbols.
Generate a number of candidate reductions for each chord, with triads or whatever "simple" chords you want to produce.
Select the "best" combination of candidates for the song, by evaluating a HowGoodIsThisReduction() function. Either for individual chords, or entire reduced songs.
Convert each selected best candidate chord back to a textual chord symbol.

How well this works, depends on the HowGoodIsThisReduction() function. If it only looks at individual chords like HowGoodIsThisReduction(OriginalChord, ReducedChord), then it cannot retain any information about movement and song structure. But if it's like HowGoodIsThisReduction(OriginalSong, ReducedSong), then it might give extra points for keeping song structure, voice leading and harmonic turns intact.
The GenerateCandidateReductionsForChord() function might operate by simply leaving out notes. Or it could take the key of the song into account and suggest E major as a candidate replacement for Am maj7. And then let the evaluator function decide if Am - Am - Am - Am is a better reduction than Am - E - C - D for the chord progression Am - Am maj7 - Am7 - Am6. The choice between these two reduction styles could be user-configurable.
Comment: I'd be very impressed if OP got a program up and running that could do all of that, but great answer for humans reducing chord symbols by hand.
Comment: @user45266 I thought that this was an interesting question specifically for the "how would a human do this" aspect. Even then it's far from trivial, not to even think about how an automatic program might approach it.
Comment: Wholly agreed. A lot more goes into the reduction process for musicians than initially came to mind. It'll be fun to watch technology try to climb that barrier in the years to come, too.
Comment: Thanks a lot. There are indeed a lot of parameters to take into account. My idea is not to do something perfect but something to help beginners.

Simplify chords


How to explain why a curve is on a cylindrical surface?

Question: The question may be a bit general but I'm unsure about how to define it.
I have a curve: $\vec r(t) = (2\cos(t),2\sin(t), 2t)$, for $0\le t \le 2\pi$,
The problem I'm trying to pose :
"Show that the given space curve lies on a cylindrical surface"
What I've tried to say is something like (due to $\cos(t)$ and $\sin(t)$):  We rotate the curve about  $z$ axis and move it up (proportionate to rotation t ) along $z$ axis to create this cylindrical surface.
Comment: If you wanted to show that the curve lay in a(n origin-centered) *sphere*, you'd just have to show that the parameterizations of the $x$, $y$, $z$ coordinates satisfied the sphere equation $x^2+y^2+z^2=k^2$ for some $k$. For your problem, just realize that the equation for a $z$-axis-aligned cylinder is $x^2 + y^2 = k^2$ for some $k$, and show that your parameterizations satisfy that relation.
Comment: BTW: The phrase you want is probably "cylindrical *surface*".
Comment: Thanks that helped a lot :) Post it as an answer and i'll approve it.
Answer: Comment converted to answer, as requested.

If you wanted to show that the curve lay in a(n origin-centered) sphere, you'd just have to show that the parameterizations of the $x$, $y$, $z$ coordinates satisfied the sphere equation $x^2+y^2+z^2=k^2$ for some $k$.
For your problem, just realize that the equation for a $z$-axis-aligned cylinder is $x^2+y^2=k^2$ for some $k$, and show that your parameterizations satisfy that relation.
Answer: The surface lies on a cylinder because x^2+y^2 =4, irrespective of z(t)!
Please note, z can be ANY function of t, meaning.. you can write any curved line on your cylinder.


How do I display questions in blocks?

Question: How can I display questions in a block using the Quiz module?
I do it using the Views module, but when I click on Start quiz, it goes to a page. I want all functionality done inside a block.
Comment: Though now 3 years old, the Quiz FAQ addresses this question: https://www.drupal.org/node/507090#1
Answer: Though now 3 years old, the Quiz FAQ addresses this question: drupal.org/node/507090#1
How do I create a quiz block?
Quiz 3.x has the Views module integration. To create a quiz block showing the top scorers or recent quiz you can use the Views module [to expose as a block]

How do I display questions in blocks?


Why can't I use brackets in this while-loop?

Question: For clarity I want to use brackets in the following while-loop. But, I get compilation errors with brackets.
I can run this code
while (in.findInLine("00-01") == null)  in.nextLine();
    in.nextLine();
    for (int j = 0; j < data[0].length; j++)
    {
        data[0][j] =  Integer.parseInt(in.findInLine("[0-9]+|-"));
        in.nextLine();
    }

But I get errors with brackets
while (in.findInLine("00-01") == null)
{
    in.nextLine();
    in.nextLine();
    for (int j = 0; j < data[0].length; j++)
    {
        data[0][j] =  Integer.parseInt(in.findInLine("[0-9]+|-"));
        in.nextLine();
    }
}

Error: NumberFormatException:null.
So, how should i interpret
while (in.findInLine("00-01") == null)  in.nextLine();
    in.nextLine();

Comment: the two code blocks are not equivalent, due to language syntax (because of the brackets)
Comment: I'm guessing the second example is what you wanted the program to do. Please add to the question what you're reading in and what you're trying to do with the program ([Minimum, Complete and Verifiable example](https://stackoverflow.com/help/mcve)) if you would like help with the numberformatexception.
Answer: Without brackets, the loop only apply to the first statement. So your code should be
while (in.findInLine("00-01") == null)
{
    in.nextLine();
}
in.nextLine();
for (int j = 0; j < data[0].length; j++)
{
    data[0][j] =  Integer.parseInt(in.findInLine("[0-9]+|-"));
    in.nextLine();
}

Answer: Adding brackets for clarity is a great idea indeed. This question is a prime example as to why: Your indentation leads to confusion here :)
while (in.findInLine("00-01") == null)  in.nextLine();

Equals (and should be converted to):
while (in.findInLine("00-01") == null) {
  in.nextLine();
}

So, for the question:

So, how should i interpret
while (in.findInLine("00-01") == null)  in.nextLine();
    in.nextLine();

The answer is:
while (in.findInLine("00-01") == null) {
  in.nextLine();
}
in.nextLine();

Answer: Your first code block is equivalent to
while (in.findInLine("00-01") == null) {
  in.nextLine();
}

in.nextLine();

for (int j = 0; j < data[0].length; j++)
{
  data[0][j] =  Integer.parseInt(in.findInLine("[0-9]+|-"));
  in.nextLine();
}

Without more context what you want to do we not correct your code.


Approximate distribution for sum of squares of standardized Poisson random variables

Question: Suppose that $X_1, ..., X_n$ are independent and identically distributed Poisson($\lambda$) random variables.
What is a good approximating distribution for $\sum_{i = 1}^{200} \frac{(X_i - \lambda)^2}{\lambda}$?
I think that it is $\chi^2_{200}$, because it is a sum of the squares of standardized normal random variables.   However, I'm not sure if they really are standardized normal random variables.
Comment: They (the $(X_i-\lambda)/\sqrt{\lambda}$) are not standardized normal random variables: they are standardized *Poisson* variables!  There are many possible answers.  Which are good ones depend on what you mean by a "good" approximation: could you tell us what aspects of the approximation need to be good and how you measure how good they are?
Comment: There are innumerable possibilities.  Perhaps you could tell us the context in which this question arises or the actual statistical problem you are dealing with?
Comment: Two possibilities out of "innumerably many": If $\lambda$ is large then $X_i$ are nearly normal, $Z_i =(X_i - \lambda)/\sqrt{\lambda}$ are nearly standard normal, and the sum of 200 $Z_i^2$ is nearly CHISQ(200), which in turn is nearly normal. (Why and with what $\mu$ and $\sigma$ ?). // If $\lambda$ is very small, then the $X_i$ are mostly zeros and ones, and normal by CLT seems a better fit to the sum of 200.
Comment: I don't have any criteria for "good". I'm eager to learn all the possibilities.
Comment: This question is from an exam in a second-year course in mathematical statistics.  There is no more context.  The question actually asks for the expected value of the approximate distribution.
Comment: I suspect that the instructor is asking us to apply the central limit theorem.
Comment: Please don't assume that $\lambda$ is big.
Comment: In most cases it is easier to compute expectations than it is to obtain the entire distribution, and one can often compute the expectation exactly without recourse to approximation.  That is the case here. Thus, if your interest really is in answering the exam question, then please ask the exam question and explain the steps you have already taken towards answering it.
Comment: The exam question asks for the approximating distribution - just as I posed above.
Answer: There are many possible approximations. But I guess the idea here is simply CLT.
Consider that, for large $n$, the sum $Z= \sum_n Y_i$ tends to a normal $N(n\mu ,n \sigma^2 )$
if $Y_i$ are iid variables of mean $\mu$ and variance $\sigma^2$.
In our case $Y_i = \frac{(X_i-\lambda)^2}{\lambda}$, with $X_i$ being a $\lambda-$Poisson.
We only need to calculate the expectation and variance of $Y_i$, I leave that to you.
Notice that the approximation is obviously wrong in some respects: in particular, $Z$ is non-negative and discrete.

I'm not sure if [it's the sum of the squares of] standardized normal random variables.

No, of course not. $\frac{(X_i-\lambda)}{\sqrt{\lambda}}$ is a "standardized" Poisson variable. Hence it not justified to assume that $Z$ is $\chi^2_{200}$.
Comment: Ah - that makes sense. Thanks for providing a clear, concise, and straightforward answer to my question. I knew that it would not be so complicated!


How to format a number in Expression Language?

Question: How can I make a formatted output for a number (e.g. long or BigDecimal) in EL? For example, I want to limit a number of decimal digits to 3 in
${result.returnValue.contract.balance}

Comment: in most cases you might end up adding both 'maxFractionDigits' and 'minFractionDigits, attributes to get it working.
Answer: Using <fmt:formatNumber/>
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fmt/formatNumber.html
For example:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<fmt:formatNumber
     value="${result.returnValue.contract.balance}"
     maxFractionDigits="3"/>

Comment: Upvote, and a quick comment - BigDecimal definitely works like this. If you are having problems, it's not the fault of BigDecimal :)
Answer: The modern Java EE 5-8 approach with JSF is:

   <h:outputText value="#{result.returnValue.contract.balance}">
      <f:convertNumber minFractionDigits="3"/>
   </h:outputText> ...

See also Using the Standard Converters.
Since Java EE 6 (2009), JSF/Facelets is recommended.


Como fazer essa busca de Query?

Question: Estou tentando desenvolver um webService Rest no Netbeans(Java).Para tal segui esse tutorial...
https://rafaelsakurai.gitbooks.io/desenvolvimento-distribuido/content/chapter10.1.html
Porem, na hora de rodar eu tenho um erro:

Eu depurei o projeto e encontrei o ponto de erro.Eu só não sei como resolver(todo meu conhecimento relacionado a webService vem do próprio tutorial).
O ponto de erro:
Classe DAO
public class PalestraDAO {
    private EntityManager em;

    public PalestraDAO(EntityManager em) {
        this.em = em;
    }

     public List<Palestra> consultarTodos() {
            Query q = em.createNamedQuery("TipoProduto.consultarTodos"); //<- Linha de erro
            return q.getResultList();
     }
}

Classe Entidade
@Entity
@NamedQueries({
    @NamedQuery(name = "TipoProduto.consultarTodos",
            query = "SELECT tpprod_nome FROM tipoproduto ORDER BY tpprod_nome")

        //String sql = "select tpprod_id, tpprod_idExt, tpprod_nome, tpprod_descricao, tpprod_imagem, tpprod_visibilidade, tpprod_configurado, tpprod_imagem64 from tipoproduto order by tpprod_nome;";

})
@SequenceGenerator(name = "tipoProduto_seq", sequenceName = "tipoProduto_seq", allocationSize = 1, initialValue = 1)

public class TipoProduto implements Serializable {

    private static final long serialVersionUID = -2806694270931063283L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
      generator = "tipoProduto_seq")
    //private Long idEntidade;

    private int id;
    private int idExt;
    private String nome;
    private String descricao;
    private int imagem;
    private boolean visibilidade;
    private boolean configurado;
    private String imagem64;

    public boolean isConfigura() {
        return configurado;
    }

    public void setConfigura(boolean configura) {
        this.configurado = configura;
    }

    public String getImagem64(){
        return imagem64;
    }

    public int getId() {
        return id;
    }

    public void setImagem64(String imagem64){
        this.imagem64 = imagem64;
    }
    public void setId(int id) {
        this.id = id;

    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public int getImagem() {
        return imagem;
    }

    public void setImagem(int imagem) {
        this.imagem = imagem;
    }

    public boolean isVisibilidade() {
        return visibilidade;
    }

    public void setVisibilidade(boolean visibilidade) {
        this.visibilidade = visibilidade;
    }

    public int getIdExt() {
        return idExt;
    }

    public void setIdExt(int idExt) {
        this.idExt = idExt;
    }

}

Comment: https://i.stack.imgur.com/PWL2x.png - O problema não seria o nome da Named Query errado?
Comment: @SULEIMANALVESDEMORAES não, o nome estava errado apenas aqui na questão, pois na hora de subir copiei parte do código do tutorial e parte do meu código...ai houve a divergência.
Comment: https://www.guj.com.br/t/resolvido-ajuda-ejb-exception/199718/5 de uma olhada
Answer: Mas tá subindo a aplicação?
A @NamedQuery ainda tá errada.
@NamedQuery(name = "TipoProduto.consultarTodos",
        query = "SELECT tpprod_nome FROM tipoproduto ORDER BY tpprod_nome")

Deveria ser
@NamedQuery(name = "TipoProduto.consultarTodos",
        query = "SELECT tpprod.nome FROM tipoproduto tpprod ORDER BY tpprod.nome")

Como fazer essa busca de Query?


Google Mini frequently times out

Question: I have a Google Mini device that I've successfully configured to index two websites on our network.
The problem is that about 50% of the time I load the admin site
http://192.168.0.150:8000 (our internal IP for the box)
I get the "Unable to connect" message as if the server was down.
Also, sometimes while I'm using the admin site I'll open the main search in a new tab (192.168.0.150) and then when I return to the admin it no longer works.
The usual fix is to close all browsers and try again.
This issue occurs on FF3, IE8 and Chrome.
I reviewed the network settings and confirmed they look OK to me (no errors on the diagnostics). I don't really know what else to troubleshoot. Are there patches I'm not aware of? Has anyone else seen this issue?
Any troubleshooting ideas?
j
Comment: Do a ping -t and let it go for awhile. If you get drops you'll know if it's a network issue rather then a higher level application issue
Comment: No drops during a long ping session. Not a network issue.
Comment: That almost sounds like general IE8 breakage, does it apply to any browser or just IE?
Comment: FF, IE and Chrome.
Answer: Well, I'm a complete idiot.
The device was set with the same internal IP as another device on my network.
Comment: We've all made this mistake once.

Google Mini frequently times out


How do I query node sort by randomize?

Question: I want to get all articles content type, but I want to get it randomize, how can I do that? Refer to my code below:
<code>$nids = \Drupal::entityQuery('node')->condition('type', 'articles')->sort('RAND()')->execute();
</code>
I'm using drupal 8
Answer: I don't think this is possible with an entity query directly, but you can alter entity queries after they are converted into select queries.
Add a tag to your entity query and then you can alter it there.
<code>  $nids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->addTag('sort_by_random')
    ->execute();
</code>
Then add a query alter function to your custom module using the tag you added.  Drupal's select query even has a built in function to make a query sort on "RAND()":
<code>function mymodule_query_sort_by_random_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->orderRandom();
}
</code>
If you're going to have to tag an entity query to alter it, and it's not essential that you use an entity query, you might want to just replace it with a select query.
<code>$query = \Drupal::database()->select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'article')
  ->range(0, 10)
  ->orderRandom();

$results = $query->execute()->fetchCol();

if (!empty($results)) {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($results);
}
</code>
Comment: Can I add query alter function in ```mytheme.theme``` file?
Comment: @oknate, any way to add a seed variable to the mysql `rand(seed)` function? - for consistent randomized pagination.

How do I query node sort by randomize?


Floquet substitution and matrix exponentials

Question: Given
$$
    \dot{y}
    =
    A(t)y,\quad
    A(t)=
    \begin{pmatrix}
    1 + \frac{\cos t}{2 + \sin t} & 0 \\
    1 & -1
    \end{pmatrix},
    \quad y\in\mathbb{R}^2,
$$
I have calculated the $(0,t)$-flow ($\Phi^{t,0}$) and the monodromy operator $M=\Phi^{2\pi,0}$.
We have $$\Phi^{t,0}=\Psi(t)=
\begin{pmatrix}
\frac{1}{2}e^t(\sin(t)+2) & 0 \\
\frac{1}{2}(e^{t} - \frac{1}{5} e^{t} (\cos t - 2 \sin t) - \frac{4}{5}e^{-t}) & e^{-t}
\end{pmatrix},$$ and therefore $$M=\Phi^{2\pi,0}=
\begin{pmatrix}
e^{2\pi} & 0 \\
\frac{2}{5}(e^{2\pi}-e^{-2\pi}) & e^{-2\pi}
\end{pmatrix},
$$
where $\Psi(t)$ is the fundamental matrix of $A$.
Now the exercise wants me to find a matrix $\Omega$ such that $M=e^{2\pi\Omega}$.
I already know that $\Omega=\begin{pmatrix}1 & 0\\\frac{4}{5} & -1\end{pmatrix}$ (it was given so we'd know when we'd have found the correct answer), but I have to know how to get it, and also how to check that it is true (which I know by using Matlab, but cannot replicate myself).
This is where I think I have to look:
By Floquet's theorem I know that there exists a substitution of variables
$$y=\Lambda(t)z(t), t\in\mathbb{R},$$
with $\Lambda:\mathbb{R}\to M_n(\mathbb{C}), \Lambda(t+\tau)=\Lambda(t)$ (with $\tau=2\pi$ in our case?), such that the system at the start of this question becomes the system with constant coefficients:
$$
\frac{dz}{dt}=\Omega z, z\in\mathbb{C}^n, \Omega\in M_n(\mathbb{C}).
$$
But I don't know $\Omega$, $z$, $\Lambda$, and for $y$ I'm also not sure (one of two columns of fundamental matrix?)
I have already found that the eigenvalues of $M$ are $\mu_1=e^{2\pi}$ and $\mu_2=e^{-2\pi}$.
Only in the next step, where I already had to know the answer to this question, do they tell me that $\Lambda(t)=\Phi^{t,0}e^{-t\Omega}$, which they ask me to calculate in this next step. (But that's a question for another post)
Comment: Are you asking about the matrix logarithm, https://en.wikipedia.org/wiki/Logarithm_of_a_matrix , or why exactly $\Psi^{2\pi,0}=e^{2\pi\Omega}$?
Comment: @AVK I am making an exercise that requires me to rewrite $\Phi^{t,0}$ into something of the form $e^{2\pi\Omega}$, where $\Omega\in M_n(\mathbb{C})$. But I have found a solution, for which I will now create an answer.
Answer: After reading on the Jordan canonical form, I discovered an answer myself
Since $M\in M_2(\mathbb{C})$ has two distinct eigenvalues, we have that $M$ is diagonalizable.
We write
$$M=PJP^{-1},\quad J=\begin{pmatrix}e^{-2\pi} & 0 \\ 0 & e^{2\pi}\end{pmatrix},\quad P\in M_2(\mathbb{C}),\quad\det(P)\neq0.$$
So $J$ is a diagonal matrix with the eigenvalues on its diagonal. To find $P$ we solve the system of equations
$$MP=PJ.$$
Since this system has two equations in four unknowns, we have end up with two degrees of freedom, and therefore we have
$$P_{a,b}=\begin{pmatrix}0 & 5a \\ b & 2a \end{pmatrix},$$
for any $a,b\in\mathbb{R}$. We choose $P=P_{1,1}$, and see $\det(P)\neq0$, so $P$ has an inverse given by
$$
P^{-1}=\begin{pmatrix}-\frac{2}{5} & 1 \\ \frac{1}{5} & 0\end{pmatrix}.
$$
Because $J$ is a diagonal matrix we have
$$
J
=
\begin{pmatrix}
e^{-2\pi} & 0 \\
0 & e^{2\pi}
\end{pmatrix}
=
e^{
\begin{pmatrix}
-2\pi & 0 \\
0 & 2\pi
\end{pmatrix}
}
=
e^{
2\pi\hat{J}},\quad \hat{J}=\begin{pmatrix}
-1 & 0 \\
0 & 1
\end{pmatrix}.
$$
So we now have an alternate expression for $M$:
$$
M=PJP^{-1}=Pe^{
2\pi\hat{J}}
P^{-1}
=
e^{2\pi P\hat{J}P^{-1}},
$$
where
$$
P\hat{J}P^{-1}
=
\begin{pmatrix}
0 & 5 \\
1 & 2
\end{pmatrix}
\begin{pmatrix}
-1 & 0 \\
0 & 1
\end{pmatrix}
\begin{pmatrix}
-\frac{2}{5} & 1\\
\frac{1}{5} & 0
\end{pmatrix}
=
\begin{pmatrix}
1 & 0 \\
\frac{4}{5} & -1
\end{pmatrix}
=
\Omega,
$$
and that is exactly as was to be shown.


TLV Macro expansion raises warning: Assignment makes pointer from integer without a cast

Question: My TLV structure can hold string or integer.  I'm trying to create a macro that handles them both.
The example below runs as expected, but it compiles with warnings from the MACRO expansion. I understand the precompiler cannot know what type of value I'm going to assign at runtime, which is why I think it's raising the warning.
How can this little code snippet be fixed so it generates no compile warnings?
FWIW, I can code around this by not using the MACRO, but would prefer to use it if possible.
$ gcc -o simple{,.c} && ./simple
simple.c: In function 'main':
simple.c:25:21: warning: assignment makes pointer from integer without a cast [enabled by default]
       tlv.value_str = (val); \
                     ^
simple.c:38:3: note: in expansion of macro 'TLV2STR_MACRO'
   TLV2STR_MACRO(string, TYPE_INT, 11);
   ^
simple.c:28:21: warning: assignment makes integer from pointer without a cast [enabled by default]
       tlv.value_int = (val); \
                     ^
simple.c:41:3: note: in expansion of macro 'TLV2STR_MACRO'
   TLV2STR_MACRO(string, TYPE_STRING, "ELEVEN");
   ^
-----------------------------
INT   : 11
STRING: ELEVEN
-----------------------------

#include <stdio.h>

typedef struct _tlv_s {
  int type;
  size_t length;
  union _value {
    int value_int;
    char *value_str;
  } value_u;
} tlv_t;

#define value_int value_u.value_int
#define value_str value_u.value_str

#define TYPE_STRING 0
#define TYPE_INT 1

#define TLV2STR_MACRO(s, t, val) { \
    tlv_t tlv; \
    tlv.type = (t); \
    if (t == TYPE_STRING) { \
      tlv.value_str = (val); \
      sprintf(s, "STRING: %s", tlv.value_str); \
    } else { \
      tlv.value_int = (val); \
      sprintf(s, "INT   : %d", tlv.value_int); \
    } \
}

int main(int argc, char *argv[])
{
  char string[128];

  printf("-----------------------------\n");
  TLV2STR_MACRO(string, TYPE_INT, 11);
  printf("%s\n", string);

  TLV2STR_MACRO(string, TYPE_STRING, "ELEVEN");
  printf("%s\n", string);
  printf("-----------------------------\n");

}

Comment: Any reason why you can't add a cast to the relevant lines: `tlv.value_str = (char*)(val);` and `tlv.value_int = (int)(val);` ?
Comment: Thanks for the tip. I tried that and it fixed one of the cases and the other case has a slightly different warning.  I now get:

simple.c:25:23: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
       tlv.value_int = (int)(val); \
                       ^
simple.c:38:3: note: in expansion of macro 'TLV2STR_MACRO'
   TLV2STR_MACRO(string, TYPE_STRING, "ELEVEN");
   ^
Comment: With the clarity of a new morning, I don't think it will be possible to achieve what I first hoped for.  Instead, if I modify the macro to pass around pointers to values, then I can cast those pointers.  It then corrects the warnings.  I'll post my solution.
Answer:
How can this little code snippet be fixed so it generates no compile warnings?

You can add explicit casts.
tlv.value_str = (char*)(val); \
tlv.value_int = (int)(val); \

To your FWIW, such macro will not scale up, while it is fast to write for a toy example with two types and one use case, it will become painful and unreadable when more to come. Use virtual table with dispatch functions, keep your code readable, prefer not to use macros. I suggest removing confusing definitions #define value_int value_u.value_int and keeping your symbols within one namespace tlv_*. Do not end up with unreadable big switches, which your code seems to be going for. Prefer to use snprintf instead of sprintf.
Comment: All good tips, thank you.  I tried your suggestion and the warning morphed to be: simple.c:25:23: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] tlv.value_int = (int)(val); \ ^ simple.c:38:3: note: in expansion of macro 'TLV2STR_MACRO'.
Comment: `tlv.value_int = (int)(uintptr_t)(val);`
Comment: Right, that's the idea.  It means I must pass the values as pointers, and not as literal strings or integer values.  I'll post my solution and glad for your commentary.
Answer: I believe (glad to be proven otherwise) that it is not possible to pass values around as I had intended, casting them arbitrarily to string or integer.
Instead, passing pointers to values and casting the pointers is the proper way to do this.  (As an aside, if this was truly a TLV implementation, it would handle any kind of structure, but this is just a dinky little app to demo the issue with passing values).
Notice that I modified the macro to accept a pointer to the value.
#include <stdio.h>

typedef struct _tlv_s {
  int type;
  size_t length;
  union _value {
    int value_int;
    char *value_str;
  } value_u;
} tlv_t;

#define value_int value_u.value_int
#define value_str value_u.value_str

#define TYPE_STRING 0
#define TYPE_INT 1

#define TLV2STR_MACRO(s, t, valp) { \
    tlv_t tlv; \
    tlv.type = (t); \
    if (t == TYPE_STRING) { \
      tlv.value_str = (char *)(valp); \
      sprintf(s, "STRING: %s", tlv.value_str); \
    } else { \
      tlv.value_int = *(int *)(valp); \
      sprintf(s, "INT   : %d", tlv.value_int); \
    } \
}

int main(int argc, char *argv[])
{
  char string[128];
  int val_int = 11;

  printf("-----------------------------\n");
  TLV2STR_MACRO(string, TYPE_INT, &val_int);
  printf("%s\n", string);

  TLV2STR_MACRO(string, TYPE_STRING, "ELEVEN");
  printf("%s\n", string);
  printf("-----------------------------\n");

}

And the output from compile and run....
$ gcc -o simple{,.c} && ./simple asdf
-----------------------------
INT   : 11
STRING: ELEVEN
-----------------------------


Mostrar dados de json

Question: Preciso recuperar os dados PONTOS e RODADA_ATUAL
O link do json é --> https://api.cartolafc.globo.com/time/slug/semtitulos
Esse é o nome do time que quero puxar os dados: semtitulos
Quando você acessa essa url aparece todos os dados do time, mas não consigo pegar os 2 valores que preciso e imprimir na tela, tentei da seguinte forma:
<code><?php

// EM file_get_contents

    $url = "https://api.cartolafc.globo.com/time/slug/semtitulos";

    $options = array(
        'http' =>
          array(
            'method' => 'GET',
            'user_agent' => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
            'timeout' => 1
            )
    );

    $context = stream_context_create($options);
    $response = file_get_contents($url, false, $context);
    $jogadores = json_decode($response, true);

    $jogadores['atletas']['pontos'];
    $jogadores['atletas']['rodada_atual'];

     echo $jogadores;

?>
</code>
Mas não objetive resultado, porém uso o mesmo esquema acima para lista os jogadores mais escalados --> https://api.cartolafc.globo.com/mercado/destaques
e funciona normalmente. Alguém pode ajudar ???
Comment: Obrigado Junior :)
Comment: Tira o índice `['atletas']`, deixa assim: `$jogadores['pontos'];` e `$jogadores['rodada_atual'];`
Comment: Criei uma resposta só pra oficializar!!
Answer: É só você tirar o índice atletas já que essas informações estão vindo na raíz do json:
<code>$pontos = $jogadores['pontos'];
$rodada = $jogadores['rodada_atual'];
</code>
JsonFormatter é um bom site pra você analisar melhor a estrutura do JSON.

Mostrar dados de json


How to perform mean differences in Linear Probability Model in Stata

Question: I was wondering if I am able to perform a mean differences for LPM
with binary dependent variable using diff() in stata.
Dependent variable: child's education (High or Low)
Independent Variable: Father's Education (High or Low)
                      Mother's Education (High or Low)
Basically I want to test for differences between father and mother's education.
Please any help would be appreciated.
Comment: @StataMA Do you want to test that the effect on child's education of father's education and mother's education is the same?
Comment: @DimitriyV.Masterov Yes Please that is what I want to test for.....I was wondering how to test it...
Comment: @DimitriyV.Masterov in stata that is...I spent hours on this but could not get anything done. t-test and f-test would not work so I was wondering how can I test this very easily....
Answer: You can do a simple Wald test that two coefficients are equal or construct a difference of coefficients like this after fitting an LPM:
sysuse auto, clear

foreach var of varlist price mpg {
    xtile high_`var' = `var', nq(2)
    replace high_`var'=high_`var'-1
    table high_`var', c(mean `var' min `var' max `var')
}

reg foreign i.high_price i.high_mpg weight, robust
test 1.high_price=1.high_mpg
lincom 1.high_price-1.high_mpg

The way you can learn about this is that Stata has pdf manuals. Every estimation command has an entry, and all the things you can do after using that command also have an entry, under command_name_postestimation. For example, for regress, type help regress_postestimation. Clicking on the the blue links will open the relevant instructions, examples, and formulas. You want a simple linear hypothesis test.


How to check to use linear models for huge data?

Question: Generally, whenever we had the data when we want to use linear models we try to make numerical features to have normal distributions. And we check it with by plotting distribution or qqplot. It's the first time I am working on huge dataset which is having around 2000 columns. In which except 50 columns all others are numeric features. Now, how do I need to check for those many features whether there are having normal-distributions or not? how to get clarity whether to use logistic regression or not?
Comment: What exactly are you trying to check for normality, the predictors? Even under the strictest assumptions of linear modeling, we don't assume normal predictors. This is a common misconception.
Comment: Do you want to do inference or prediction? If the latter, don't use the assumptions of the former, simply cross-validate your solution.
Comment: for prediction.
Comment: Pca, T-sne visualization or Any other Dimensionality Reduction methods can help to check linearity.
Comment: Welcome to Cross Validated! We typically expect answers to contain more detail than this. How does PCA check for linearity? How does t-SNE check for linearity? Further, the question asks about normality, not linearity.
Answer: how to get clarity on whether to use logistic regression or not?
Linear regression is used when you've continuos response variable (like house price) and logistic regression is used when you've categorical response variable (e.g., spam or not spam).
There are many other techniques for both purposes.
Now, how do I need to check for those many features whether there are having normal-distributions or not?
Usually, when prediction accuracy is the objective, some (not all) assumptions of OLS can be safely ignored.
By the way, OLS never assumes normally distributed predictors or response variable. It assumes normality of residuals.
If your objective is to make inference, then you can check these assumptions (including normality of residuals) either by using statistical tests or diagnostic plots.
If you're using R for the same, you can simply get model diagnostic plots using plot(model) function.
Let me know, if you've any further query.


Não consigo pegar algumas Strings do strings.xml

Question: Quero pegar uma String que está no arquivo strings.xml, mas dá sempre o seguinte erro:
 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.macave.rastreador/com.macave.rastreador.AjudaActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2246)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:135)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                       at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
                                                       at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
                                                       at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:555)
                                                       at com.macave.rastreador.AjudaActivity.gerarQuestoes(AjudaActivity.java:42)
                                                       at com.macave.rastreador.AjudaActivity.<init>(AjudaActivity.java:17)
                                                       at java.lang.reflect.Constructor.newInstance(Native Method)
                                                       at java.lang.Class.newInstance(Class.java:1606)
                                                       at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:135)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)

E esse erro surge quando abro esta Activity:
public class AjudaActivity extends AppCompatActivity {

private List<Questao> listaDeQuestoes = gerarQuestoes();
private ListView lista;
private ArrayAdapter<String> questoes;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.janela_ajuda);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    lista = (ListView) findViewById(R.id.lista);

    final QuestaoAdapter adapter = new QuestaoAdapter(this, listaDeQuestoes);

    lista.setAdapter(adapter);

}

public List<Questao> gerarQuestoes() {

    //As perguntas e as respectivas respostas
    String pergunta1 = this.getResources().getString(R.string.pergunta_1);
    String resposta1 = this.getResources().getString(R.string.resposta_1);

//O erro surge por causa das duas linhas acima.
    List<Questao> questoes = new ArrayList<>();
    questoes.add(criaQuestao(pergunta1, resposta1));

    return questoes;
}

public Questao criaQuestao(String pergunta, String resposta) {

    Questao questao = new Questao(pergunta, resposta);

    return questao;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

   switch(item.getItemId()) {

       case android.R.id.home:
           finish();
           break;

   }

    return super.onOptionsItemSelected(item);
}

}
Preciso pegar essas Strings daquele arquivo para efeitos de tradução. Assim não dá.
Comment: A critério de simplificação do código usa "getString(R.string.pergunta_1)"; direto sem o "getResource"
Answer: Faça desta forma, colocando o metodo gerarQuestoes() dentro do seu onCreate(). Veja a baixo como deve ficar:
private List<Questao> listaDeQuestoes;
private ListView lista;
private ArrayAdapter<String> questoes;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.janela_ajuda);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

//coloque aqui o gerarQuestoes
listaDeQuestoes = gerarQuestoes();

lista = (ListView) findViewById(R.id.lista);

final QuestaoAdapter adapter = new QuestaoAdapter(this, listaDeQuestoes); lista.setAdapter(adapter);
}

Comment: Pois é!!! Falta de atenção...


Filter a list of integers based on integer multiples - C#

Question: I am trying to filter a list of int based on multiples of a specific number, but I am not sure how to do this.  I have searched this forum and found nothing related, but apologies in advance if I'm wrong.
Here is my code:
int val = 28;

List<int> divisible = new List<int>();

for (int i = 1; i <= val; i++) {
                divisible.Add(i);
}

foreach(var d in divisible)
{
     if(val % d == 0)
     {
         // do something
     }
     else
     {
      // get rid of all multiples of the number that "val" is not divisible by
     }
}

Basically, this code should create a divisible list from 1 to 28.  If val is divisible by one of the numbers in the list, thats fine, but if it falls into else, I want to be able to filter out all multiples of that number out of the current list we are looping through.
The next number that wouldn't be divisible would be 3 in this example, so in the else get rid of 6, 9, 12, ... etc.
Comment: Possible duplicate of [Check if number is prime number](https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number)
Comment: Or more precisely you probably want Sieve of Eratosthenes https://stackoverflow.com/questions/25702173/c-sharp-sieve-of-eratosthenes
Answer: Your code is fine, but you're just missing the actual code to remove the item. But there is a caveat: You cannot modify a list when you are looping through it using foreach. There are a couple ways to handle that:

Depending on your requirements, maybe just don't add them in the first place. Move your val % d == 0 condition into the for loop that adds the values, and just don't add the values that are divisible by d.
Make a new list (List<int> toRemove) where you keep track of all the values you need to remove. After you're done the foreach loop, loop through your toRemove list and use divisible.Remove(value) to remove those.
Change your foreach to a for loop, which will allow you to use divisible.RemoveAt(i). But you will have to make sure you don't skip a value on the next iteration of the for loop (since removing a value changes the size of the list).
Answer: I agree with Gabriel.  You cannot alter a underlying enumeration while traversing it with with foreach.  The easiest thing to do would be to convert it to a for loop.
Also in the initial population of your list try using the newer way
var divisible = Enumerable.Range(1, val).ToList();

then do
for(int 0 = 1; i < val; i++)
{
    if(val % d == 0)
    {
       // do something
    }
    else
    {
       divisible.RemoveAt(i);
    }
 }


Let $g_n(x)=\frac{1}{x} \chi_{(1,n)} (x) : \mathbb{R} \rightarrow \mathbb{R}$. Show $\forall$ $n>1$, $\exists$ a m>1 such that $||g_n - g_m||_1>1$.

Question: I am struggling with this question!
For each $n > 1$, let $g_n(x)=\frac{1}{x} \chi_{(1,n)} (x) : \mathbb{R} \rightarrow \mathbb{R}$, where $\chi_(1,n)$ is the characteristic function of $(1,n)$. Show that $g_n \in L_1(\lambda)$. Show that for every $n>1$, $\exists$ a m>1 such that $||g_n - g_m||_1>1$. Here $\lambda$ is the Lebesgue measure on $\mathbb{R}$.
Now it appears to me that $||g_n - g_m||_1 = \int^m_1 \frac{1}{x} dx - \int^n_1\frac{1}{x}dx = \ln(\frac{m}{n})  $. However, I am not too sure how to show that this is greater than 1.
Comment: If $m = en$ then $\ln(m/n) = 1$. So if $m > en$ then...
Comment: take $n=m/3$ if $m$ odd and $m/4$ if $m$ even.
Comment: @UmbertoP.: I guess that $m,n\in\mathbb N$
Comment: so all I have to do is define what m to take and then I have answered the question?
Comment: @user386627 I didn't check but I'm fairly certain there is a natural number larger than $en$.
Comment: @CatherineDrysdale that is correct. You are proving that there exists an $m$, so you just have to specify how to find such a value and you've answered the problem.
Answer: After your computation, the problem reduces to the following: prove that for every $n\gt 1$, there exists a integer $m\gt 1$ such that $\ln\left(m/n\right)\gt 1$.
So let $n\gt 1$ be fixed.
Using equality $\ln\left(m/n\right)=\ln m-\ln n$, we have to find $m$ such that $\ln m\gt 1+\ln n$. We know that $\lim_{m\to +\infty}\ln m=+\infty$, so we are sure that such an $m$ exists. But we can give an explicit choice: take $m=3n$. Then $$\ln m=\ln 3+\ln n\gt \ln e+\ln n=1+\ln n.$$


What if a log transformation wipes out significance in regression?

Question: I'm doing an OLS regression of donations made by individuals to a not-for-profit organisation. The donation amount is the dependent variable and dummy (treatment) variables are the only independent variables.
The non-transformed treatment variable is significant (5% level), but when I take a log of the donation amount (not treatment), the treatment variables become highly insignificant.
Does this show an outlier problem and should not be used for interpretation of the data?
Comment: If you are worried about outliers or influential points in your original or transformed model, it is worthwhile to perform a proper set of regression diagnostics. If you are doing your analysis in R you may find http://www.gmw.rug.nl/~boomsma/apstatdata/Regrdiag_R.pdf helpful, although it doesn't cover all diagnostic approaches. What is the reason you chose to perform a log transformation - was there a known theoretical result, or a pattern in your data, that made you suspect this is the correct functional form?
Comment: If I understand correctly, you are running a t-test, w/ donation amount as the DV, & treatment as the IV. Is that right? Now, for some reason, you feel compelled to log transform your DV, but if you do so, the t-test is no longer significant. Is that right? If so, why do you believe you should transform your DV?
Comment: what do you mean by "dummy (treatment)" variables?
Comment: What do the conditional distributions look like?
Answer: The proper solution depends on the nature of your dependent variable: donation amount.
If this takes on a small number of integer values (in number of dollars or Euros  or whatever) and those integers are all small (or adjacent) then some sort of count model is appropriate (as @Tomas notes). This could be Poisson or negative binomial regression, or perhaps a zero-inflated version of these, if you are interested in who gave nothing.
If donation amount takes on a small number of levels, but those values are widely dispersed (as might be if people were responding to a request that had a number of donation levels and check boxes) then an ordinal logistic regression might be correct.
However, if donation amount takes on a large number of levels and they are widely dispersed and there are no zeroes (e.g. some people give \$10, some give $10,000, most give somewhere in between) then it might be that a log transformation is correct or it might be that you need some form of robust regression. It depends partly on substantive questions: Are differences in amount given better looked at on arithmetic or multiplicative scale?  That is, which of these two differences are equivalent?
1) The difference between \$10 and \$20 is the same as the difference between \$1000 and $1010?
2) The difference between \$10 and \$20 is the same as the difference between \$1000 and $2000?
If 1) then some robust regression is probably better; if 2) then a log transform.
One thing that seems very unlikely to me is that the regular (OLS) regression on the untransformed donation amount could be correct. But you'd have to examine residual plots to be sure.
Comment: A difficulty expressing whether arithmetic/multiplicative scales are preferable, is that the very word "difference" strongly suggests subtraction and the arithmetic scale (if read too literally, the difference between 10 and 20, or 1000 and 1010, _is_ 10). I suppose another way to express the distinction, is that if a "_proportional_ difference" is more appropriate then a multiplicative scale is preferred. Let's say sex is one of the binary IVs: is (1) "on average women give 18 dollars more than men" more appropriate than (2) "on average women give 23% more than men"?
Answer: Amount (donation) is a count so first thing that comes to my mind is a Poisson regression. This actually uses the log link function. The fact that the relationship is no longer significant does not necessarily mean that the model is less accurate. This is also related to the difference between accuracy and precision.
I cannot say more until I know more about your dependent variable.
Comment: Even if donations are not thought of as counts, their values are positive and likely to be skewed, so something like a Poisson is still likely to be appropriate (more generally, a generalized linear model with log link). Presumably you have no zeros in your data, but if you did, the same point applies.


Arrangement of triad inversions

Question: For any given triad there are six possible arrangements of the notes.
For example: CEG, CGE, GEC, GCE, ECG, EGC
Why are only three of them taken account of, ie. root, first and second inversions?
Comment: I'm puzzled... what are the 6 possible arrangements?
Comment: @Tetsujin He probably means that those examples are rather 6 inversions than only three: CEG, CGE, GEC, GCE, ECG, EGC.
Answer: Theorists have decided that there will only be three 'inversions' - root, with base note (C) at the bottom, 1st inversion, with E at the bottom, and 2nd inversion, with G at the bottom. Obviously using C major as the key and chord.
So, C E G and C G E are both root position triads. E G C and E C G both 1st inversions, and G C E and G E C both 2nd inversions.
You'll see that some are close voicings, where the three notes are as close as possible to each other, while the others are open voicings  - which could have other chord tones in between the played notes.
Even with larger chords, such as played on guitar or piano, where there may be two or three of the same name notes, but in different octaves, the inversion is named from the lowest note. You may be interested to find out about drop chords too.
It follows that chords with four notes will also have a third inversion, and so on. But voicings will have many combinations at and after that many notes.
Answer: If you're trying to take everything into account, there are more than six arrangements - C4-E4-G4 is not the same as C4-E4-G5.
Any language has different levels of specificity.  If you tell me you bought a car, that's more general than if you tell me you bought a blue car, and that's still more general than telling me you bought a blue 2017 Focus.
Music is the same.  "C" as a chord name is general - any arrangement of CEG will fit the description.  "First inversion C" or 6 with an E in figured bass is more specific... but not as specific as standard notation, which will tell you the exact arrangement.
We really don't need a tool more specific than an inversion, but less specific than standard notation, which will tell you if it's G4 or G5 in the voicing.

Arrangement of triad inversions


Exibir Imagem dentro de outra

Question: Galera Assim e tenho essa imagem de carteirinha e preciso exibir outra imagem em cima no caso a foto da pessoa, consegui inserir os dados buscados do banco mas a foto da pessoa não consigo buscar do banco e exibir em cima dessa imagem da carteirinha

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>exemplo</title>

    <?php
    //Inclui a conexao
    require 'conexao.php';

ex1.php
        //Prepara conexão com mysql, classe pdo
        $stm = $pdo->prepare( 'SELECT * FROM ifsp WHERE id = 4' );
        //Executa conexao
        $stm->execute();

        //Tranforma toda pesquisa em uma matriz
        $consulta = $stm->fetch( PDO::FETCH_ASSOC );

    // Carregar imagem já existente no servidor
    $imagem = imagecreatefromjpeg( "carteirinha.jpg" );
    /* @Parametros
     * "foto.jpg" - Caminho relativo ou absoluto da imagem a ser carregada.
     */

    // Cor de saída
    $cor = imagecolorallocate( $imagem, 0, 0, 0 );
    /* @Parametros
     * $imagem - Imagem previamente criada Usei imagecreatefromjpeg
     * 0 - Cor vermelha ( RGB )
     * 0 - Cor verde ( RGB )
     * 0 - Cor azul ( RGB )
     * -- No caso acima é preto
     */

    // Texto que será escrito na imagem
    $nome = $consulta['nome_aluno'];
    $rg = $consulta['rg'];
    $prontuario = $consulta['prontuario'];
    $datavalidade = $consulta['data_validade'];
    $curso = $consulta['curso'];
    $periodo = $consulta['periodo'];
    /* @Parametros
     * $_GET['nome'] - Texto que será escrito
     */

    // Escrever nome
    imagestring( $imagem, 5, 220, 750, $nome, $cor );
    /* @Parametros
     * $imagem - Imagem previamente criada Usei imagecreatefromjpeg
     * 5 - tamanho da fonte. Valores de 1 a 5
     * 15 - Posição X do texto na imagem
     * 515 - Posição Y do texto na imagem
     * $nome - Texto que será escrito
     * $cor - Cor criada pelo imagecolorallocate
     */
    imagestring( $imagem, 5, 100, 860, $rg, $cor );
    imagestring( $imagem, 5, 100, 925, $prontuario, $cor );
    imagestring( $imagem, 5, 350, 925, $datavalidade, $cor );
    imagestring( $imagem, 5, 220, 620, $curso, $cor );
    imagestring( $imagem, 5, 350, 860, $periodo, $cor );;
    // Header informando que é uma imagem JPEG
    header( 'Content-type: image/jpeg' );

    // eEnvia a imagem para o borwser ou arquivo
    imagejpeg( $imagem, NULL, 80 );
    /* @Parametros
     * $imagem - Imagem previamente criada Usei imagecreatefromjpeg
     * NULL - O caminho para salvar o arquivo.
              Se não definido ou NULL, o stream da imagem será mostrado diretamente.
     * 80 - Qualidade da compresão da imagem.
     */

Codigo para exibir imagem do banco
<?php
// Incluindo arquivo de conexão
require 'conexao.php';

$id = (int) $_GET['id'];

// Selecionando fotos
$stmt = $pdo->prepare('SELECT conteudo, tipo FROM ifsp WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

// Se executado
if ($stmt->execute())
{
    // Alocando foto
    $foto = $stmt->fetchObject();

    // Se existir
    if ($foto != null)
    {
        // Definindo tipo do retorno
        header('Content-Type: '. $foto->tipo);

        // Retornando conteudo
        echo $foto->conteudo;
    }
}

Comment: Então Victor, deixa eu ver se te ajudo, O problema está onde exatamente: A imagem da pessoa que não está vindo ou você está com problema de posicionar a imagem da pessoa em cima de outra ?
Comment: Não consigo trazer a foto da pessoa que esta no banco pra exibir em cima da carteirinha
Answer: Visto que todos os dados estão na mesma tabela (ifsp) você pode adicionar a foto na imagem da carteirinha que você criou utilizando imagecopyresampled (sem tradução), dessa maneira elimina a necessidade de sobrepor as duas imagens.
...
imagestring( $imagem, 5, 350, 860, $periodo, $cor );

$foto = imagecreatefromstring($consulta['conteudo']); // cria imagem
imagecopyresampled(
  $imagem, // destino
  $foto, // origem
  $posicao_x, // posição X na carteirinha
  $posicao_y, // posição Y na carteirinha
  0, // posição X na origem
  0, // posição Y na origem
  $largura, // largura desejada na carteirinha
  $altura, // altura desejada na carteirinha
  imagesx($foto), // largura da origem
  imagesy($foto) // altura da origem
);

// Header informando que é uma imagem JPEG
header( 'Content-type: image/jpeg' );
...

Comment: Vlw deu muito certo Obrigado

Exibir Imagem dentro de outra


Partial sums of partial sums

Question: $$s_0[n] = 1, 1, 1, 1, ...$$
$$s_1[n] = \sum_{i=1}^{n}s_0[i]=1,2,3,4,...$$
$$s_2[n] = \sum_{i=1}^{n}s_1[i]=1,3,6,10,...$$
$$s_k[n] = \sum_{i=1}^{n}s_{k-1}[i]$$
can anyone please remind me what the closed form for $s_k[n]$ is?
Answer: Write out all of the values and then turn them $45^{\circ}$. You'll see Pascal's triangle appear, and it's not hard to prove that this is actually Pascal's triangle. After a little fiddling it follows that the closed form is
$$s_k[n] = {n+k \choose n}$$
(at least if you index your series starting with $0$). The partial sum relation you give is known as the hockey-stick identity and has a fairly straightforward combinatorial proof.
A very general method for finding partial sums is the following: suppose $f_n$ is a sequence whose generating function
$$F(x) = \sum_{n \ge 0} f_n x^n$$
you know, and you are interested in the sequence of partial sums $\displaystyle s_n = \sum_{k=0}^n f_k$. Then
$$\sum_{n \ge 0} s_n x^n = \frac{F(x)}{1 - x}.$$
See e.g. Wilf's generatingfunctionology for details.
Answer: $s_k[n]={{n+k}\choose k}$ if you start with $n=0$.
Answer: Note: $s_k[n] = s_k[n-1] + s_{k-1}[n]$, so this is the same as Pascal's triangle (i.e. $S(k,n) = S(k,n-1) + S(k-1,n)$ ) and so the answer is going to be something like $xCy$. Since $s_0[n] = 1$ and $s_k[0] = 1$, these define the two sides of Pascal's triangle and so we have
 $$s_k[n] = (n+k)Ck = (n+k)!/(n!k!).$$

Partial sums of partial sums


Show array element - when index is a variable - inaccesible value

Question: during debbugging,
why I can't view an array element?
when index is a variable (arrai[i]) I get Inaccesible value issue
But when index is a const number (array[1]) it works fine.
Please view my picture:

I get the issue with any type of array (simple array of integers or strings or also with multidimensional array of objects)
I use Delphi XE4
How can I fix it?
Comment: Are you sure optimization is disabled for your project when in debug mode?
Answer: Try to disable Optimization in the Project Options when run in DEBUG mode.
Comment: Tested with Delphi 10.4.1. When optimization option is TRUE, then weekdays[i] is not accessible during debug. But it gives a clear message now: "Variable 'i' inaccessible here due to optimization".


How to use $form['#action'] in Views PHP field

Question: I print the comment form for each node in my view with the Views PHP module. The URL of the view is user/%/selection, and the code I am using is the following one.
<code>$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_node_MYCONTENTTYPE_form', $comment);
$form['#action'] = url('user/'.$row->uid.'/selection');
print render($form);
</code>
When the form is submitted, I get /node/nid#comment-17 as URL.
Could you explain why <code>$form['#action']</code> doesn't work?
Answer: Instead of this method, why cannot a new submit handler be written? so that you can use drupal_goto there and redirect.


What would you consider to be called a "helper method"?

Question: I am wondering what kind of methods are "helper methods". Where do we have to draw te border to say that an specific method is a "helper method"? Actually, I consider any method to be a "helper method" if it's not an initialization method, a method implemented for conforming to an protocol or delegation response methods. Any other method I implement to perform anything is a "helper method" in my perspective, but I feel that there are more categories to think of.
Why I want this to know? Because I want to make mor use of the #pragma mark HEADLINE stuff in Xcode. I beliefe it's good to organize the code in some way.
Please help me to get my picture of an "helper method" clear. Examples appreciated!
Comment: If your goal is to organize your code, it would probably make more sense to divide things into groupings that make sense to you, rather than using other people's definitions of a subjective term.
Answer: I look at it as Methods that aren't required for the proper functioning of library, but make things easier or more readable for the end user.
Hmmm... didn't give an example.  Lets say you have a function to get users from a database, and it took the form of
User GetUsers(UserRole)
{
//Do Something
}

And example helper method might be
User GetAdmins()
{
   return GetUsers("Admins");
}

Its a crude pseudo code type example, but gives you the gist.  The functionality of GetAdmins is complete in GetUsers(), but the GetAdmins helper function helps readability ( and nothing more ).
Make sense?
Comment: Actually, I would call your GetAdmins() function a (convenience) wrapper.
Comment: True, although wouldn't you consider a conveinence wrapper a type of helper method?  I was going to use an example of calculating the distance between two points, but that could just as easily be considered a core method.  It really is all rather subjective in the end.  I think the key ( in either case ), is that it is not a core requirement.
Answer: I'd say a method that is specific to a particular class but does not rely on access to private implementation details of that class is a helper method for that class.  Helper methods should not be stateful either.
Answer: I think of a helper method as one that has only one caller.  It could be inlined, but because its code is external to the caller, the caller is easier to understand, with less innate complexity.
Comment: And why helper method could be used by more than one caller? There are cases there you extracting some shared logic to serve several methods, also very used for testing purpose.
Comment: That's a fine thing, too.  But to me, that method isn't a helper method; it's an encapsulation of common functionality.  The question is about what "helper" means, and to me, it means the method has little reason to exist beyond simplifying the called method; once a method has two callers, it has a much more important reason.
Answer: I think you question is context dependent. In general you could say, as you stated, that every method could be a helper method in certain application. But I believe in most of the cases helper methods is more about dividing some general method in several more smaller one to provide more clear picture and good code.
Answer: Generally I define helper methods as methods that make a class easier to use, but provide no new behaviours that can't be implemented by calling other more complicated methods.
Examples:

+[NSObject new] is a helper method for [[NSObject alloc] init];
NSClassFromString(str) is a helper method for objc_getClass([str UTF8String]);
+[NSURL URLWithString:str] is a helper method for [[[NSURL alloc] initWithString:str] autorelease];
-[NSURLRequest initWithRequest:request delegate:delegate] is a helper method for [request initWithRequest:request delegate:delegate startImmediately:NO]
-[NSString substringFromIndex:] is a helper method for -[NSString substringWithRange:]
Answer: I'd chime in with something that provides some general utility, rather than a shim around a more complex function or something to do with implementation specifics. For example, a helper method for me would be something like a method on NSString which returned an NSDate directly, rather than requiring you to use NSDateFormatters all over the place.
In this respect, I'd categorize helper methods as either something to help you DRY-up your code by wrapping some frequently-used sequence into a single function, or something which you write to wrap up some chunk of awkward code from another API (yes, these two are usually the same thing).
At the risk of looking like I'm trying to pimp my own code here, I'll point you at the Extensions directory of my toolkit repository, which contains a whole bunch of stuff I wrote as 'helper methods' on standard Objective-C classes. Case in point: +(NSError *)errorWithCFStreamError:(CFStreamError)streamError, which is a 'helper method' for converting an old-style CFStreamError value to a proper NSError/CFErrorRef object using the new values exported in OS X 10.5 (and iPhone).
Answer: On Objective-C, I think you could call any private method a "helper method", where by private I mean that the method signature doesn't appear in the .h file.  I.e. these are methods you'd likely declare in a class continuation in the .m file:
@interface MyClass ()
- (void)somePrivateMethod;
@end

What some other answers are calling helper methods -- optional but public methods that are not crucial to the API -- I would rather call "convenience methods".


A module for generating PDFs

Question: I have tried PDF using mPDF and Printer-friendly pages (Drupal 7.x). They both need own styling of an output. I have got a CSS that formats my pages for printing. I would like to generate PDFs by just "printing" to them. I do not want to maintain separate styles.
Is there a module that generate a PDF file with an output that would be sent to a printer?
Comment: If you need css handling I guess your best bet would a local webserver that takes screenshots, there are plenty of similar question on stackoverflow for that issue. but for sake of ease implement any webservice for that, I made some good experience with http://convertapi.com/ additionally you will probably have to make sure the right css is used for that request.
Answer: Try Printer, email and PDF versions module.

This module allows you to generate the following printer-friendly
  versions of any node:
Printer-friendly version (webpage format) (at
  www.example.com/print/nid)
PDF version (at www.example.com/printpdf/nid)
Send by email (at www.example.com/printmail/nid)
where nid is the node id of content to render.
Comment: @NetExpert, take a look at how they print/render content in `print.tpl.php`
Comment: It uses its own print.tpl.php template. I would like something that builds a content using my hmtl.tpl.php, page.tpl.php etc.
Comment: @NetExpert, how can you do that? If we use `page.tpl.php` we will get all css/images in print page. If you still want to use `page.tpl.php` consider invoking the `theme` fn provided by that module
Comment: @nikhil-m I use CSS (print media) to hide what I do not want. You can look at Zen template for an example.

The module makes an output inconsistent. You receive a different looking page that one you receive by using a print command of a browser.
Comment: @nikhil-m Using a theme function looks promising. I replaced print.tpl.php content with . I have got my html now. However a page content is missing. How should I build a render array for a page (I believe I could add it within theme_preprocess_print())?
Comment: @nikhil-m They just print a content which is a node only. I need to process a page, a region etc.. The problem with using a html.tpl.php is it prints $page and it is blank now.

A module for generating PDFs


How many answers to this combinatorial puzzle?

Question: Take a square. How many ways are there to draw or not draw a line from the center to each of its sides?
16, of course. Here are all the different squares:

Now, how many ways are there to put those squares in a 4x4 square so that all lines meet up (and no lines touch the border)? Of course, rotating the squares is also not allowed.
There are 652 solutions (counting in all rotations and reflections). I got that easily with a simple backtracking program. But that's the easy version of the problem.
To get the hard one, just add diagonals. Now there are 256 different squares:

How many solutions exist for this one (to clarify: now we're trying to arrange all of them in a 16x16 square)?
I'm a CS major, so I tried throwing everything I learned about algorithms at this one. I solved it as an Exact Cover problem, and as a SAT problem (well, #SAT, to be precise). Either way, it's way, way too big for all the software I have available.
My only hope now is that it can be solved mathematically, but I lack the tools and knowledge. Save all that's left of my sanity, please!
Comment: @RossMillikan, I just calculated the number of midpoints of edges, which is $4\cdot 5\cdot 2=40$. Then, for every midpoint you can choose whether or not the adjacent squares have a line to that point, which yields $2^{40}$. When lines may not touch the border, we get $2\cdot 3\cdot 4=24$ midpoints, so $2^{24}$ solutions.
Comment: @Ragnar:  I thought you were doing the one with diagonals but not touching the sides.  Besides the $24$, there are $18$ diagonals, making $42$ choices.  However, at this point neither of us considered that you can't have lines stop in the middle of a square.
Comment: @RossMillikan, since the squares with only one line in them are shown in the examples to choose from, I supposed they are allowed to, but I'm not sure. (Since the answer the OP gave is not a power of $2$, I think you're right.)
Comment: To clarify: 1) The real version of the puzzle requires a 16 x 16 square. 2) All the tiles need to be used, each only once. 3) All the lines must join up, no lines should touch the sides.

And by the way, I did a crude estimation and the upper bound (not a very tight one) on the answer is 3.29 x 10 ^ 272
Comment: The squares that have only 1 line; how can they be connected from both ends? Is connecting the edge enough or will squares have to overlap? Also, for a diagonal line that will end with 1 point at the centre of 4 squares, is there any limit for how many of the other 3 have to connect to it?
Answer: Here is an approach that avoids backtracking, but will probably be too slow for the $8 \times 8$ diagonal one.  I will describe it for the $4 \times 4$ with diagonals.  You can use a $10$ bit binary string to define the lines connecting one column to another-there are four potential horizontal lines and six potential diagonal lines.  For each string count the number of legal first columns.  There are three more choices (eight possibilities) and the constraint is that all four squares do not have a single active line coming in.  The case with all four horizontals active forces all the verticals to be active, so there is just one possibility for that.  The case with all ten active allows all eight possibilities in the vertical direction.  You finish with a list of the number of ways for each string to represent the line between the first and second columns.  Then for each string between the second and third columns, loop over the strings between first and second, count the choices for the verticals in the second column and sum up.  This is $2^{20}$ loops, just a million.  Keep going, noting that the fourth output must be all zeros.  The mantra is forget what you don't need to know-when you get to the third/fourth column joint, you need to know how many ways there are to generate a given string, but not what they look like.
Unfortunately, this would require $(2^{22})^2$ loops for the $8 \times 8$ with diagonals, which is too many for my computer.
Comment: Interesting approach, but it really is too big for the real puzzle. Especially since it's not  even a 8 x 8 square, but a 16 x 16 one.
Comment: I hadn't recognized that you had to use each tile once.  I thought you just had to fill the square.  But then you just need the tiles to match at the edges, you don't mind if they have a single line in the center.
Comment: Yes, I do mind! Every line going out of a square has to match another line going out of the neighboring square.
Comment: No, I meant in the center of the square.  My answer suggested you had to pick tiles that didn't have a line ending in the center. I was answering a completely different problem that you were asking about.


React Close dropdown when other dropdown is opened

Question: I tried but i can't. Do I need to create separate function for each dropdown? I think there should be a brevity. I want other open dropdowns to close when the user clicks on a dropdown. I hope someone can help me. it took me a long time still i couldn't find any result. this way i will add 2 more dropdown menus.
    import React, { useState } from "react";

export const AsideItems = () => {
  const [menuOpened, setMenuOpened] = useState(false);
  const [menuOpenedSecond, setMenuOpenedSecond] = useState(false);

  const handleMenu = () => {
    setMenuOpened((menuOpened) => !menuOpened);
  };
  const handleMenuSecond = () => {
    setMenuOpenedSecond((menuOpenedSecond) => !menuOpenedSecond);
  };

  return (
    <>

        Computers & Laptops

      <span
        onClick={handleMenu}
        className={`list-icon${menuOpened ? " " : " open-list"}`}
      >
        +

      <span
        onClick={handleMenu}
        className={`list-icon${menuOpened ? " open-list" : " "}`}
      >
        -

      <div className={`sub-menu${menuOpened ? " open-sub" : " "}`}>

              Computer Accessories

      Game Consoles

    <span
      onClick={handleMenuSecond}
      className={`list-icon${menuOpenedSecond ? " " : " open-list"}`}
    >
      +

    <span
      onClick={handleMenuSecond}
      className={`list-icon${menuOpenedSecond ? " open-list" : " "}`}
    >
      -

    <div className={`sub-menu${menuOpenedSecond ? " open-sub" : " "}`}>

            Consoles

    </>
  );
};

Answer: Instead of using multiple boolean state values, you can use a single state value that holds the name (or index) of the open menu. This way you only need one state variable and only one menu can be open at a time. To indicate that no menu is open, you can set the state value to null.
Here's an example:
const menuNames = {
    first: "first",
    second: "second",
    // ...
}

export const AsideItems = () => {
    const [openMenuName, setOpenMenuName] = React.useState(null);

    return (
        <>
             setOpenMenuName(menuNames.first)}
                className={`list-icon${openMenuName === menuNames.first ? " " : " open-list"}`}
            >
                +

             setOpenMenuName(menuNames.second)}
                className={`list-icon${openMenuName === menuNames.second ? " " : " open-list"}`}
            >
                +

        </>
    )
}

Note you don't have to define an object containing the menu names, but it's safer than just using string literals.


WCF custom UserNameValidator - When and where in the channel mode is this added?

Question: I need to access the EndPoint on a service before UserNamePassword valdiation is done. I am having a custom usernamepasswordvalidator. Before this authentication i need to access the endpoint. I tried implementing messageinspector,iservicehbevaior etc but all of them seems to be hit only after UserNamePassword validation. Is there any extensibility point before UserNamePassword validation that would allow me to access the EndPoint?
Answer: What kind of processing do you want to do before UserNamePassword validation is done?
A few things I can think of:

Create a custom channel, and then a custom binding that injects this channel between the transport and the security channels
Create a custom encoder that wraps the built-in (text, binary, etc.) encoder that you're using
Comment: I just need to acces the endpoint before authentication is done. I guess writing a custom channle or an encoder might be an overkill here.But i'll definitely give custom encoder a go until i get a better way to do it.


Atualizar componente/object Angular 6

Question: Tenho 3 componentes que trocam um object entre si, como faço para quando atualizar um os outros também atualizar sozinho?
Exemplo: tenho os componentes 1, 2 e 3, o 1 chama o 2 passando um object e o 2 chama o 3 passando o mesmo object, tudo isso na criação dos componentes.
Tenho que atualizar o componente 3 quando o object no componente 1 sofrer alteração.
Comment: Você tem que notificar o evento pai, e assim por diante que um evento ocorreu no componente filho. Você precisa dessa diretiva: https://angular.io/api/core/EventEmitter. Faz uma demo aqui:https://stackblitz.com/ que saberemos melhor o problema.
Answer: Para fazer isso você deve utilizar o @Input, passando do pai para o filho o valor que você quer.
Neste exemplo que você deu, as propriedades dos component 2 e 3 devem ter a anotação @Input, para os pais 'inputarem' o valor nos filhos. Component inputa no 2, o 2 inputa no 3, por isso só o 2 e 3 precisam o @Input. E assim por diante.
Para enviar valor dos filhos para os pais, você deve utilizar o @Output.
O detalhamento de como utilizar o @Input e @Output no site do Angular:
https://angular.io/guide/component-interaction
Fiz um exemplo para você ver funcionando:
https://stackblitz.com/edit/angular-pufge7

Atualizar componente/object Angular 6


Windows Server 2012 HA Cluster Shared Volume "Online (No Access)"

Question: We have a Hyper-V 3.0 Failover Cluster (2 servers) each running Windows Server 2012 RC. We have Shared Storage (HP P4300) which is reporting no errors and is working just fine as either a standalone disk or witness disk within the cluster. We have also installed the HP P4000 DSM which is also working fine (this is on one of the Hyper-V nodes and has full access to the disk).
The issue is that when we add the Cluster Disk (which initially reports as Online with 'Available Storage' status) as a Cluster Shared Volume, it briefly reports as Online until reverting to Online (No Access). They do not appear in C:\ClusterStorage as they should on either of the member nodes. There are no errors or warnings in the log and the only informational message is that the disk was brought online.
To further confuse things, enabling 'Maintenance Mode' on the disk changes the status to Online (Maintenance Mode) and the disk now appears in C:\ClusterStorage (on the node where the cluster disk is located) and allows read/write access just fine.
There doesn't appear to be any information regarding Online (No Access) on the internet, so any information at all would be very much appreciated right now.
Results of a 'Validate Cluster' only brought back the following relevant errors:

Successfully issued call to Persistent Reservation REGISTER using
Invalid RESERVATION KEY 0xc, SERVICE ACTION RESERVATION KEY 0xd, for
Test Disk 0 from node PRODHV1.prodhv.local.
Test Disk 0 does not support SCSI-3 Persistent Reservations commands
needed to support clustered Storage Pools. Some storage devices
require specific firmware versions or settings to function properly
with failover clusters. Please contact your storage administrator or
storage vendor to check the configuration of the storage to allow it
to function properly with failover clusters.

These errors do seem most relevant to the issue and would probably cause it, although the P4300 supports SCSI-3 as far as I can tell. (source)
EDIT: Just some more information to fuel the fire, this works perfectly well on Server 2008 R2, so I know that SCSI-3 is actually supported on the device. Whether the DSM Driver works well under 2012 or not is a different matter, but it may well be that.
Comment: Have you validated the cluster? That's almost certain to tell you where the problem is. Seems to me as if your storage isn't allowing multiple host access to a single LUN.
Comment: @ChrisMcKeown Thanks, just ran a validation and the only real error is that which I have updated the answer with now.
Comment: Your running beta software with unsupported drivers... expect problems (the kind you can't "solve" yourself). It looks like the DSM driver is not working correctly in Server 2012. You'll have to use the MS Driver (with the lesser functionality) or wait for HP to release a DSM that's compatible with Server 2012.
Comment: @ChrisS Don't worry, definitely expecting problems. Just not unsolvable ones! :)
Comment: Update - The MS DSM didn't work, disabling MPIO didn't work. We're trying to contact HP Support to see when support may be available, but not expecting too much on that front.
Answer: The ability to have Persistent Reservations is important - it allows to cluster to ensure that the only nodes which have the ability to access and modify the LUN are the ones that belong to the cluster.
You may need to ensure that you have the latest firmware for your SAN, the latest drivers and DSM. It appears that you're not alone although that thread is quite old.
Comment: We've just updated the SAN's firmware and still having the same issue unfortunately. We're going to try using Microsoft's default DSM driver and see if that works, but then the SAN only runs in Failover mode.
Answer: Based on the error message and the information you posted the storage device is either not loaded with drivers that support concurrent access or your device does not support multi-host access to begin with.
Are you sure you have a 2012 approved driver and that your device supports multi-host access?
Comment: The `HP P4000 DSM for MPIO` driver is showing as running on boot and is signed, despite the status being "Degraded". I'm not sure what that means, but the default MS driver is also showing as "Degraded" as are a few others. EDIT: Also just to confirm that this did work on Server 2008 R2 also, we'd just like to utilise Hyper-V 3.0 features.
Comment: It's possible the latest drivers and firmware have simply not been updated yet to support the 2012 requirements.  I'm not sure.
Comment: Definitely seems most likely yes, it's just a little weird to me that 2008 R2 signed drivers wouldn't work on 2012. As far as I can tell the requirements didn't change so much.
Comment: No but the functionality certainly did to support seamless cross-network moves of VMs.


Show that a group does not have a composition series

Question: I am asked to show that the following group does not have a composition series:
$$X = \left\{ \left( \begin{array}{cc}
\lambda & 0 \\
\mu & \tau  \\
 \end{array} \right) : \lambda, \, \mu, \, \tau \in \mathbb{Q}, \, \lambda \neq 0 \neq \tau \right\}$$
We know that if any group is abelian, then it has a composition series if and only if it is finite. But $X$ is not abelian, is it? So I am a bit stuck here. I am not really too sure which direction to take to prove this.I thought maybe to prove that it is isomorphic to a well known group which does not have a composition series, but to be honest I  can't think of any.
Another approach I had in this question was to find a normal subgroup of $X$, $N$, such that $N$ does not have a composition series. This would in theory work because if $G$ has a composition series and $M$ is a normal subgroup of $G$ then $M$ has a composition series. However I could not really think of any.
Any sort of help would be very appreciated. Thank you.
Answer: The set of matrices $\begin{pmatrix} 1 & 0 \\ \gamma & 1\end{pmatrix}$ forms an infinite abelian normal subgroup.