What to do when assumptions of both ANOVA and Kruskal-Wallis are violated?

Question: I am trying to analyse whether three groups (samples sizes 27, 26 and 23) differ in their responses to 20 questionnaire items, each measured using a 5-point likert scale. The items are all investigating different things, so it is not appropriate/of interest to condense them into likert scales for broader constructs.
I am well aware of the controversy surrounding the use of ANOVA for likert data. However, I have been advised that this could be justified, and I know of papers that suggest ANOVA is relatively robust in most situations. However, my data is also non-normal and contains multiple extreme outliers. As these outliers represent real likert responses, I believe that they have value and should not be excluded. Overall, I feel like there are a lot of arguments against using one-way ANOVAs to analyse the data at this point.
I have therefore also endeavoured to analyse the data using the Kruskal-Wallis test, which at first seemed to be more appropriate. However, the data violated the assumption that distributions across groups should be similar and consequently analysis can only tell me about the distributions of likert responses, rather than median responses which would make more interpretable sense (I think?). Following a guide to conducting and reporting the analysis, I arrived at findings like this:
'Likert ratings increased from Group 1 (mean rank = 33.78), to Group 2 (mean rank = 38.41), to Group 3 (mean rank = 42.77), but the differences were not statistically significant, χ2(2) = 2.218, p = .330.'
Talking about 'mean rank' seems to be irrelevant to my discussion of whether, and in what ways, groups differed in their likert responses.
My supervisor is suggesting that I stick to one-way ANOVA, but I do not see how the results of this can be justified for this data. At the same time, Kruskel-Wallis does not seem suitable for my questions of interest.
I would greatly appreciate any advise on how I can best analyse my data at this point!
Comment: K-W and ANOVA both tend to fall apart in the presence of heteroskedasticity across groups; if this is your main concern, you might want to try Welch's ANOVA (https://www.statisticshowto.datasciencecentral.com/welchs-anova/), which corrects for this.
Comment: The Kruskal Wallis does not compare medians without additional assumptions. There's no actual requirement that "distributions across groups should be similar"; that's a requirement for a pure location-shift alternative (which would turn it into a comparison of means, medians, upper quartiles or whatever other location measure you like). The assumption you need for a valid test is that the shapes are the same under the null (which of course you can't assess from the data), and that the kind of alternatives you want to consider will tend to make the test statistic larger than under the null.
Comment: Suppose " it is not appropriate/of interest to condense them" means you analyze 20 items separately. Then create 20 3 by 5 contingency tables and analyze these tables one by one.
Comment: A pure location-shift alternative doesn't make much sense for Likert scale data; the only possible location shifts would be shifts by integers and even then only if your scales used less than the possible range.
Answer: One of the difficulties of departing from the original measurement scale to find a suitable test is figuring out
how to understand results on an unfamiliar, possibly unintuitive,
measurement scale. If you get a suitably small P-value, then
you can assert that there are significant differences among
groups, but it can be difficult to assess whether these differences are large enough (on some scale) to be of practical interest.
Your sample sizes 27, 26, and 23 are modest, but
it is worthwhile, as suggested by @jbowman, to investigate whether the Welch ANOVA (which
does not assume equal variances) finds significant differences,
and if so, what that means.
Simulated data. Below I generate fake data for three groups, in which subjects have somewhat different probabilities of choosing the various Likert values on a particular question. Specifically, responses 1 through 5 have proportions as follows--increasingly likely to choose higher values as we go from Group 1, to 2, to 3. (We could turn the 'proportions' into probabilities by dividing by 14, but it is not necessary to do so.)
p1 = c(1,3,5,3,2)
p2 = c(1,2,3,5,3)
p3 = c(1,1,2,5,5)

Then the Likert scores are generated in R as shown:
set.seed(1234)  # for reproducibility
x1 = sample(1:5, 27, rep=T, prob=p1)
x2 = sample(1:5, 26, rep=T, prob=p2)
x3 = sample(1:5, 23, rep=T, prob=p3)
x = c(x1,x2,x3)
g = as.factor(c(rep(1,27),rep(2,26),rep(3,23)))

For an overview of these data, here are boxplots of the groups with red dots showing group means.
boxplot(x ~ g, col="skyblue2")
points(1:3, c(mean(x1), mean(x2), mean(x3)),
  pch=19, col="red")

A stripchart shows the individual Likert scores. (Points have been 'jittered', randomly displaced vertically, to avoid plotting them directly on top of each other.)
stripchart(x ~ g, pch=20, meth="jit", jit=.2)
points(c(mean(x1), mean(x2), mean(x3)), 1:3, col="red", pch="x")

Group sample means differ and group sample variances also differ somewhat.
mean(x1); mean(x2); mean(x3)
[1] 3.407407
[1] 3.692308
[1] 4.173913
var(x1); var(x2); var(x3)
[1] 0.7891738
[1] 1.181538
[1] 0.9683794

So, it seems that I have simulated 'Likert' data with some differences in means among the groups. The question now is
whether differences are large enough to rise significantly
above the random noise.
Welch ANOVA. The Welch ANOVA test, implemented in R by the procedure onesample.test does not require equal variances.
The null hypothesis is that group population means are equal
$H_0: \mu_1 = \mu_2 = \mu_3$ and the alternative is that they are not all equal. The null hypothesis is rejected at the 5% level because the P-value $0.023 < 0.05.$
oneway.test(x ~ g)

       One-way analysis of means
     (not assuming equal variances)

data:  x and g
F = 4.068, num df = 2.000, denom df = 47.559,
   p-value = 0.02339

It seems realistic to say that $\mu_1 < \mu_3,$ but one cannot say whether $\mu_2$ differs significantly from $\mu_1$ or from $\mu_3.$ Ad hoc Welch 2-sample t tests do not find significant differences:
t.test(x1,x2)$p.val;  t.test(x2,x3)$p.val
[1] 0.3023305
[1] 0.1102826

One issue remains: The Likert data are not normal, and it is
reasonable to wonder whether the 'F-statatistic' of the Welch
ANOVA truly has the assumed distribution--or close enough to
the assumed distribution in the tail where we compute P-values.
Permutation test. One way to answer this question is with a permutation test.
We randomly re-assign the scores of the 76 subjects in the three groups to see how that affects the F-statistic. (R code for the random scrambling is sample(g).) If we do this many times, we can get a good idea what the true distribution of the F-statistic under the null hypothesis is.
This is called a permutation test, using Welch's F as 'metric'. The result for our data is that the P-value of the permutation test is essentially identical to the P-value of Welch's F-test.
set.seed(2019)
m=10^5; d=numeric(m)
f.obs = oneway.test(x ~ g)$stat
f = replicate(m, oneway.test(x ~ sample(g))$stat)
mean(f > f.obs)
[1] 0.02404

Each random scrambling during the permutation test had a slightly different number of denominator degrees of freedom.
So the simulated F-distribution is a mixture of F-distributions.
Nevertheless, we notice that the simulated distribution of F is not far from the distribution $\mathsf{F}(2,48)$ of Welch's ANOVA.
hist(f, br=40, prob=T, col="skyblue2",
   main="Simulated Dist'n of F")
  curve(df(x, 2, 48), add=T, lwd=2, col="red")

Notes: (1) The Welch ANOVA has become popular relatively recently. So its behavior for nonnormal data is perhaps not fully understood. In my own experience, the Welch ANOVA has worked well for sample sizes around two dozen, even if data are discrete, and there are a few outliers. (2) As shown above, the permutation test is programmed in a way that is easy to write, and I hope to understand. However, this code runs slowly. I would not
run it again for every one of your Likert items. If you have doubts about the Welch ANOVA in a few specific cases, you might try permutation tests for the relevant data.


Formula for factorial?

Question: I need an equation that defines factorial without using factorial, that also works for $0$.
I have seen factorial defined like this:
$$n! = 1\cdot2\cdot3\cdot4\cdots n$$
But if we plug $0$ into that, we end up with $0$, which doesn't work.
So what would be the correct way to put it?
Comment: $0! = 1.\quad$ See [empty product](http://en.wikipedia.org/wiki/Empty_product)
Comment: When $n=0$, you have an empty product.  The empty product is defined to be the identity element, i.e., 1.  Alternately, you could use the Gamma function at natural values.  You could also use your formula for $n!$ except $n!=(n+1)!/(n+1)$ (although somewhat circular).
Answer: In your definition, if we plug $0$ into that we don't get $0$. Because your definition starts with $1$, so the case for $n = 0$ simply isn't defined. Usually it is defined $0! = 1$.
You can therefore define factorial like this:
$$n! = \begin{cases}1 & n = 0\\
1\cdot2\cdots n & n > 0
\end{cases}$$
Alternatively, if you don't like the above definition, you could use the Gamma function definition:
$$\Gamma(t) = \int_0^\infty x^{t - 1}e^{-x}\,\mathrm dx$$
and the put
$$n! = \Gamma(n + 1).$$
Note that the Gamma function is defined for real values, whereas the factorial only for natural numbers.
Comment: I indeed think a piece wise function is the best. Because 0!=1 is chosen by "choice". In fact, I still have a calculator with red leds that gives 0!=0 (With no error message) That is one of the reasons why I keep that old calculator. But then inflation took place and we made 0!=1. So +1 for rubik
Comment: 0!=42 is a big inflation though :)
Comment: @imranfat You are absolutely right. Actually I think I have to emphasize the fact that $0! = 1$ by definition. One could define $0! = 42$, but the previous definition is just more useful and has many applications.
Answer:
Let $A = \{a_1, \dots , a_n\}$ be a finite set of numbers. Then
$$\prod_{a\in A} a = a_1 a_2 \cdots a_n$$
and by convention $\Pi_{a\in \emptyset} = 1$, therefore you can define factorial as $$f(n) = \prod_{1 \leq k \leq n} k\text{.}$$
In this case, $f(0) = \prod_{k\in \emptyset}k = 1$.
Also, you can define factorial in the terms of gamma function:
$$f(n) =\int_{0}^{\infty} t^{n}e^{-t}dt\text{.}$$
The third option is a combinatorial definition. Define $n!$ as a number of bijections $$g:\{1, 2, \dots , n\}\to \{1, 2, \dots , n\}\text{.}$$
Again, $0!$ is somehow special, since you have to notice that there is exactly one empty function $g:\emptyset \to \emptyset$.
The last one, I can come up with is
$$f(n) = \frac{1}{c_n}\text{,}$$
where $c_n$ are uniquely determined coeffients of the Taylor's series of the exponential function: $$e^x = \sum_{n = 0}^{\infty}c_n x^n\text{.}$$
Answer: When thinking about combinations, we can derive a
formula for "the number of ways of choosing k things from a collection
of n things." The formula to count out such problems is  $n!/k!(n-k)!$.
For example, the number of handshakes that occur when everybody in a group of $5$ people shakes hands can be computed using $n = 5$ (five people) and $k = 2$ ($2$ people per handshake) in this formula. (So the answer is $5!/(2! 3!) = 10$).
Now suppose that there are $2$ people and "everybody shakes hands with everybody else."  Obviously there is only one handshake. But what happens if we put $n = 2$ ($2$ people) and $k = 2$ ($2$ people per handshake) in the formula? We get $2!/(2!0!)$.  This is $2/(2x)$, where $x$ is the value of $0!$. The fraction reduces to $1/x$, which must equal $1$ since there is only $1$ handshake. The only value of $0!$ that makes sense here is $0! = 1$.
And so we define $0! = 1$.
more here
Answer: If you just want it to work with 0, use
$$
0!=1\\
(n+1)!=(n+1)\cdot n!
$$
The other options have been covered in other answers.

Formula for factorial?


Why isn't there a key signature with F flat?

Question: I think the title asks the question. There are key signatures with Ab, Bb, Cb, Db, Eb and Gb. But no Fb.
There's probably no practical reason for my question. I'm just curious.
Comment: Cb major has Fb, in case Niel's answer isn't totally clear about that. C# major has B# and E#, in case that's the next logical question. :-)
Comment: There IS. Just rare. Rare, but still exists.
Answer: Technically, there could be, you just keep extending the pattern. You could even keep extending it to the point where you need to start using double flats, though this is almost never done in practice.

The key of F contains: B♭
The key of B♭ contains: B♭, E♭
The key of E♭ contains: B♭, E♭, A♭
The key of A♭ contains: B♭, E♭, A♭, D♭
The key of D♭ contains: B♭, E♭, A♭, D♭, G♭
The key of G♭ contains: B♭, E♭, A♭, D♭, G♭, C♭
The key of C♭ contains: B♭, E♭, A♭, D♭, G♭, C♭, F♭
The key of F♭ contains: B♭♭, E♭, A♭, D♭, G♭, C♭, F♭

Though it is rare, wikipedia (linked above) points out that the key of C♭ has been used, and, in fact, is the most resonant key for the harp. The main reason that this key isn't used frequently is because it is enharmonically equivalent to the key of B, which only has 5 sharps instead of 7 flats, and is therefore easier for many instruments to play. Notice how each pair of notes from the following two scales are different names for the same pitch:

C♭,D♭, E♭, F♭,G♭, A♭, B♭, C♭
B, C♯, D♯, E, F♯, G♯, A♯, B
Comment: You generally wouldn't. One possible case where it might come up is modulations. Say you were playing in Db major, and you wanted to modulate to the parallel minor key. It might be clearer to keep the tonic the same, and write it as Db minor (which has the same signature as Fb) rather than suddenly transpose everything to the distant key of C# minor.
Comment: For transposing instruments in a "flat" keys (e.g., most brass and saxes), music written in flat keys is easier to read than sharp keys. The transposition reduces the number of flats but increases the number of sharps. For an alto sax (in E flat), a piece in C flat major would have only 7-3 = 4 flats, but a piece in B major would have 5+3 = 8 sharps (notionally in G sharp major with F double sharp in the key signature, though it would never be written that way). To fix this you have to pretend the alto sax is in D sharp not E flat, but that can also cause problems reading a full score.
Comment: I would just like to add that in my experience, A flat minor (parallel of C flat major) is quite common in the classical literature. Apart from that, +1; well put & complete answer.
Comment: Fb -Gb-Ab-Bbb-Cb-Db-Eb-Fb is the same as E-F#-G#-A-B-C#-D#. So I was right that E - Fb would be a series of notes that are all enharmonic of each other. So again why would you do this?
Answer: To expand, enharmonic equivalence is an invention of convenience. Musical intervals are just frequency ratios, and ratios with smaller numbers sound more consonant. For example, the octave is 2:1, and the perfect fifth is 3:2, the two simplest.
Compounding ratios by stacking intervals serves to create more notes. However, since no nonzero power of 3/2 can ever equal a power of 2 (prime factorization), that means you can always create new notes by adding on fifths and correcting the octave - the number of pitch classes is infinite.
To have something usable requires one of two things: restricting usage to some level of sharps and flats, or deliberately tuning the fifth wrong so that the cycle of fifths closes. Thus the art of temperament, or tuning theory.

results in Pythagorean tuning, where the keyboard would have (say) Eb, but D# literally does not exist. You cannot play the fifth G#-D#, and attempting to use G#-Eb, a diminished sixth, sounds horrible (also known as a wolf fifth, representing 192:125 or worse).
results in equal temperament (or 12EDO, equal divisions of the octave), where each fifth is slightly out of tune by about 1/50 of a semitone. In exchange, there are only 12 equivalent notes in an octave, and most intervals are tolerable. Combinations are possible, leading to meantone and other temperaments.

Twelve fifths is very close to seven octaves (hence 12EDO), off by the difference between B# and C, a tiny ratio known as the Pythagorean comma - which is discarded in Western music theory. Thus the origin of enharmonic equivalence: B# is represented by the same pitch as C, because we can't be bothered to care about the difference, not because they are musically equal.
In short, when modulating in tonal harmony, using equivalence is absolutely improper and summarily barred, whatever the savings in notation. To wit, modulating from Db major to Db minor would be I->i, but to go to C# minor is from I->bbii, a transition that nobody uses.
A quick example I can think of is Bach's Fugue in C# major, BWV842/2 (WTC I). For whatever reason he chose to use 7 sharps instead of Db, and so in bar 19 he writes a full scale in iii melodic: E#-Fx-G#-A#-B#-Cx-Dx-B#-E#. Yes, the imitable key of E# minor.
That said, since equivalence is used, there isn't too much point in starting a piece with more than 7 sharps or flats. Modulation extends the range up to about 10 sharps or flats, but that's basically the limit.
Comment: This is useful information, but I'm having a hard time seeing how it answers the question. Could you please add an introduction or summary that ties this all together and more obviously provides an answer?
Comment: "For whatever reason he chose to use 7 sharps..." _because he could_. That's really the reason, since [WTC](https://en.wikipedia.org/wiki/The_Well-Tempered_Clavier) was most of all a proof-of-concept work. — I agree that this answer could use some more connection to the question, though there's really good points in there.


How to comment on image in colorbox (modal form)?

Question: I have created view to display images and also user to display it in popup using Colorbox trigger in view.
I want to allow users to comment on each individual image in modal form only. Just like Facebook. I have printed the comment form on popup but it is coming with preview button which redirects user to the photo's node page. And allow there to POST comment which I don't want.
What I want is user should be able to comment in popup with post button and the comment should be posted in modal form only (Should be visible in modal and node page as well). Is there any module to workout this?
Answer: Inline Ajax Comments should do the trick for you.

Inline Ajax Comments is a views handler that allows you to add a field
  to a view to allow users to view and post comments on nodes in a view.
  This is a basic version of what you see with commenting in social
  networking sites like Facebook.

Ajax Comments comments can also be considered.
Comment: Ajax Comments module is not working with me, When I include Ajax Add Comment Link to Colorbox trigger the link doesn't get appear in modal.
Comment: Is there anybody who knows the solutions?


Summary/Trimmed field in view doesn't include Read More link

Question: I have a view, and the key display points are:

Format: Unformatted List (I'm adjusting the views look through CSS)
Show: Fields

One of the fields to show is Body (so, a textarea.) When I choose to display it as "Summary or Trimmed", and set the trim length to, say, 600, it trims it fine, but it doesn't show a "Read More" link to the content's page. Is there something I'm missing?
Comment: This may helps you http://drupal.stackexchange.com/questions/44791/how-to-set-the-read-more-link-in-rewrite-rules-for-body-field-to-point-to-th
Answer: did you check " Add a read-more link if output is trimmed. "?
If yes, maybe the problem is, that the text is not trimmed. If you want to have a "read more" link in any case, then you sould add the field "Link" to the view. You can then also enter your custom text, e.g. "details..." instead of "read more" etc.
Comment: The problem is I'm not seeing that option; I've got "create a lable", "exclude from display" and "Formatter". If I choose "Trimmed" or "Summary or Trimmed" from "Formatter", the "Trim Length" field appears... but that's my only new option.
Comment: Nevermind. Found it. It wasn't where I was expecting. It was under "Rewrite Results". Thank you!


Drupal Commerce Total Order Weight

Question: I am writing a custom module to add surcharge values to a commerce order at the time of UPS shipping calculations. I am trying to find a way to access the total weight of the order.
I thought I would be able to access the weight from the array returned by:
entity_metadata_wrapper('commerce_order', $order);
Unfortunately it's not present in the data that I can see.
Does anyone know how I can access the total weight of an order or are these generated dynamically when the UPS shipping process is called?
Answer: I believe it is generated when it's needed, and not stored. But, after looking at the Commerce Order Weight Token module, you can get the weight using the following:
$weight = commerce_physical_order_weight($order);

Comment: [`commerce_physical_order_weight`](http://www.drupalcontrib.org/api/drupal/contributions!commerce_physical!commerce_physical.module/function/commerce_physical_order_weight/7) is a function provided by the [Commerce Phsycial Products](https://www.drupal.org/project/commerce_physical) module. As long as you have that module installed and are using it to configure weights for your products, the function will be available. The Commerce Order Weight Token module is not needed for this function.
Comment: I have not checked the mentioned module commerce order weight token but does this $weight = commerce_physical_order_weight($order);
 require the module or we can use it without the module?
Answer: Drupal Commerce itself doesn't require products to have weights, so there is no way for it to know what an order's total weight might be. However, the Commerce Physical Product module does at this support. I'm actually using that module for a project now and will be ensuring it has complete Rules support for the various API functions that determine whether or not an order / a particular line item is shippable and how much an order / a particular line item weighs.

Drupal Commerce Total Order Weight


Activecampaign - Adding checkbox values via API

Question: I am trying to submit multiple values into an AC field using the contact_sync PHP API.
The field has been set as a checkbox field and I can select multiple items in AC itself but I am not sure how to submit multiple items via the API.
<code>'field[17]'                => 'Option 1, Option 2',
</code>
I thought this would work as it does work for multiple lists. Does it need to be an array of sometype?
Answer: You can submit multiple values to a single checkbox field via the API with double pipes (||), like this:
field[76,0]=option1||option2||option3


Too much string on the tuning peg?

Question: I just finished changing the strings for my classical guitar. This is the first time so it wasn't absolutely smooth.
Now, tuning my E string (the highest) I noticed that it gets quite tense and all. I guess that it's normal however because of how I wound the strings, my E string on the tuning peg gets all stacked up on one side:

See that and whenever I need to tight the string up, it kinda makes a sound that makes me think it wouldn't be able to wind up anymore!
My question is what should I do? Do I let it stay like this and tighten the string up whenever it's needed? Or should I remove the string and wind it up all over again? In that case would it affect the quality of the string and the sound?
Comment: Also, you might be interested in this thread: [Beginner replacing guitar strings](http://music.stackexchange.com/questions/12616/beginner-replacing-guitar-strings/12618)
Answer: I would do it over again, and have about half as many loops on the peg as you have now. See this guide for some more hints.
Comment: Yes, cut off a few inches that are spare at the end, after you've pulled some of the string through the hole in the post.Or leave it flapping around...
Comment: It wouldnt change the quality right? And how do we do it with less loops? It still has the be tense enough. Do i cut off half of the strings?
Answer: It looks like the string is butting up against the headstock itself, so if you wind the string up more it'll be fouling on the wood which won't help with tone etc and in the end will make a rut in the wood where the string is fouling.
That's not "major damage" but it's undesirable, and the wood fouling on the string will affect the tone even if only a little bit.
I would unwind it so that you can move the string through the hole oin the peg, pull it tight and then start winding again to hopfully take up more slack.
The alternative would be to pull the string through the hole, and pull it towards the middle of the headstock and see if it'll 'want to' wind over the peg, over the hole and not as far up the peg at the other end
Comment: I only know this through experience, not through thorough understanding, but it seems if the string (even outside the nut/bridge) is resting on something even remotely flexible, then as the string tenses and relaxes during vibration, some of the tension whcih wants to pull it straight is spent moving the wood about, albeit a very small abount. Admittedly my experience of this was with an electric guitar where maybe things are more sensitive to such stuff.
Comment: How will it affect the tone? The string isn't vibrating once it's over the nut.
Comment: Actually, taking another look, maybe in this case it won't reeally affect the tone so much here as the point it's pushed against the wood is right near the peg anyway

Too much string on the tuning peg?


Setting up Exchange Server 2010 on Windows Server 2012 (Azure)

Question: What roles and features do I need to setup Exchange Server 2010 (Trial) on a Windows Server 2012 Azure instance? I've bought a domain name from Go-Daddy and I'd like it all up so I can have email@example.com email addresses.
Answer: Exchange 2010 is not yet supported on Server 2012 (per the Exchange Team). They recently announced that Exchange 2010 SP3 will support installation on Server 2012, but that update is not due out until the first half of 2013.
If you just want email branded with your domain name, you could use Office 365 or any number of hosting services (google apps.. etc..).
If you want to install Exchange 2010 now, you'll need a Server 2008 R2 image.
On that server (if you are going to run the Client Access, Hub Transport, and Mailbox roles on the same box), you'll need the following roles (PowerShell script provided for ease of use).
<code>import-module ServerManager
Add-WindowsFeature NET-Framework,RSAT-ADDS,Web-Server,Web-Basic-Auth,Web-Windows-Auth,Web-Metabase,Web-Net-Ext,Web-Lgcy-Mgmt-Console,WAS-Process-Model,RSAT-Web-Server,Web-ISAPI-Ext,Web-Digest-Auth,Web-Dyn-Compression,NET-HTTP-Activation,RPC-Over-HTTP-Proxy -Restart
</code>
After that other prerequisites can be found in this Technet article.


Modify apache solr search sort options?

Question: Is there the ability through contrib module or hooks to modify how the apache solr sort block sorts queries?
Currently, it seems it supports these queries out of the box:

Relevancy
Title
Author
Date

What i would like to have is to remove Author, Add a field to sort title from a-z and z-a. Is that possible?
Answer: You can find all info with examples here: http://drupal.org/node/715276
<code><?php
function MYMODULE_apachesolr_query_prepare(DrupalSolrQueryInterface &$query, &$caller) {
  $query->addParam('fl', 'some_field_image');
  $query->addParam('fl', 'some_field_date');
  //Remove sorts
  $query->remove_available_sort('sort_label');
  $query->remove_available_sort('bundle');
  $query->remove_available_sort('sort_name');
  //Rename sorts
  $query->remove_available_sort('score');
  $query->set_available_sort('score', array('title' => t('Relevance'), 'default' => 'desc'));
  $query->remove_available_sort('ds_created');
  $query->set_available_sort('ds_created', array('title' => t('Latest'), 'default' => 'desc'));
 }
?>
</code>
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. Link-only answers are not considered proper answers on Stack Exchange websites
Answer: There is a module Apachesolr Sort that provides an UI to configure apachesolr sort block. From module page:

Removal of a sort by field
Weights for the sort by fields
Neat integration with the apachesolr modules.
Adds a block that gives you a select block to sort your results on.

Modify apache solr search sort options?


Obtaining Full Text of ISO27002

Question: You would think this information would be easier to come across but I can't really find it. How do somehow obtain the text of ISO27002? I've tried to find it online in various places (including the IEC webstore) but can't find so much as a "contact sales" message. If it's free, great, if it costs, is there a place where I can get the price?
Comment: http://17799.cryptovb.com/ and http://www.27000.org/standards.htm
Comment: Yeah I found both links in my searching, both are unofficial sources and the first one is only selling the "toolkit" versus just the standards document and the second one just looks shady as hell.
Comment: Not sure why this was closed. I'm assuming it's because of "Product, service, or learning material recommendations" in which case I'd like the people who voted to close to actually read the FAQ and see that prohibition is on a "which is better x or y" subjective slug match. This question pertains to an international standard used for constructing IT baselines which falls under the "operations" category in the FAQ. Just because it's not a technical question doesn't mean it's not appropriate to place it here.
Answer: The text can be downloaded here from the ISO website.
EDITED by The Cleaner:  The U.S. version can be found here on the ANSI Site: ISO 27000
Comment: Thanks, I probably should have mentioned that I'm in the United States. The linked page only sells in Swiss Francs (of which I have none) but looking at the page again I did find my answer: the ANSI website is the official source for ISO standards in the United States. Since I found the answer by way of the link I'm marking this as the answer.
Comment: For future reference I've updated the answer

Obtaining Full Text of ISO27002


ajax response does not use currently loaded resources (php + jquery)

Question: I'm using some css files and js libraries (bootstrap, packry, etc.) in my master page. There's a button on page that when you click on it, it sends an ajax request and prints the response on a div in current page:
<code>jQuery.post("index.php", "some_post_data", function (data)
{
 jQuery('#mydiv').html(data);
});
</code>
The page I'm calling needs those libraries I've already included on my master page, but when I print the response inside the div, it still shows js errors and style-less objects. If I add those resources to the second page, it will work but I don't want to do this.
Do I have to do some kind of refreshing thing on the newly printed html codes, or something like that? What am I doing wrong in here?
Comment: need more info, please show what's returned by the ajax request
Comment: Is you AJAX posting to your main index.php page? As I think this will return the HTML of the main page. Seeing your index.php file will be helpful
Answer: When you add html content to a page dynamically like you are doing. Any script files loaded in the header section (or anywhere else for that matter) will not be loaded and registered in your dom. I presume the same will apply to any style sheets you include on the dynamic page.
To add any script files or stylesheets you need to register them separately into the head section of your document.
You could load the js/css files into your head like so:
<code> var jsLink = $("<script type='text/javascript' src='"+src+"'>");
     $("head").append(jsLink);
</code>
or check out this link:
Ways to add javascript files dynamically in a page


Show that the sequence defined as $x_{n+1}=\sqrt[3]{x_n+x_{n-1}}$ converges

Question: Show that the sequence $(x_n)$ defined as $x_{n+1}=\sqrt[3]{x_n+x_{n-1}}, x_0=3,x_1=2$ converges. Here i wil try to prove that $(x_n)$ converges considering all details. So. i would like to have a critical feedback on my proof and would like to know if i missed something or did much more than it should be.. Here $\mathbf{R}^*$ will denote $\mathbf{R}\ \ \not \ \{0\}$.
Consider a function $f(x)=\sqrt[3]{x}$. First, we show that it's defined on $\mathbf{R}$ and then we will show that $f(x)$ is an increasing function on $\mathbf{R}$.
We remark that $f(x)$ is differntiable on $\mathbf{R}^*$. Let $a \in \mathbf{R}^*$. By definition of differentiable function the $\lim_{x\to a}\frac{f(x)-f(a)}{x-a}$ msut exist:
$\lim_{x\to a}\frac{f(x)-f(a)}{x-a}=\frac{1}{3\sqrt[3]{a^2}}$ and so it exists $\forall a \in \mathbf{R}^*$ as we chose an arbitrary $a$. So $f(x)$ is differentiable on $\mathbf{R}^*$ and so is continious on $\mathbf{R}^*$.
We show now that $f(x)$ is continious on $0$. To show that we pass by the definition :
$\forall \varepsilon>0 \ \exists \delta>0 \ \forall x \in \mathbf{R}$: $|x|<\delta \implies |f(x)|=|\sqrt[3]{x}|<\varepsilon$
To satisfy the definition, one can take $\delta=\varepsilon^3$, so it holds and we can conclude that $f(x)$ is continious on $\mathbf{R}$.
Let $a,b \in \mathbf{R}$ such that $a<b$. As $f(x)$ is continious on $\mathbf{R}$ we can write:
$a<b \iff \sqrt[3]{a}<\sqrt[3]{b} \iff f(a)<f(b)$
As $a,b$ are arbitrary numbers (satisfying $a<b$), we can conclude that $f(x)$ is strictly incrasing function.
Now, as all preliminary results are proven, we can show that $(x_n)$ is a convergent sequence. For that, we show that $(x_n)$ is monotonic and bounded.
$\bullet$ $(x_n)$ is decreasing: Suppose $x_{n+1}<x_n$. The previous inequality holds for $n=1$ so we can suppose that it works up to a certain $n\in \mathbf{N}^*$. We show nowthat it holds for $n+1$:
$x_{n+2}<x_{n+1} \iff \sqrt[3]{x_{n+1}+x_n}<\sqrt[3]{x_n+x_{n-1}}$. But, as $f(x)=\sqrt[3]{x}$ is strictly increasing function and by induction hypothesis $x_{n+1}<x_n$, we can conclude that $x_{n+2}<x_{n+1}$ and so $x_{n+1}<x_n$ holds $\forall n\in\mathbf{N}^*$. So $(x_n)$ is decreasing.
$\bullet$ $(x_n)$ is bounded below: Suppose $x_n>1$. It holds for $n=1$ so we can suppose that it works up to a certain $n\in \mathbf{N}^*$. We want to show now that t holds for $n+1$:
$x_{n+1}>1 \iff \underbrace{x_{n}}_{>1}+\underbrace{x_{n-1}}_{>1}>1$ which is true, because $(x_n)$ is decreasing. So we conclude that $x_n>1 \ \forall n\in \mathbf{N}^*$.
So, we have shown that $(x_n)$ converges.
Comment: Assuming that it is established that the sequence is strictly decreasing and (therefore) converges to some non-negative value $L$, one approach is to recognize that the $\lim_{n\to\infty} x_n = L = \lim_{n\to\infty} \left(x_{(n-1)} + x_n\right)^{(1/3)}.$  Another approach is to **guess** the value of $L$, show that $\forall n, x_n > L$, and further show that the assumption that the limit equals some other value $L_1 > L$ leads to a contradiction.
Comment: My bad, I didn't actually scrutinize your analysis.  If you have analysis that demonstrates that there is a finite set $S$ such that $L$ must be an element of $S$, then yes, one way of *completing the problem* is to prove that there is only 1 value (i.e. element) in the set $S$ that will work.
Comment: I just have a question: i also could have shown that $(x_n)$ is bounded below by 0. But, if i calculate the limit (solving an equation), i have 3 different values: $L=0,L=\sqrt{2}$. We can drop the solution $"-"\sqrt{2}$ but how can i be sure that it is $"+"\sqrt{2}$ and not 0 in my case? It is kinda immediat if i calculate first 5-6 values of the sequence, but still i would like to know how to be sure for 100% and have a rigorous proof.
Comment: The query's title indicates that it is sufficient to determine that the sequence is convergent - calculating the actual limit of the sequence is therefore irrelevant.  Consequently, all that is required is that [1] the sequence is strictly decreasing and [2] there exists **some** lower bound for the sequence (regardless of what that lower bound is).  From this perspective, a lower bound of $0$ works fine.
Comment: @user2661923 Yes, it wasn't asked to calculate a limit but still by curioisty why couldn't I ask this question...
Comment: Totally separate question.  This (separate) question is certainly closely related enough to the original question to *include* this question in the **same** query, as long as it is understood that since it is a different question, it (plausibly) **requires different analysis**.  Assuming that (for example) you wanted to add an addendum to your query to explore the *related* question, there are some *distinct* methods of attack. ...see next comment
Comment: @user2661923 Could we proceed by absurd as well? For example taking $n=1$ and $\varepsilon=1/2$ would show that $L=0$ is impossible (using a negation of a definition of the sequence limit). (I think it's what you proposed...)
Comment: Wrong approach - assuming that you are trying to calculate the exact value of the limit $L$.  It is not a good idea to identify isolated values, such as $0$, and show that $L$ can not equal $0$.  Instead, you have to identify a specific candidate value $C$, and demonstrate that $L$ must equal $C$.  The only two approaches that I know of (there may be others) are as I described in my previous note.
Comment: @user2661923 Yes, but i already calculated all "possible" values so why it would be wrong to proceed by exclusion and then conclude that the only possible value is $"+"\sqrt{2}$ (as i showed that $(x_n)$ must converge)
Comment: So can someone give a feedback on the proof, please?
Answer: $$x_{n+1}=\sqrt[3]{x_{n}+x_{n-1}};\;x_0=3;\;x_1=2$$
$(x_n)$ is a decreasing sequence
Proof. (by strong induction)
for $n=1$
$x_2=\sqrt[3]{x_0+x_1}=\sqrt[3]{5}<x_1$
Now suppose that it is true for all integers $1,2,\ldots, n$,  and let's prove it for $(n+1)$
$$x_{n+2}=\sqrt[3]{x_{n+1}+x_{n}}$$
$$x_{n+2}^3=x_{n+1}+x_n<x_n+x_{n-1}=x_{n+1}^3$$
thus $x_{n+2}<x_{n+1}$. Proved.
The sequence is decreasing and is bounded above by $x_n\le 3$
$x_n>1$ for any $n$.
$x_1=2>1$. Suppose $x_n>1$ for $0,1,2,\ldots,n$.
$x_{n+1}=\sqrt{x_n+x_{n+1}}>\sqrt[3]{1+1}>1$. Proved.
Thus the sequence is bounded above and below $1<x_n<3$,  therefore it converges
$x_n\to x$ as $n\to\infty$
To find the limit let's use the definition
$$x=\sqrt[3]{x+x}\to x^3=2x\to x=\sqrt 2$$
The sequence converges to $\sqrt 2$.
Comment: @DeepSea You are right!
Comment: @archuser The fact that $f(x)=\sqrt[3]{x}$ is strictly increasing is common knowledge. The feedback on your proof is implicit in my answer's length: 8 lines vs 33.
Comment: @archuser Your proof is verbose. You prove that $\sqrt[3]{x}$ is continuous, that $x^3$ is increasing. You even compute the derivative from the definition! The inferior bound is trivially zero... as user2661923 commented three hours ago. My feeling is that you confused rigorous with pedantic
Comment: @archuser were you looking for feedback or for unconditionally praise?
Comment: @Raffaele: Your $x$ could be $0$ why not ?. You still have to "show" that $x > 0$. !
Comment: Thank you for an answer, but my question was to give a feedback on the proof that I wrote here. And how can you conclude that $x_n$ is decreasing without involving $f(x)=\sqrt[3]{x}$
Comment: yes, it is a common knowledge. But, as I study I prepare myself to make complete proofs including all the details as I can't assume something as "known" without proving it.. so that is why I wanted to have a complete feedback on my proof not only convergence.
Comment: Yes, but to show that $\sqrt[3]{x}$ is increasing on $\mathbf{R}$ you have to show that it is defined on this domain... and that was my method to show that.
Answer: You asked for feedback on your proof, here are some thoughts:

To prove $f$ is continuous, you say that it's differentiable. But you do not prove that $f$ is differentiable directly - you only state the derivative. You could show that the derivative exists with this value, but that proof would be very similar to proving $f$ is continuous directly (e.g. using the binomial theorem). So it would be simpler to just do that.

To prove $f$ is increasing, you just say "$f$ is continuous, therefore [$f$ is increasing]". There is no proof in your question that $f(x) = \sqrt[3]{x}$ is an increasing function.

Your proofs that $(x_{n})$ is decreasing and bounded below by 1 appear to be correct. Note that they only rely on the fact that $f$ is increasing and that $f(1) = 1$. You haven't used the fact that $f$ is continuous anywhere.

However, the property that $f$ is continuous does allow you to find the limit. In general, if $x_n \to x$ and $f$ is continuous, then $f(x_n) \to f(x)$. Applying this to the equation $x_{n+1} = f(x_n+x_{n-1})$ shows that the limit satisfies $x = f(2x)$. In other words, $x^3 = 2x$, so either $x=0$, $x=-\sqrt{2}$ or $x=\sqrt{2}$. But since you argued already that $x > 1$, the limit must be $\sqrt{2}$.
Comment: Thank you very much! That is the answer that I was waiting for!
Answer: After showing that the limit exists and call it $x$. We show next that: $x \ge \sqrt{2}$. Using the decreasing property just established we have: $x_n = \sqrt[3]{x_{n-1} + x_{n-2}} > \sqrt[3]{2x_n} \implies x_n^3 > 2x_n \implies x_n(x_n^ 2 - 2) > 0 \implies x_n > \sqrt{2}, \forall n \ge 1 \implies x \ge \sqrt{2} \implies x = \sqrt{2}$, because it's shown that $x = 0$ or $x = \sqrt{2}$.


How to translate the menu title?

Question: Currently I am working on a multilingual website and have already a multilingual set-up.
Now I have translated menu items and it is working great, however I also want the menu title to be translated.
This is how I get the menu titles:
$menuInfo = menu_load('menu-second-menu');

and I get the title through by $menuInfo['title'];
I print the links with the following code (and the title is displayed above):
print theme('links__system_main_menu', array('links' => $menu, 'attributes' => array('id' => $menuInfo['menu_name'], 'class' => array('links', 'clearfix')), 'heading' => array('text' => $menuInfo['title'], 'level' => 'h3')));

So the links are translated, but the $menuInfo['title'] not and $menuInfo does not contain any translated information.
Any help?
Edit: The issue is I do not know how to get the translated menu title (programmatically) I made in Structure -> Menus -> Second Menu -> click the tab Translate and gave a different Menu title for the different languages. I am using the Menu Translation (sub)module of the i18n Internationalization module.
Answer: The only solution I could come up with, to translate the menu title is by using the following:
$menu = menu_load('main-menu');
$menu_title = i18n_string_translate('menu:menu:main-menu:title', $menu['title']);
$menu_desc = i18n_string_translate('menu:menu:main-menu:description', $menu['description']);

Answer: Enable locale and Translation module, goto admin/config/regional/translate/translate select the language and enter the corresponding English statement, then translate it.
Comment: These modules are already enabled. The point is I do not know how to get the translated menu title I made in Structure -> Menus -> Second Menu, than click the tab Translate and gave a different Menu title for the different languages.
Comment: did you search the original phrase?
Comment: I have searched yes, I found another thread discussing how to get the menu title using the menu_load('menu-name'); function, but apparently the Internationalization module doesn't hook into this one.

How to translate the menu title?


Convergence of the size of largest component in subcritical Erdos Renyi graph

Question: Considering an Erdos Renyi random graph with $p = \frac{\lambda}{n}$ and $\lambda < 1$, I am trying to show that $ \frac{|C_{max}|}{log (n)} $ approaches  $ \frac{1}{I_{\lambda}} $ in probability, where $|C_{max}|$ is the size of the largest component and $I_\lambda = \lambda -1 - log(\lambda)$.
So I should show that:
$$ \lim_{n \to \infty} P(|\frac{|C_{max}|}{log (n)} - \frac{1}{I_{\lambda}}| > \epsilon) = 0 $$
I think I should use the upper and lower bounds on the largest subcritical component, i.e. $P(|C_{max}|\ge a log(n)) = O(n^{-\delta})$ if $ a > \frac{1}{I_\lambda} $ and $P(|C_{max}|\le a log(n)) = O(n^{-\delta})$ if $ a < \frac{1}{I_\lambda} $, which means that $|C_{max}| \approx \frac{1}{I_\lambda}log(n)$. Then rewriting the equation above:
$$ \lim_{n \to \infty} P(||C_{max}| - \frac{1}{I_{\lambda}} log (n)| > \epsilon log (n)) = 0 $$
Then I should be able to use Chebyshev's inequality, but I'm not sure if this approach is valid until now and I don't know what the variance of $|C_{max}|$ is.
Answer: So you're not interested in proving those upper and lower bounds, just in using them to prove convergence in probability?
For that, you don't need any extra knowledge of the random graph. For any $\epsilon>0$, the first bound says that we have
$$
 \Pr[|C_{\max} > (\tfrac1{I_\lambda} + \epsilon)\log n] = O(n^{-\delta})
$$
(presumably for some $\delta>0$ depending on $\epsilon$) which we can rewrite as
$$
 \Pr\left[\frac{C_{\max}}{\log n} - \frac1{I_\lambda} > \epsilon\right] = O(n^{-\delta})
$$
and this goes to $0$ in the limit as $n \to \infty$. Similarly, the second bound tells us that
$$
   \Pr[|C_{\max}| < (\tfrac1{I_\lambda} - \epsilon)\log n] = O(n^{-\delta})
$$
and this can be rewritten as
$$
 \Pr\left[\frac{C_{\max}}{\log n} - \frac1{I_\lambda} < -\epsilon\right] = O(n^{-\delta})
$$
which also goes to $0$ in the limit as $n \to \infty$. Finally, the probability you were looking for,
$$
 \Pr\left[\left|\frac{C_{\max}}{\log n} -\frac1{I_\lambda}\right| > \epsilon\right],
$$
is the sum of the two probabilities above, so its limit is also $0$.


Total variation of a complex measure is a positive measure (Rudin proof)

Question:
Hi everybody
Im trying to prove this theorem from rudin.
I have two difficulies

what gives us to right to put $\sum_{i}t_i$ in $(\star)$, this is a sum of real numbers maybe it doesnt exist?
In $(\star\star)$ i think he did
$$sup\{\sum_{i}t_i~~,~~(t_i)_{i}\text{ sequences in }\mathbb{R}\text{ such that }t_i<|\mu|(E_i)\}=\sum_i |\mu|(E_i)$$
but how to prove this .
Answer: Additionally we can require $-\left(\frac{1}{2}\right)^i \leq t_i < |\mu|(E_i)$
This additional restriction makes $$\sum_{i=1}^\infty \max(0,-t_i) \leq \sum_{i=1}^\infty \left(\frac{1}{2}\right)^i = 1 < \infty,$$ so that $\sum_i t_i$ exists [as an extended real number].

Immediately from $t_i < |\mu|(E_i)$ we have $\sum_i t_i < \sum_i |\mu|(E_i)$ and therefore, since the right-hand side is independent of $(t_i)$, we have $$\sup_{(t_i)} \sum_i t_i \leq \sum_i |\mu|(E_i)$$
To show equality, let $t_i = |\mu|(E_i) - \epsilon\left(\frac{1}{2}\right)^i$ for $0 < \epsilon < 1$ to see $$\sum_i t_i = \sum_i |\mu|(E_i) - \epsilon$$ so $$\sup_{(t_i)}\sum_i t_i \geq \sum_i |\mu|(E_i) - \epsilon.$$ Now, let $\epsilon \to 0^+$.
Comment: thank youuu sir


Approximation of integral of $\frac{e^{-\frac{x^2}{2t}}}{t}$

Question: I saw the following approximation in the book Conformally Invariant Processes in the Plane by Lawler (Chapter 2, page 54), and I am not sure how to obtain this result.

Let $x > 0$ and $x \to 0$. Show that $$\int_0^1 \frac{e^{-\frac{x^2}{2t}}}{t} \,{\rm d}t = -2 \log{x} + O(1)$$

I tried Taylor expanding the integrand but to no avail, and I have no insight as to why this result is true.
Comment: @banana this is the first equation in the proof of Proposition 2.34, I just changed up the notation a bit for simplification. Maybe you have an older version of the book that doesn't include Chapter 0 so the page numbers are different?
Comment: So the "=" in the above equation should be replaced with "$\approx$"?
Comment: I don't find it on page 54 of the book. Which section? You may be talking about the proof of Proposition 2.30.
Comment: @tia: thanks, indeed. I think I am looking at an old version
Answer: Too long for a comment
Making the substitution $s=\frac{1}{t}$
$$I(x)=\int_0^1 \frac{e^{-\frac{x^2}{2t}}}{t} \,{\rm d}t=\int_1^\infty\frac{e^{-\frac{x^2}{2}s}}{s}ds=\int_{\frac{x^2}{2}}^\infty \frac{e^{-t}}{t}dt$$
Integrating by part
$$=\ln t\,e^{-t}\Big|_{\frac{x^2}{2}}^\infty+\int_{\frac{x^2}{2}}^\infty e^{-t}\ln t\,dt=-\ln\frac{x^2}{2}e^{-\frac{x^2}{2}}+\int_{0}^\infty e^{-t}\ln t\,dt-\int_{0}^\frac{x^2}{2} e^{-t}\ln t\,dt$$
The third term can be evaluated
$$\Big|\int_{0}^\frac{x^2}{2} e^{-t}\ln t\,dt\Big|<\Big|\int_{0}^\frac{x^2}{2} \ln t\,dt\Big|=\Big|\frac{x^2}{2}\ln\frac{x^2}{2}-\frac{x^2}{2}\Big|$$
Given that $\int_{0}^\infty e^{-t}\ln t\,dt=-\gamma$ and $e^{-\frac{x^2}{2}}=1-\frac{x^2}{2}+O(x^4)$
$$I(x)=-2\ln x+\ln2-\gamma+O(x^2\ln x)$$
Comment: @banana $\ln t\,e^{-t}\Big|_{\frac{x^2}{2}}^\infty=\ln t\,e^{-t}|_{t=\infty}-\ln t\,e^{-t}|_{t=\frac{x^2}{2}}$. Yes, there is a typo - just correcting. Thank you.
Comment: +1. You are welcome :-)


Why is Eigenvalue different from Variance.percent?

Question: I am conducting PCA analysis on results from a Likert-scale (10-point base) survey on user preferences. When using the code below, I obtain the list of variables with their respective eigenvalues. However these eigenvalues are different from the adjacent column which shows variance.percent (in the reference guide, it's one-tenth of the eigenvalue.
Could anyone explain why this might be or if there is anything off with my approach?
res.pca <- PCA(mydata, graph = FALSE)
print(res.pca)
library("factoextra")
eig.val <- get_eigenvalue(res.pca)
eig.val

Comment: I think it might have to do with the set number of variables. The model seems to be cut at then variables but I have thirteen.
Answer: Everything is OK. Sum of eigenvalues is always equal to number of variables (10 on the left and 13 on the right). So variance.percent is always eigenvalue divided by number of variables.
Comment: Thank you very much.


Can not get Virtualizor IP pool working with /27 subnet

Question: I've been scratching my head a few days at this now and I am by no means a networking expert but I know (most) of the basics.
I've got Virtualizor setup on CentOS 7 and I'm trying to add a new /27 (216.x.x.0/27) I got from my hosting company. My servers main IP is the first available IP in the subnet (216.x.x.2), the rest of the IPs should go to any VPS that gets spun up.
So far the furthest I've gotten with this is: I can ping vps ip inside server but not outside. SSH is not available at all in server or outside.
When configuring IP Pool in Virtualizor I have the NAT option checked. This creates a libvirt network (mine is called natbr3). It starts fine, sometimes I have to start service firewalld before hand. For the gateway, it is the first IP of my subnet (216.x.x.1). For first available IP I have 216.x.x.3 and for last I have 216.x.x.30. For the netmask I put 255.255.255.224.
IP Pool Settings
GATEWAY: 216.x.x.1
NETMASK: 255.255.255.224
IP POOL: 216.x.x.3 - 216.x.x.30 (28)
My server is only using one connection called eno1 and the ifcfg-eno1 is as follows:
<code>DEVICE=eno1
HWADDR=xx:c4:xx:c4:xx:14
IPV6INIT=no
ONBOOT=yes
BOOTPROTO=static
IPADDR=216.x.x.2
NETMASK=255.255.255.255
GATEWAY=216.x.x.1
PREFIX=32
DEFROUTE=yes
DNS1=188.8.131.52
DNS2=188.8.131.52
</code>
Im not positive by all means but I'm starting to wonder if my main server IP needs to be outside of the subnet. I put the server IP as a /32 to be able to use the correct netmask in the IP pool settings (natbr3 gets these settings), this is the only way I'm able to ping the vps inside the server (outside still does not work).
I know this may be a shot in the dark and I've tried to be as precise with the information I've given in my question. If there is any more information need please ask!
Thank you for taking the time to read this and any help you may have to offer.
EDIT
I should mention I can access the VPS with VNC and inside the VPS I can ping the gateway but nothing else.
Answer: Come to find out, the server main IP being inside the /27 subnet is a issue and will cause Virtualizor IP Pool to not function properly. I have got that resolved by getting a dedicated IP for the main server IP.


Why does .htaccess redirect URL routing fine but break css/js/image links after two levels deep?

Question: I have the following .htaccess file in a subdirectory of a site:
RewriteEngine On

RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]

I have the following index.php file:

        <link href="css/main.css" rel="stylesheet"/>

if css loads, this should be green

javascript is NOT loaded

If images are displaying correctly, then there should be a green square below:

<?php echo '$_SERVER["REQUEST_URI"] = '. $_SERVER["REQUEST_URI"]; ?>

All URLs are properly redirected to index.php. However, if the URL is more than one level deep below the sub-directory path, then my css/js/images paths are broken:

What do I have to change to the .htaccess file so that routing works at any level and doesn't break my css/js/image paths?
Comment: You can always provide a absolute URL to the file.

It is easier to maintain if you set a variable to the site url in PHP and echo that out infront of each include.
Comment: Tried the 'base' tag?
Comment: I've considered that but I would like to keep these links relative if possible, just to lower overhead of moving the site from server to server, local to online, etc.
Comment: I'm not the best at htaccess but I've worked with a lot of CMS's and they've all done it with a absolute URL. I'll favorite this question maybe someone can think of a clever solution.
Answer: From the absolute URL suggestions, if the files are always at the root of the domain, and if you're in control of the html, you could do the leading-slash absolute, which might avoid having to edit them among servers.
/css/main.css
/js/main.js
/images/test.jpg

htaccess rules can help if the files move, or you're not in control of the html. e.g., I work on project where some are using dreamweaver, which loves to do ../images/test.jpg.
RewriteRule (css|js|images)/(.+)$ /$1/$2 [NC,QSA,L]

This assumes the files are actually at the root of the domain. If that varies among servers, then you'll need to edit the paths in htaccess - but that's still easier than editing the html.
This assumes all the style, script and images are in the three folders css, js, images; and these are the only folders with these names. e.g., there can't be another images folder in some other subfolder.
This will break any folder ending in these strings, e.g., myimages or somecss. That can be avoided by tweaking the rule to require these to stand alone. Then those folders won't be changed, only the specific css, js, and images folders.
RewriteRule (?:^|/)(css|js|images)/(.+)$ /$1/$2 [NC,QSA,L]

The (?:^|/) means non-capturing ?:, at the beginning ^ or after a slash /.


jQuery solution to detect for touch only device?

Question: I have designed my site with an image gallery that does not display the next / previous arrows until the mouse is rolled over them <code>.next:hover{display: block}</code> This is fine but the site is fluid and I did not think at all that hover (mouse over) does not work on touch screen! I do not want to keep the arrows on constant display unless the device is touch screen only like an ipad for example!
What is the best way to detect if the device is touch only and if so change display: none to display block automatically. Is there a jQuery way of doing this?
I hope this makes sense, I have googled it and search on S.O. but am unable to find a direct answer. That along with the fact that I am a bit (understatement) of a novice when it comes to jQuery!
Thank you for any help
Comment: Check out answers of http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript this question
Comment: Other than Modernizr if you are looking responsive design tutorial - 1) http://webdesignerwall.com/tutorials/responsive-design-in-3-steps 2) http://css-tricks.com/snippets/css/media-queries-for-standard-devices/ which will help you to write CSS for specific range of devices
Comment: Wow! If I cannot find the answer there there is no answer! It seems that Modernizr is what I may need. I will look into that and option as it seems to do what I am looking for the question in that post is very similar to mine. Thank you for your help.
Answer: I worked something out like this, the click counter also fires on touch events when I was testing it.
<code>// Detect touchscreen only
var touchscreenonly = true;
var moves = 0;
var clicks = 0;
$("body").mousemove(function() {
    moves++;
    if (moves > clicks + 1){
        touchscreenonly = false;
        // now unbind these functions if you like
        $(this).unbind("mousemove").unbind("click");
        console.log('mouse moved, this is not a touch-only device');
    }
}).click(function(){
    clicks++;
});
</code>
Answer: I was in a same situation like you but, I did not wanted to use Modernizr, so as a quick fix I just checked for the window width.Most of the touch devices including tablets falls below the width of <=1024. So I wrote the below piece of code inside document.ready:
<code>$(document).on("ready", function() {

   if ( $(window).width() < 1025 ){
       //Insert your code to add/display something different for mobile/tablet devices
   }

});
</code>
Hope it helps someone.


create matrix whose position value is given by a function

Question: I have to create a 5X5 matrix from a function given below.

f(x,y) = x(1-y) + y(1-x); where 0 < x,y <=5

where x indicate row position and y indicates columns. How do I create a matrix such that bottom left corner is f(0,0) and top left corner has value f(5,5)
Comment: What have you tried so far?
Comment: Just a tip: *f(x, y)* = `f[4-x, y]`
Comment: I have tried to create a list having 25 elements and then arrange list into matrix, but I am failing to create list in first place using `f = [x*(1-y)+y*(1-x) for x,y in range(0,5,1)]`.
Comment: Then you need to start with python basics. `for x,y in range(0,5,1)` doesn't make much sense.
Answer: <code>M,N = 5,5
matrix = [[((x*(1-y))+(y*(1-x))) for y in range(M)] for x in range(N)]
for i in range(N):
    print(matrix[i])
</code>


Does the position of ∃ matter?

Question:
Everyone who makes an A aces some final exam

Is this
<code>∀x,∃y: makes(x, A) => aces(x, y)
</code>
the same as
<code>∀x: makes(x, A) => ∃y: aces(x, y)
</code>
where x represents everyone and y represents exams.
Does the position of <code>∃</code> matter?
Comment: In this case both are equivalent, however, it is **not** the case for ∀x,∃y P(x,y) and ∃y,∀x P(x,y)
Answer: No, they are equivalent.
This is part of a theorem called "Prenex normal form".
Answer: Let $M=\{x\mid\text{makes}(x,A)\}$ and $E$ the set of exams. Then, both assertions are equivalent to:
$$
\forall x\in M,\quad\exists y\in E,\quad\text{aces}(x,y).
$$

Does the position of ∃ matter?


for-loop problems changing property of all objects in array

Question: My first time and I hope this is/was not only a problem for me.
Upfront, I create and do all stuff without .nib, .xib or storyboard and am quite new to Xcode.
Problem description:
I create a series of labels, that go into an array all programmatically.
int i is below or equal 4 else it does not fire anyway.
int i = (int)[players count];

if (i<=4) {

    nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width-(self.view.bounds.size.width/3)-20*widthmultiplayer, self.view.bounds.size.height-((50*heightmultibplyer)*i)-50*heightmultibplyer, (self.view.bounds.size.width/3), 50*heightmultibplyer)];
    nameLabel.text = enterName.text;

    [nameLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:fontSize]];
    [nameLabel setTextAlignment:NSTextAlignmentRight];
    [self.view addSubview:nameLabel];
    players[i] = nameLabel;
    NSLog(@"index: %i , name:%@", i, nameLabel.text);

    enterName.text = @"";
}

then I hide all labels programmatically with following code
for (UILabel *label in players) {
    label.hidden = YES;
}

Now the funny part - when I want to show them again using
for (UILabel *label in players) {
    label.hidden = NO;
}

it does not show the last entry.
Meaning:

if I have only 1 entry it shows nothing
if I have 3 entries it only shows 2
and so on and so on...

Funny thing is my Log of the array shows all objects, shows the correct index of each object and the hidden status as false (-so what it should be).
Tried to bring the views to front by
[self.view bringSubviewToFront:label]

but that wouldn't work as well.
I can't figure out why.  Answers and tips on what I do wrong would be highly appreciated.
---- EDIT ----
I found a workaround to my problem, maybe this helps someone:
i changed the change of the hidden value a little by doing this:
        for (UILabel *label in players) {
        [label removeFromSuperview];
        label.hidden = NO;
        [self.view addSubview:label];
    }

looks cheesy, is cheesy, but works.
Still if someone can help me find a solution or the major bug, i would really love it.
Comment: Why are you casting return values to ints? This might cause problems when building for 32 vs 64 bit.
Comment: Did you log `int i = (int)[players count]`?
Comment: @Joride: the int i I just use to figure out the needed index for the next
Comment: @Himanshu Joshi: also logged this one, but also when I Log the array players i have correct entries - first one has 0 - sure because the players count is 0 when it is empty and so next count 1 so next index 1.
Comment: The -count method of NSArray returns an NSInteger; why cast it to an int? Someday you will get into trouble with this practice..
Comment: True, should change the int to nsinteger right from the beginning, thanks for the tip
Answer: The NSArray indexes start at 0. You have to go from 0 to [players count] - 1.
Comment: array players has correct entries - first one has 0 - sure because the players count is 0 when it is empty, than i add one entry, so the count is 1 and the next needed index is also 1 if i would set the index to [players count]-1 than i would always overwrite the previous entry and never exceed a count of 1.
Comment: Are using an NSArray(Not an NSMutableArray). And if you are, have you added a nil object at the end?
Comment: I misinterpreted your code, then. I will delete my answer when the relevant comments are not important anymore. I would be good if you showed the declaration of `players`.
Comment: Did you log the `for`enumerations?
Comment: am using an NSMutableArray actually, i allocate it and fill it up on the run. Also logged the for enumerations, everything is perfect in the log, the thing just wont show
Comment: @user3071962 if possible and allowed please leave your answer, if i could upvote it i would (lacking reputation) but this a thing a lot of newcomers (as i am one) forget quite frequently
Answer: Ok I worked the whole theory part in this question and the result i got is that it worked properly without any issues
Here is the code i used for testing
players=[[NSMutableArray alloc]initWithCapacity:3];

for (int k=0; k<10; k++) {
    NSLog(@"%@",NSStringFromCGRect(CGRectMake(self.view.bounds.size.width-(self.view.bounds.size.width/3)-20*widthmultiplayer, self.view.bounds.size.height-((50*heightmultibplyer)*k)-50*heightmultibplyer, (self.view.bounds.size.width/3), 50*heightmultibplyer)));

}
int i=0;
CGRect rect=CGRectMake(self.view.bounds.size.width-(self.view.bounds.size.width/3)-20*widthmultiplayer, self.view.bounds.size.height-((50*heightmultibplyer)*i)-50*heightmultibplyer, (self.view.bounds.size.width/3), 50*heightmultibplyer);
NSLog(@"%@",NSStringFromCGRect(rect));
nameLabel = [[UILabel alloc]initWithFrame:rect];
[nameLabel setBackgroundColor:[UIColor blueColor]];
[nameLabel.layer setBorderColor:[UIColor blackColor].CGColor];
[self.view addSubview:nameLabel];
players[0] = nameLabel;

i=1;
nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width-(self.view.bounds.size.width/3)-20*widthmultiplayer, self.view.bounds.size.height-((50*heightmultibplyer)*i)-50*heightmultibplyer, (self.view.bounds.size.width/3), 50*heightmultibplyer)];
[nameLabel setBackgroundColor:[UIColor redColor]];
[nameLabel.layer setBorderColor:[UIColor blackColor].CGColor];

[self.view addSubview:nameLabel];

players[1] = nameLabel;
NSLog(@"%@",players);
i = (int)[players count];
if (i<=4) {
    NSLog(@"%@",players);
    nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width-(self.view.bounds.size.width/3)-20*widthmultiplayer, self.view.bounds.size.height-((50*heightmultibplyer)*i)-50*heightmultibplyer, (self.view.bounds.size.width/3), 50*heightmultibplyer)];
    [nameLabel setBackgroundColor:[UIColor greenColor]];
    [nameLabel.layer setBorderColor:[UIColor blackColor].CGColor];
    [self.view addSubview:nameLabel];
    players[i] = nameLabel;
    NSLog(@"index: %i , name:%@", i, nameLabel.text);

    NSLog(@"%@",players);
}
for (UILabel *label in players) {
    label.hidden = YES;
}
NSLog(@"%@",players);
for (UILabel *label in players) {
    label.hidden = NO;
}

NSLog(@"%@",players);

Now the Explanation of what may have went wrong.This case can occour due to the reason that  one of the label added into the array is not added into the view.That is the reason when you re-add it turns to be working
Comment: true, but my main problem is ... longer explanation: I create the labels in, let's say viewNr1., and they all show up. When I switch to viewNr2. and hide them, switch back to viewNr1. and unhide them, one is missing. as i just hide the 'views' so its actually a list of views that lie above each other, and are hidden, unhidden as needed.
Comment: although my problem only works in the workaround, the explanation is the best for someone having similar issues, always check that you add your subviews correctly! Thanks, if i come up with a more detailed description or the pit-trap i fell into, i will update this.


Finding the Average in a sequence of number in c while ignoring the negative numbers in the sequence

Question: I have to write a C program that reads a sequence of integers (positive, negative, or zero) and calculate the average of the positive integers only.
If there are no positive numbers, you should display the following statement followed by a new line
No positive numbers!
Here is my code, I just need help with how to ignore the negative numbers in the input sequence.
#include<stdio.h>

int main(){

    int num;  //number of elements
    int i;
    int sequence[100];  //numeber if sequence
    int sum = 0.0;            //sum if the sequence
    float avg;          // the average

    printf("Enter the number of number in the sequence:\n");
    scanf("%d", &num);

    while (num < 0 || sequence[num] < 0) {
        printf("No positine numbers!\n");
    }

    printf("Enter the sequence:\n");
    for (i=0; i < num; i++) {
        scanf("%d", &sequence[i]);
        sum += sequence[i];
    }

    avg = (float) sum / num;
    printf("Average is %.2f\n", avg);
    return(0);
}

Comment: A hint for starters: You do not need to store the full sequence of numbers, just add up the positive ones and keep a counter tracking how many you added. Divide after that.
Comment: you never break the while loop once you enter it.  "No positine numbers!\n" spammed forever.  you dont initialize any of your variables when you declare them, so you use squence[num] before its initialized.  but to answer your question, dont add sum += sequence[i] when sequence[i] is <= 0.
Comment: Please explain each line of your coding attempt, by adding a comment. It is very unclear what your thinking is. What is the idea of `sequence[num] < 0`? Where in  your code is anything related to "only positive numbers"?
Answer: Here:
while (num < 0 || sequence[num] < 0) {

you are testing sequence[num] before you have written any values to the array, and the test of num should be num <= 0 since if there are zero values, there are also no positive values.  You can only decide that there are no positive values after you have entered them all.
The array sequence is unnecessary - you can simply accumulate the positive values to sum and discard them, maintaining a count of valid values.  The avoids any buffer overrun issues also.
sum is an int, but you have unnecessarily initialised it with a double.
Your average calculation:
avg = (float) sum / num ;

is incorrect since num includes negative values - you need a separate count of valid values contributing to the average (unless the intent is to treat all negative values as zero).
Another issue is that you have not validated the input matched the format specifier.
int main()
{
    printf("Enter the number of number in the sequence:\n");
    int num = 0 ;
    int check = scanf( "%d", &num ) ;

    int positive_count = 0 ;
    int sum = 0 ;
    if( check != 0 && num >= 0 )
    {
        printf( "Enter the sequence:\n" ) ;

        int i = 0 ;
        while( i < num )
        {
            int value = 0 ;
            check = scanf( "%d", &value ) ;
            if( check != 0 )
            {
                i++ ;
                if( value >= 0 )
                {
                    positive_count++ ;
                    sum += value ;
                }
            }
        }
    }

    if( positive_count != 0 )
    {
        float avg = (float) sum / positive_count ;

        printf( "Average is %.2f\n", avg ) ;
    }
    else
    {
        printf( "No positive numbers!\n" ) ;
    }

    return 0 ;
}

Answer: If you want the average of the positive numbers, you should use a different variable than num for your final avg calculation.
I would do something like this:
    int PositiveNumCount = 0;
    float avg;
    for (i=0; i < num; i++) {
        scanf("%d", &sequence[i]);
        if(sequence[i] > 0){ sum += sequence[i]; PositiveNumCount++;}
    }
    avg = (float) sum / PositiveNumCount;

Answer: There are multiple problems in your code:

sequence[num] may refer to an entry beyond the end of the array which has undefined behavior, and otherwise reads from an uninitalized array, which has undefined behavior too. Just remove this test completely as it is useless.
you do not need to store the numbers read, just read them ne at a time into a temporary variable and only add and count the positive values.
you should test the return value of scanf to avoid undefined behavior on invalid input.

Here is a corrected and simplified version:
#include <stdio.h>

int main() {
    int num;           // max number of values to read
    int count = 0;     // number of positive values
    double sum = 0.0;  // sum if the sequence
    double avg;        // the average

    printf("Enter the number of number in the sequence:\n");
    if (scanf("%d", &num) == 1 && num > 0) {
        printf("Enter the sequence:\n");
        while (num-- > 0) {
            int temp;
            if (scanf("%d", &temp) != 1)
                break;
            if (temp >= 0) {
                sum += temp;
                count++;
            }
        }
        avg = sum / count;
        printf("Average is %.2f\n", avg);
    }
    return 0;
}

Answer: printf("Enter the sequence:\n");
for (i=0; i < num; i++) {
    scanf("%d", &sequence[i]);
    if(sequeunce[i] > 0){ //This if statement is what your looking for, but there are several other problems in your code.  GL!
        sum += sequence[i];
    }
}

The above if statement is what the OP was asking for: "Here is my code, I just need help with how to ignore the negative numbers in the input sequence."
There are many issues with his posted code, including using variables before they are initialized and infinite looping paths.  This is the shortest answer to his question.
Comment: This will give a wrong average, since you still have to track how many positive numbers you have added
Comment: Would you like to improve this code-only answer by adding some explanation?
Comment: From the OPs only question: "Here is my code, I just need help with how to ignore the negative numbers in the input sequence."  This code is riddled with issues...
Comment: @Yunnosch I have clarified my response, thank you for the suggestion.
Comment: Pointing out shortcomings and giving the shortest possible answer is not the same as a helpful answer and not the explanation to improve the answer either.
Comment: By me, for the reasons you mentioned @Yunnosch
Comment: @Yunnosch well thanks for clarifiying that.  I put the list of issues with the OPs source as the second comment to his question.
Comment: @ctx Fair is fair. And being open about it deserves respect in my opinion.
Comment: @Ctx He asked SPECIFICALLY where he needed help.  he didnt ask SO to finish his homework for him.  My answer is legitimately what the OP was requesting, but feel free to downvote me anyways.  Clearly this is a homework assignment and a learning experience, leaving the other issues in there is beneficial to his debugging efforts so he can LEARN on his own.
Comment: Giving only what OP asks for, with little explanation, is not the same as a helpful answer, especially not from point of view of every other future reader.
Comment: https://stackoverflow.com/help/how-to-answer

Read the question carefully. What, specifically, is the question asking for? Make sure your answer provides that – or a viable alternative. The answer can be "don't do that", but it should also include "try this instead". Any answer that gets the asker going in the right direction is helpful, but do try to mention any limitations, assumptions or simplifications in your answer. Brevity is acceptable, but fuller explanations are better.


Data Binding in axis2

Question: I want to create a simple webservice using Axis2 1.5.1. The expectations from the webservice is:
1. interoperability
2. interaction with custom objects
Do i require to use any data binding (initially i thought of using ADB) or is deploying WS using POJO sufficient?
Do we have enough documentation for the Data binding?
Because Axis2 quick start guide has some text for how to create webservices using these data bindings but it doesn't list the scenarios where to use what.

Thanks in advance.
Answer: Axis databinding (ADB) code cannot be reused as it is only for Axis2 Web services.
Your POJOs should be sufficient for data binding.
Comment: but how can i try changing the wsdl type (doc/literal) when i deploy webservice from POJO beacause the wsdl is autogenerated by giving ?wsdl in servlet

Data Binding in axis2


gradient of KL-Divergence

Question: Let $X$ be a finite set and $A$ be a set of probability distributions.
Then KL-Divergence between two probability distributions $P(x)$ and $Q(x)$ $\in$ A  is
$$D(P(x)\vert \vert Q(x))=\sum P(x)\operatorname{log}\left(\frac{P(x)}{Q(x)}\right)$$ for all x$\in$ X.
Since KL-divergence is the distance between two probability distributions, therefore for fixed $Q(x)$ we can talk about its derivative with respect to $P(x).$
Can anyone tell what will be its gradient w.r.t $P(x)$?
Comment: Gradients make sense in a continuous space -- we need some form of continuity on A to allow for derivatives.
Answer: $\newcommand{\dd}{\mathrm{d}}\newcommand{\R}{{\rm I\!R}}$Based on the formula you are using for the KL divergence, I'm assuming $X$ is a discrete space - say $X = \{1, 2, \ldots, n\}$. I will also assume that $\log$ denotes the natural logarithm ($\ln$).
For fixed $q$, the KL divergence (as a function of $p$) is a function $D_{\rm KL}(p \parallel q): \R^n \to \R$. We have
$$
\frac{\dd}{\dd p_i}D_{\rm KL}(p \parallel q)
{}={}
\frac{\dd}{\dd p_i}\sum_{i=1}^{n}p_i\ln\frac{p_i}{q_i}
{}={}
\ln\frac{p_i}{q_i} + 1,
$$
therefore, $\nabla_{p}D_{\rm KL}(p \parallel q) \in \R^n$ and its $i$-th element is
$$
(\nabla_{p}D_{\rm KL}(p \parallel q))_i = \ln\frac{p_i}{q_i} + 1.
$$
Comment: I think gradient will be (1 + ln(p(i)/q(i)),if I am not wrong.
Comment: +1 -- makes sense to me :)
Comment: Isn't the KL Divergence based on log10, instead of ln?
Comment: @DávidTóth it can be either

gradient of KL-Divergence


Programmatically create a menu

Question: How can I programmatically create a menu? I have 3 different menus I want to create: The first menu will be placed in the top left of the header; the second menu will be placed below the first menu; the third menu will be the main navigation.
Answer: If you are trying to do this in an update script, this should work:
$menus = array(
  array(
    'menu_name' => 'menu_test_one',
    'title' => 'My Menu One',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_two',
    'title' => 'My Menu Two',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_three',
    'title' => 'My Menu Three',
    'description' => 'Lorem Ipsum',
  ),
);

$links = array(
  array(
    array(
      'link_title' => 'Link1',
      'link_path' => 'http://yourdomain.com/link1',
      'menu_name' => 'menu_test_one',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link2',
      'link_path' => 'http://yourdomain.com/link2',
      'menu_name' => 'menu_test_one',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link3',
      'link_path' => 'http://yourdomain.com/link3',
      'menu_name' => 'menu_test_two',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link4',
      'link_path' => 'http://yourdomain.com/link4',
      'menu_name' => 'menu_test_two',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link5',
      'link_path' => 'http://yourdomain.com/link5',
      'menu_name' => 'menu_test_three',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link6',
      'link_path' => 'http://yourdomain.com/link6',
      'menu_name' => 'menu_test_three',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
);

// Save menu group into menu_custom table
foreach ($menus as $menu) {
  // Look the table first if the data does exist
  $exists = db_query("SELECT title FROM {menu_custom} WHERE menu_name=:menu_name", array(':menu_name' => $menu['menu_name']))->fetchField();
  // Save the record if the data does not exist
  if (!$exists) {
    menu_save($menu);
  }
}

$item = '';
foreach ($links as $layer1) {
  foreach ($layer1 as $link) {
    // Build an array of menu link
    $item = array(
      'link_path' => $link['link_path'],
      'link_title' => $link['link_title'],
      'menu_name' => $link['menu_name'],
      'weight' => $link['weight'],
      'expanded' => $link['expanded'],
    );
    // Look the table first if the data does exist
    $exists = db_query("SELECT mlid from {menu_links} WHERE link_title=:link_title AND link_path=:link_path", array(':link_title' =>  $link['link_title'], ':link_path' => $link['link_path']))->fetchField();
    // Save the record if the data does not exist
    if (!$exists) {
      menu_link_save($item);
    }
  }
}

Comments are welcome if my approach is wrong. Thanks.
Comment: Instead of running the $exists db query a more future proof (but maybe slightly slower) method would be to just use if (!menu_load($menu['menu_name'])) { menu_save($menu); }
Comment: Also when you check if the menu link exist:
// Look the table first if the data does exist
    $exists = ...
You need also to check for menu_name as the same link combination can be in different menus.
Comment: This is exactly what I want. Let me try your code and will give feedback later. Thanks for sharing
Comment: Cool, nice one!
Comment: My suggestion would be to use [menu_get_menus()](http://api.drupal.org/menu_get_menus) instead of a query. Then you can save the menus to a var and simply do an `if (!array_key_exists($menu, $menus)) {` - also adding the single param FALSE to menu_get_menus() returns only custom menus.
Comment: you should also make sure that page with target URL exist on the page if you will use not absolute URL. Otherwise you will not see link
Comment: Why is it necessary to check if the menu exists? `menu_save` already does a `db_merge` and checks the status of the menu. If it exists, it updates. If it does not exist, it creates the menu.
Answer: Here's a way to easily populate a menu from an array :

<?php
function populate_menu($links, $menu_name, $plid = 0) {
  foreach ($links as $link) {
    $ls = array(
      'menu_name' => $menu_name,
      'link_title' => $link['link_title'],
      'link_path' => $link['link_path'],
      'plid' => $plid,
    );
    $newpid = menu_link_save($ls);
    if (!empty($link['childs'])) {
      populate_menu($link['childs'], $menu_name, $newpid);
    }
  }
}

$items = array(
  array(
    'link_title' => 'Menu1',
    'link_path' => '<front>',
    'childs' => array(
      array(
        'link_title' => 'Sub Item 1',
        'link_path' => '<front>',
        'childs' => array(
          array(
            'link_title' => 'Link item 1',
            'link_path' => '<front>',
          ),
          array(
            'link_title' => 'Link item 2',
            'link_path' => '<front>',
          ),
        ),
      ),
      array(
        'link_title' => 'Sub Item 2',
        'link_path' => '<front>',
        'childs' => array(
          array(
            'link_title' => 'Link item',
            'link_path' => '<front>',
          ),
        ),
      ),
    ),
  ),
);
populate_menu($items, 'main-menu');

Answer: hook_menu() is all you need to implement in you custom module. For creation of custom module, refer to this documentation.
//Define the menus in the function which goes in your MYMODULE.module file

function MYMODULE_menu() {
  //the menu which will point to http://yoursite/first-menu
  $items['first-menu'] = array(
    'title' => 'First menu',  // will appear as the name of the link
    // Page callback, etc. need to be added here.
  );

  //the menu which will point to http://yoursite/second-menu
  $items['second-menu'] = array(
    'title' => 'Second menu',  // will appear as the name of the link
    // Page callback, etc. need to be added here.
  );

  //the menu which will point to http://yoursite/third-menu
  $items['third-menu'] = array(
    'title' => 'third menu',  // will appear as the name of the link
    // Page callback, etc. need to be added here.
  );

  return $items;
}

You could print the menu in any region by adding the following code to the page.tpl.php file of you theme.
// Add this line in

 to print it in header.
<?php
$menu1 = menu_navigation_links('first-menu');
print theme('links__first_menu', array('links' => $menu1));

//Print the second menu right after the first menu.
$menu2 = menu_navigation_links('second-menu');
print theme('links__second_menu', array('links' => $menu1));
?>

You don't need to print the third menu because by default it will appear on the navigation menu.
Note
This is not the best practice for creating a navigation menu and adding it to a page. hook_menu() is for creating page callbacks and not for creating navigation menus. Please read Menu system, which explains the differences. I answered this when I had started to learn Drupal and I don't recommend this answer anymore.
Answer: You can also try the Menu Import module. It's very cool and easy for menu deployment.
You can create menu by hands on your website and use generated JSON. Also you can create nodes for non-existing pages.
Here is example of export script:
$menu_name = 'menu-footer-secondary-menu';

// Create menu if doesn't exist.
if (!menu_load($menu_name)) {
  $menu = array(
    'menu_name' => $menu_name,
    'title' => t('Footer secondary menu'),
    'description' => '',
  );
  menu_save($menu);
}

// Import menu links from JSON.
$menu_string = 'Impressum {"url":"node\/1","options":{"attributes":[]}}
Datenschutzbestimmungen {"url":"node\/2","options":{"attributes":[]}}
Nutzungsbedingungen {"url":"node\/3","options":{"attributes":[]}}
';

$options = array(
  //'link_to_content' => TRUE, // Look for existing nodes and link to them.
  'create_content' => TRUE, // Create new content (also if link_to_content not set).
  'remove_menu_items' => TRUE, // Removes current menu items.
  'node_type' => 'page',
  'node_body' => 'Page is in development...',
  'node_author' => 1,
  'node_status' => 1,
);

menu_import_string($menu_string, $menu_name, $options);

You can run this script with hook_update_N() or Update script processor
Answer: For creating a menu block, in your .install file add the following code. (Replace mymodule with the module machine name.)
function mymodule_enable() {
  $t = get_t();

  if (module_exists('menu')) {
    menu_save(array(
      'menu_name' => 'my-new-menu',
      'title' => $t('My New Menu'),
      'description' => $t('My Menu description'),
    ));
  }
}

function mymodule_uninstall() {
  if (module_exists('menu')) {
    if ($my_menu = menu_load('my-new-menu')) {
     menu_delete($my_menu);
    }
  }
}

In the .module file, add this code.
function mymodule_menu() {
  return array(
   'mypage' => array(
   'title' => 'My Page',
   'description' => 'My Page description',
   'page callback' => 'my_page_callback_func',
   'page arguments' => array(arg(0)),
   'access arguments' => array('access content'),
   'menu_name' => 'my-new-menu',
   'file' => 'my.new.page.inc',
   'file path' => drupal_get_path('module', 'mymodule') . '/includes',
  ),
 );
}

Programmatically create a menu


How to dissect raw data in an email

Question: There may be an obvious answer to this question, but I have not found it yet.  I have two email messages that were sent to two different people in our company.  One individual did receive the message, the other did not.  I want to try to better understand why.  One way that I can think of to do this is to pick apart the raw email message (we use Exchange 2003) and see if there is a possibility that the problem resides at the senders side rather than our side.
What techniques are typically use to dissect email messages and/or verify their validity.  Also, what can be done on the Exchange side to understand what may have happened to undelivered email messages.  I have asked our local exchange administrator, and he can't answer the question for me, so I'm looking to the community for help -- Thanks.
Answer: You can use Exchange's message tracking feature to see exactly what path the incoming messages took; that's where I'd start. There's a decent tutorial here. Note that this is something your Exchange admin will have to do.
Answer: Well I don't think it's possible do dissect an email message that never arrived :)
1) You should eventually receive an NDR at the sender indicating why a message failed.
2) Enable Message Tracking and you'll get a log of all the messages through the server.  Here's a little walk-through .
3) Enable logging in the SMTP service (if the messages originated outside of the server).
4) Check your firewall logs, especially if they do any sort of mail filtering (many do).

How to dissect raw data in an email


Dificuldade para mover personagem em tabuleiro

Question: Tenho uma matriz de estruturas como tabuleiro.
Meu personagem começa na posição [0][0]:
tabuleiro[0][0] = personagem;

O personagem é exibido corretamente em sua posição inicial, mas não consigo movê-lo utilizando o código abaixo (está incompleto, mas deveria funcionar até onde fiz):
void movimentar(criatura tabuleiro[][10], criatura personagem){
system("cls");
imprime(tabuleiro);
criatura vazio;
int i=0, j=0;
char mover;

printf("Use WASD ou as setas do teclado para se mover pelo tabuleiro!\n");
scanf(" %c",&mover);

if(mover=='s'){
    tabuleiro[i+1][j]= personagem;
    i++;
}
imprime(tabuleiro);
system("pause");
}

O tabuleiro e o personagem são definidos algumas funções acima. Mais ou menos dessa forma (tirei o que considero menos relevante):
criatura tabuleiro[5][10];
    criatura personagem;
    criatura chefe;
    criatura vazio; // isto aqui adicionei recentemente, ainda preciso verificar se faz sentido criar uma "criatura vazio" para colocá-la no local de onde o personagem saiu.
    vazio.classe = ' ';

    for(i=0;i<5;i++){
        for(j=0;j<10;j++){
            tabuleiro[i][j].status = 0; // aqui o tabuleiro todo é dado como desconhecido, a princípio (utilizo 0 como status para aquilo que não está visível).
            tabuleiro[i][j].classe = ' ';
        }
    }

    // ATRIBUTOS PERSONAGEM
    personagem.classe = classeE;
    personagem.atc = atcE;
    personagem.def = defE;
    personagem.saude = saudeE;
    personagem.status = 1;
    tabuleiro[0][0] = personagem;

Quando aperto o s, o personagem permanece na mesma posição e um espaço em branco aparece do outro lado do tabuleiro.

A função para imprimir o tabuleiro é, em parte, esta:
for(j=0;j<10;j++){
            if(tabuleiro[i][j].status == 0){
                printf(" ?  ");
            }
            else{
                if(tabuleiro[i][j].classe=='X'){// X -> armadilha de grande potencial ofensivo
                    printf(" X  ");
                }
                else if(tabuleiro[i][j].classe=='x'){ // x -> armadilha de pequeno potencial ofensivo
                    printf(" x  ");
                }
                else if(tabuleiro[i][j].classe=='i'){//i -> inimigo
                    printf("%c_%c ",155,155);
                }
                else if(tabuleiro[i][j].elixir == 'e'){ // e -> elixir
                    printf(" %c  ",3);
                }
                else if(tabuleiro[i][j].classe == 'C'){ //C -> Chefe
                    printf("%c_%c ",227,224);
                }
                else if(tabuleiro[i][j].classe == ' '){
                    printf("   ");
                }
                else if(tabuleiro[i][j].classe=='g' || tabuleiro[i][j].classe=='b' || tabuleiro[i][j].classe=='p'){ // g,b ou p -> herói
                    printf("^_^ ");
                }
            }
        }

O status do personagem é definido como 1 no início do código, para que ele seja visível. Não copiei o código todo aqui pois seria muita coisa, é possível saber o que está dando errado apenas com essas informações?
@edit: troquei
if(mover=='s'){
    tabuleiro[i+1][j]= personagem;
    i++;
}

por
 if(mover=='s'){
        tabuleiro[i+1][j] = personagem;
        tabuleiro[i+1][j].classe = 'g'; // onde g é a classe guerreiro
        tabuleiro[i][j].classe = ' ';
        i++;
    }

e parece estar "funcionando", apenas não tenho certeza se está da maneira correta...
Comment: Sua ideia de `criatura vazia` pode ser comparável a algo como um [`Objeto Nulo`](https://en.wikipedia.org/wiki/Null_object_pattern).
Comment: De onde vem o `i` e o `j` que estão associados nessa tentativa de movimentação?
Comment: A princípio ambos são definidos como 0, visto que a posição inicial do personagem sempre será [0][0].
Comment: Mas e quanto à atualização dele? Ele não deve se manter com esses valores a vida toda. Tem como por mais contexto ao redor desse trecho do `mover`? Para saber como as variáveis se relacionam, de onde vem, para onde vão
Comment: É verdade! Pensei, então, em colocar um i++ após o tabuleiro[i+1][j]= personagem; no if do "s". A princípio eu tinha pensado em fazer um for para verificar onde o personagem está, mas a posição inicial é sempre conhecida, então penso que é possível trabalhar alterando apenas o valor do i e do j partindo do 0,0, nesse caso. Irei atualizar o post com mais informações // @JeffersonQuesado adicionei novas informações.
Comment: Já posso dizer que a função `movimentar` está errada. Você não tem persistência da posição atual do jogador, então ele não pode, digamos ir duas vezes para baixo. Não sei se vou conseguir elaborar uma resposta em tempo, mas recomendo que você guarde no próprio jogador qual a sua posição atual.
Comment: Obrigado @JeffersonQuesado, acabei notando isso quando fui tentar movimentar aqui. A solução que encontrei foi passar os valores da linha e coluna por ponteiro: int *lin, int *col
Depois os armazeno em variáveis int dentro da função:
int l = *lin;
int c = *col;
Por fim, fiz a movimentação da seguinte forma:
if(tabuleiro[l+1][c].classe == ' '){
    tabuleiro[l+1][c] = personagem;
    tabuleiro[l+1][c].classe = classeE;
    tabuleiro[l][c].classe = ' ';
    l++;
    *lin = l;

Parece ter funcionado! edit: aqui nos comentários fica complicado de ler, vou adicionar nas respostas
Answer: A solução que encontrei foi a seguinte:
void movimentar(criatura tabuleiro[][10], criatura personagem,char classeE, int *saudeE, int *atcE, int *defE, int *lin, int *col, int *elixir){ // linha e coluna passados aqui
    system("cls");
    imprime(tabuleiro);
    criatura vazio;
    int l = *lin;
    int c = *col;
    char mover;
    int retirar;
    srand(time(NULL));
    printf("Use W, A, S, ou D para se mover pelo tabuleiro!\n");
    scanf(" %c",&mover);

    if(mover=='s' || mover =='S' ){
        if(l+1<=5){
            if(tabuleiro[l+1][c].classe == ' '){ // a movimentação ocorre diretamente se o local para onde o usuário deseja ir não existe inimigo
                tabuleiro[l+1][c] = personagem;
                tabuleiro[l+1][c].classe = classeE; // classeE é a classe escolhida pelo usuário no início do jogo
                tabuleiro[l][c].classe = ' ';
                l++;
                *lin = l; // salvando o valor de volta na função anterior

Não sei se essa solução está realmente adequada, mas até agora tem funcionado bem. Criei outros ifs para movimentar para os outros lados e tomei cuidado com todos os casos especiais que imaginei.


If $\alpha, \beta$ are roots of $x^2-3ax+a^2=0$, find the value(s) of $a$ if $\alpha^2+\beta^2=\frac{7}{4}$.

Question: If $\alpha, \beta$ are roots of $x^2-3ax+a^2=0$, how do you find the value(s) of a if $\alpha^2+\beta^2=\frac{7}{4}$.

I tried to substitute the $\alpha, \beta$ but confused since it is equal to $0$.
Tried to expand $\alpha^2+\beta^2$. No clue here too.

How do you solve this?
Comment: Try to write down what $(\alpha+\beta)^2$ is equal to. . Can you express $\alpha^2+\beta^2$ using $\alpha+\beta$ and $\alpha\beta$? (I will add that you can get $\alpha+\beta$ and $\alpha\cdot\beta$ from the coefficients. Wikipedia: [Vieta's formulas](https://en.wikipedia.org/wiki/Vieta%27s_formulas).)
Comment: @MartinSleziak I did that. It becomes $(\alpha+\beta)^2-2ab$. But what do I do with it. I'm really lost.
Comment: Well, as already explained in an answer, if $x^2-cx+d=0$, you know both $\alpha+\beta=c$ and $\alpha\beta=d$, hence $\alpha^2+\beta^2=(\alpha+\beta)^2-2\alpha\beta=c^2-2d$.
Answer: Viète's relations give us $\alpha+\beta=3a$ and $\alpha\beta=a^2$, from which we get an equation in $a$:
$$(3a)^2-2a^2=(\alpha+\beta)^2-2\alpha\beta=\alpha^2+\beta^2=\frac74$$
This simplifies to $7a^2=\frac74$ or $a^2=\frac14$, whence $a=\pm\frac12$.
Answer: We know that: $\alpha+\beta=3a$ and $\alpha\beta=a^2$.
Now, $$(\alpha+\beta)^2-2\alpha\beta=\alpha^2+\beta^2$$ So,
$(\alpha+\beta)^2-2\alpha\beta=(3a)^2-2a^2=\frac74$
Now, just equate:
$7a^2=\frac74 \implies a^2=\frac14$, then $a=\pm\frac12$.
Answer: No squaring: $${7\over 4}=\alpha^2+\beta^2 =(3a\alpha^2-a^2)+(3\beta -a^2) =  3a\underbrace{(\alpha+\beta)}_{3a}-2a^2 =7a^2$$
So $a=\pm{1\over 2}$.


Chrome storage sync / local solution

Question: I'm dealing with a dilemma regarding chrome storage.
My use case it that I have a Chrome extension that will store the user's cleaned tabs on a daily basis. One of the requirements is that a history is kept, so I store tabs in an array per day.
My current implementation is to store to chrome.storage.sync, however this storage is way to small for what I intend to use it. It is in fact, rather tiny.
The second option would be to use chrome.storage.local which has sufficient capacity, but we don't want the user's historical tab data to get lost, so this poses the problem that we actually need sync.
The third option is to use localstorage and implement a custom sync to some free remote service like Firebase.
My question is:
Is my understanding right that chrome.storage.sync is only to be used for some configuration data? And is there a straightforward way to force sync the 'local' chrome storage anyhow (might Firebase be an option)?
Comment: The sync storage is for configs, yes. You can use any other storage (like local, localStorage, or IndexedDB) with any custom external cloud sync API.
Answer:
Is my understanding right that chrome.storage.sync is only to be used for some configuration data?

Yes, being a limited storage, it is intended for maintaining different forms of state data.

And is there a straightforward way to force sync the 'local' chrome
  storage anyhow (might Firebase be an option)?

You can definitely use some external service like Firebase to save the user data and gain synchronization on different devices

Chrome storage sync / local solution