Comparing prevalence among sites. Fisher.test and pairwise.t.test

Question: I'm studying the prevalence of one parasite on a host from different localities. I do it by assigning presence ("1") or absence ("0") to each host sampled.
After the sampling, I got something like this:
site      <- c("A", "A", "B", "B", "B", "C", "C","A", "A", "B", "B", "B", "C", "C",
               "A", "A", "B", "B", "B", "C", "C","A", "A", "B", "B", "B", "C", "C")
infection <- c("1", "1", "0", "0", "0", "1", "0", "1", "1", "0", "0", "0", "1", "1",
               "1", "1", "0", "0", "1", "1", "1", "1", "0", "1", "0", "0", "0", "1")
table1    <- data.frame (site, infection)

I created a data.frame with the data to automatize the process:
library(dplyr)
table.by.site <- ddply(table1,
                       "site",
                       summarise,
                       Infected = length(which(infection=="1")),
                       NonInfected = length(which(infection=="0")))
table.by.site

In total, 3 sites and 2 states of infection.  Number of hosts from each site: A= 180; B= 160; C=160.
How can I see if the prevalence of the infections depends on the site of sampling? I have done a fisher.test, finding significant differences:
table.simple <- table.by.site [,-1] #I remove the "site" column.
fisher.test(table.simple)

But how I perform a pairwise t-test? How can I introduce my grouping factor (site)? Should I use a different approach?
EDIT
I will edit the questions instead open a new one.
Let's say I've been collecting samples from 3 different sites (i.e., A, B, and C) in different moments (i.e., week of the year, from 1 to 52). From each of this sampling trips I could obtain a certain number of hosts (e.g. 20 from each). I examined these hosts and I calculate the prevalence (%) of infected hosts per site and trip.
So, the code to generate the table would be something like this:
week      <- c("1","1","2","2","3","3","4","5","5","6","6","6","6","7","8","9",
               "10","11","12","13","14","14","14","15","15","15","16","16","16",
               "16","16","17","17","18","18","18","18","18")
site      <- c("A","A","C","C","B","B","C","B","B","A","A","A","A","B","C","B","C","B",
               "C","A","C","B","B","B","A","A","A","A","C","C","C","C","C","A","A","B",
               "B","B")
infection <- c(1,0,0,0,1,1,1,0,1,0,1,0,1,0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,1,0,0,0,0,
               1,1,0,0,0)
table (week)
raw.table <- data.frame (week, site, infection)

Then I calculate the Prevalence of infection for each site and site:
library(plyr)
table.summary <- ddply(raw.table,
                       .(week, site),
                       summarize,
                       Prevalence = ( (sum (infection)*100) / length(infection)))
table.summary

Now, can I use an ANOVA to test the differences in prevalence among sites? Is there any problem because they are percentages?
anova.table <- aov(Prevalence ~ site, data=table.summary)
summary(anova.table)

In the example there is no significant differences among site, but if I want to do a post hoc test, I'd use a pairwise comparison, correcting the p-value with Bonferroni
pairwise.t.test(table.summary$Prevalence, table.summary$site, adj.meth="bonferroni")

Is the whole process correct? Should I take additional steps? Are the percentages a problem for this analysis?
Comment: What is your end goal? What would be the point of the pairwise t-test? Why did you enter `infection` as a character variable? Are you thinking of `site`s as a fixed effect (ie, do you only wonder about differences among those exact sites), or are you thinking of the sites as sampled from a larger population?
Comment: My end goal is to be able to find differences in prevalence (% of host with the parasite) among sites. My original variable is a factor, I should have make it factor, you are right. Site is the fixed effect, I'm only concert about these 3 sites.
Comment: You cannot use an ANOVA, or `pairwise.t.test`; you would use a logistic regression model--see my answer below.  In addition, you have repeated measures, so you need to take that into account.  The GEE may be appropriate.
Comment: I'm not familiar with GEE, but I'll look into it. Thanks.
Comment: It may help you to read my answer here: [Difference between generalized linear models & generalized linear mixed models in SPSS](http://stats.stackexchange.com/a/32421/7290). In R, you could use the [geepack package](http://cran.r-project.org/web/packages/geepack/index.html), there is a nice tutorial here: [pdf](http://www.jstatsoft.org/v15/i02/paper).
Comment: Thanks, I'll use R, but I want to understand how it works under the hood so I can use it with confidence.
Comment: @gung, I've been reading your sources and I think I almost got it.

Because the individuasl collected in each collecting trip (`week`) are not independent, I should set them into the same cluster (`id`). My `outcome` would be the `infection` predicted by `site`.

Because `infection` is a dichotomous variable ("0" or "1"), I need to use a logistic regression. If I want to add more predictors (i.e., `temperature`, `rain`, etc. that may or may not be continuous), should I set a new `id` with the interaction between `site` and `week`?
Comment: No the interaction terms would use the same `id` grouping indicator.
Comment: I understand. Last question: If instead of a dichotomous variable I use a continuous variable as `outcome`, would GEE still valid or should I use a different function?
Comment: You could use a GEE, I think, but it wouldn't typically be done. If you think the residuals would be normal, you could use a regular old linear mixed effects model.
Comment: Probably the residuals won't be normal.
Comment: If you had a continuous outcome, but with non-normal residuals, the GEE might be a reasonable approach.
Answer: This piece of code, close to your own code, tests if the prevalence across sites is similar:
site      <- c("A", "A", "B", "B", "B", "C", "C","A", "A", "B", "B", "B", "C", "C",
               "A", "A", "B", "B", "B", "C", "C","A", "A", "B", "B", "B", "C", "C")
infection <- c("1", "1", "0", "0", "0", "1", "0", "1", "1", "0", "0", "0", "1", "1",
               "1", "1", "0", "0", "1", "1", "1", "1", "0", "1", "0", "0", "0", "1")
data.raw    <- data.frame (site, infection)
data.table <- table(data.raw$site, data.raw$infection)
data.table
fisher.test(data.table)

It should not be necessary to perform t-tests. T tests are generally for testing two continuous variables like length; an ANOVA would be the tool to compare more than two continuous variables.
The test above could best be compared to an ANOVA, but then your variable is categorical, hence the Fisher's test.
If you want to add post-hoc tests, then you can perform Fisher's exact tests (or chi-square) for each of the site combinations AB, AC, BC. You would need to use a Bonferroni correction. For more information see for example: http://www.biostathandbook.com/fishers.html in the post-hoc section.
Comment: Thanks, I did the Fisher's Exact Test (`fisher.test`) and it's indeed significant. I'd like to know what sites are creating that difference. But I can't figure out how to use `pairwise.t.test`.
Comment: Are you sure you want pairwise.t.test? A post hoc analysis could easily be done with a combination of Fisher's exact tests and a Bonferroni correction.
Comment: I'll do the Fisher's exact test for each combination if I'm not able to use `pairwise.t.test`, but I'd like to use it. I have more data to analyze and for some of them there are more than 3 fixed variables. Thanks.
Answer: I would not use Fisher's exact test for your situation.  Fisher's exact test assumes the marginals were fixed in advance (see here), which I doubt is true in your case.
I wonder if you are worried about the validity of the chi-squared test.  The rule of thumb for the chi-squared test is that the expected values for the cells should be at least 5, not that the observed cell counts need to be.  That rule of thumb is known to be too conservative.  In your case, four out of six expected values are less than 5, but not by much, so the chi-squared test is probably fine.  Nonetheless, since that is a large proportion of your cells, and you have relatively few data, you could set simulate.p.value=TRUE just to be safe:
table(site, infection)
#     infection
# site  0  1
#    A  1  7
#    B 10  2
#    C  2  6
chisq.test(table(site, infection))$expected
#     infection
# site        0        1
#    A 3.714286 4.285714
#    B 5.571429 6.428571
#    C 3.714286 4.285714
chisq.test(table(site, infection), simulate.p.value=TRUE)
#  Pearson's Chi-squared test with simulated p-value
#  (based on 2000 replicates)
#
# data:  table(site, infection)
# X-squared = 11.75, df = NA, p-value = 0.003498

Another way is to fit a logistic regression model.  You can determine if the sites differ by using a likelihood ratio test of the model as a whole (see here).  Here we see that the sites differ:
infection = factor(infection, levels=c("0","1"))
mod       = glm(infection~site, family=binomial)
summary(mod)
# ...
# Coefficients:
#             Estimate Std. Error z value Pr(>|z|)
# (Intercept)   1.9459     1.0690   1.820  0.06872 .
# siteB        -3.5553     1.3202  -2.693  0.00708 **
# siteC        -0.8473     1.3452  -0.630  0.52878
# ...
#     Null deviance: 38.673  on 27  degrees of freedom
# Residual deviance: 25.839  on 25  degrees of freedom
# ...
1-pchisq(38.673-25.839, df=2)  # [1] 0.00163355

To run multiple comparisons on the different sites versus each other, we may want to use the Bonferroni correction to the p-value.  This is a bit conservative, but may be reasonable since your contrasts are not a-priori or orthogonal.  To control the familywise type I error rate at .05, you want the individual p-values to be less than .0167.  With relatively few data, you may not want to trust the normal approximation for the Wald tests in the output above.  To check for pairwise differences between the sites, you can select only two sites at a time and use the likelihood ratio test as before.  From this, you can see that B differs from A, and from C, but that C does not differ from A:
.05/3  # [1] 0.01666667
summary(glm(infection~site, family=binomial, subset=site!="C"))  # B vs A
# ...
#     Null deviance: 27.526  on 19  degrees of freedom
# Residual deviance: 16.842  on 18  degrees of freedom
# ...
1-pchisq(27.526-16.842, df=1)  # [1] 0.001080661
summary(glm(infection~site, family=binomial, subset=site!="A"))  # B vs C
# ...
#     Null deviance: 26.920  on 19  degrees of freedom
# Residual deviance: 19.811  on 18  degrees of freedom
# ...
1-pchisq(26.920-19.811, df=1)  # [1] 0.007669788
summary(glm(infection~site, family=binomial, subset=site!="B"))  # C vs A
# ...
#     Null deviance: 15.442  on 15  degrees of freedom
# Residual deviance: 15.026  on 14  degrees of freedom
# ...
1-pchisq(15.442-15.026, df=1)  # [1] 0.5189397

Comment: Impressive. I'm applying your code and comments to my data to see if it could be used. Thanks!


Form API : display the same form again with AJAX, but with different values, on submit

Question: I originally posted this question on StackOverflow.com but I realize this place is more appropriate... If ever I get useful answers on S.O. I will post them here.
My point is, I never found an (even dirty) way to do what I intend to do, and never managed to find an answer, although it seems quite improbable that no one ever had the same request and/or problem.
Which is, by the way...
Calling the same form again with AJAX, but with different values than those previously entered by the user
The idea
I've got a Drupal Form (a normal form built with Drupal Form API) with textfields and an AJAX-ified submit button. This form is displayed through an AJAX call and is itself AJAX-ified, so.
When I click on 'Submit', I want to do some stuff like looking in the database, updating some values, etc, based on what the user entered in the form. And then, I want to ajax-display the same form again, but with different values than those entered by the user in the first instance of the form.
Everything goes fine with doing whatever I want during the processing, but whatever I do, no matter what, I face the same problem again and again :
The problem
When the new instance of the form is displayed, it is displayed with the previous values (those entered by the user). I never was able to display other values than those previously here in the form when "Submit" was clicked in the previous instance of the form.
Simple example
What I'm actually trying to do is quite complex, with several ajax_commands and a bit of processing, but here is a simpler example that faces exactly the same problem :
function ajax_first_callback_to_my_form($type = 'ajax') {
// here the first instance of the form is ajax-called. No problem with that.

    $mail = 'firstname.lastname@example.com';
    $first_message = 'Please enter an email address...';

    $commands = array();
    $commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($mail, $first_message));
    $page = array('#type' => 'ajax', '#commands' => $commands);
    return($page);

}

function display_my_form($mail, $message) {
// the function used to display the form.
// it can be called by the first ajax callback (the previous function in this example)
// or by the ajax callback triggered by clicking 'submit' on the form itself.

    $form = drupal_get_form('my_form', $mail, $message);

    $display = '
';
    $display .= render($form);
    $display .= '
';

    return $display;

}

function my_form($form, &$form_state, $mail, $message) {
// the form constructor

    $form = array (
        'email' => array (
            '#type' => 'textfield',
            '#default_value' => $mail,
            '#suffix' => '
'.$message.'
',
        ),
        'submit' => array (
            '#type' => 'submit',
            '#ajax' => array (
                'callback' => 'my_ajax_callback', ),
        ),
    );

}

function my_ajax_callback($form, &$form_state) {
// triggered by clicking 'submit' in the form

    $mail = $form_state['values']['email'];

    if ($mail == 'email@example.com') {
        $new_mail = 'firstname.lastname@example.com';
        $new_message = 'You entered a correct email and here is your new one';
    } else {
        $new_mail = $mail;
        $new_message = 'You entered an incorrect mail, please correct it';
    }

    $commands = array();
    $commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($new_mail, $new_message));
    $page = array('#type' => 'ajax', '#commands' => $commands);
    return($page);

}

function my_form_submit($form, &form_state) {
// my_form submit handler

    $form_state['rebuild'] = true; // appears necessary, otherwise won't work at all

}

Okay, it was quite a long piece of code but it seemed useful to fully understand my question.
Processing stuff happens correctly...
All the stuff I want to do in my_form_submit or in my_ajax_callback is properly done. If I check the variables in display_my_form() they are correctly updated.
... but the new instance of the form doesn't take it into account
But whatever I can try, the next time the form is displayed with AJAX, the email field will be 'firstname.lastname@example.com' as its default value (or any different mail entered by the user), and the message div will be filled with 'Please enter an email address...'.
I tried MANY ways of doing this differently, putting the after-submit processing in the ajax callback, in the my_form_submit function, using $_SESSION variables instead of passing them through the different functions, using the database... None of this works.
What to do ?
Quite annoying. This is not the first time I encountered this problem. Last time I could find a workaround, simply by giving up this idea of re-displaying the same form through AJAX, but now I really would appreciate being able to do this.
Could the problem be related to $form_state['rebuild'] ?
By the way, I'm curious about it : have you encountered this problem before ? Is it something simple which I'm missing out ? If it's a bug, could this bug be Drupal-related, or AJAX-related... ?
Any help or ideas will be truly appreciated. Thank you for your time.
Answer: I came up with a solution to this one :
If you are to display the same form again with AJAX, for instance with this function (called by your AJAX callback), no matter what you'll do, it will display the same values again and again :
// It doesn't work :

function display_my_form($mail, $message) {

    $form = drupal_get_form('my_form', $mail, $message);

    $display = '
';
    $display .= render($form);
    $display .= '
';

    return $display;
}

If you want to change the fields values when refreshing the form, you have to update the form manually, after having called it again, by adding this kind of line :
// It works :

function display_my_form($mail, $message) {

    $form = drupal_get_form('my_form', $mail, $message); // $variables are simply ignored if the form is already displayed. Rebuilding it won't change a thing.

    $form['email']['#default_value'] = $mail; // update a part of the form
    $form['email']['#suffix'] = $message; // update another part of the form

    $display = '
';
    $display .= render($form);
    $display .= '
';

    return $display; // sends $display to our AJAX callback, and everything's fine now

}

Contrary to easy belief one (such as... me) can first have about it, the form doesn't take into account the variables it's being sent with drupal_get_form, when already constructed and recalled by AJAX.
It's just not enough to update the variables, and do drupal_get_form again. You have to do drupal_get_form, and afterwards manually update the parts of the form you want updated.
Hope this will help someone.


I do not know what is wrong with my function

Question: I have this code. However I am not able to run it as a function.
def verify_result_same():
    if verify_result_same.is_identical() & verify_result_same.confidence() > 0.5:
            face_client.face.verify_face_to_face(source_image1_id, detected_faces_ids[0])
            print('Faces from {} & {} are of the same person, with confidence: {}'
            .format(source_image_file_name1, target_image_file_names[0], verify_result_same.confidence))
            print("Valid face verification")

    else:
            print('Faces from {} & {} are of a different person, with confidence: {}'
            .format(source_image_file_name1, target_image_file_names[0], verify_result_same.confidence))
            print("Invalid face verification")
            text = "Face verification is not valid. Please try again."
            send_msg(text)

I am getting errors such as:
AttributeError: 'function' object has no attribute 'is_identical'
AttributeError: 'function' object has no attribute 'confidence'

Anyone can help?
Comment: I don't see why this would work to begin with? Where are these variable declarations, and more importantly, you shouldn't be able to access them from a function, nor meta call the function and access it either.
Comment: What are `is_identical` and `confidence`? and why are you trying to call them from `verify_result_same`?
Comment: What are you checking for *is_identical* and *confidence*, this given function? Please expand your question.
Comment: use `f` strings: `f"some text {some_var}"`
Answer: if verify_result_same.is_identical() & verify_result_same.is_confident() < 0.5:

Here you have used "verify_result_same" object which is same as the function you defined in the previous line.
Answer: verify_result_same is a function, and you maybe have defined a class named verify_result_same. So you should rename your function name from  verify_result_same to something others.


Covariance of linear combination of normal distribution is zero implies independence?

Question: Let's say we have i.i.d. normal distributions $Z_1, ..., Z_n$.
For some nonzero constants $a_1, \cdots, a_n$ and $b_1, \cdots, b_n$, let
$$X = a_{1}Z_{1} + \cdots + a_{n}Z_{n}\\
Y = b_{1}Z_{1} + \cdots + b_{n}Z_{n}$$
If $X$, $Y$have covariance zero, are $X$ and $Y$ necessarily independent?
Comment: I'm pretty sure this is effectively a duplicate. [This one](http://stats.stackexchange.com/questions/137518/proof-for-linear-combination-of-multivariate-normal-x) addresses the central issue (that (X,Y) will be bivariate normal), from which the answer to your question follows (if that's not obvious see [here](http://stats.stackexchange.com/questions/237003/independence-of-linear-combination-of-multivariate-distribution)), but I think there's another one which even more directly addresses this.question
Comment: Yes, $X$ and $Y$ will have a bivariate normal distribution, therefore zero covariance implies independence.
Answer: As gammer pointed out in a comment, $X$ and $Y$ enjoy a bivariate normal distribution and so the assumption that $X$ and $Y$ are uncorrelated suffices to show that $X$ and $Y$ are indeed independent (normal) random variables.  However, arriving at the point that $X$ and $Y$ are bivariate normal requires just a tad more work.
A standard definition of joint normality of $n$ random variables $Z_1, Z_2, \ldots, Z_n$ is

$n$ random variables $Z_1, Z_2, \ldots, Z_n$ are said to be jointly normal if for all choices of real numbers $a_1, a_2, \ldots, a_n$, $X=\sum_{i=1}^n a_iZ_i$ is a normal random variable.

Note that $Z_1, Z_2, \ldots, Z_n$ enjoying the property of being jointly normal  implies that $Z_1, Z_2, \ldots, Z_n$ themselves individually are normal random variables. So, in the OP's problem where $Z_1, Z_2, \ldots, Z_n$ are i.i.d. normal, (and hence jointly normal), $X=\sum_{i=1}^n a_iZ_i$ and $Y=\sum_{i=1}^n b_iZ_i$  certainly are normal random variables. Even more, $X$ and $Y$ are jointly normal random variables because every linear combination $\alpha X + \beta Y$ of $X$and $Y$ is a normal random variable. Note that
\begin{align}
W &= \alpha X + \beta Y\\
&= \alpha\sum_{i=1}^n a_iZ_i + \beta\sum_{i=1}^n b_iZ_i\\
&= \sum_{i=1}^n (\alpha a_i + \beta b_i)Z_i\\
&= \sum_{i=1}^n cZ_i
\end{align}
and so $W,$ being a linear combination of the jointly normal $Z_i$ is normal by definition.  So, $X$ and $Y$ are themselves jointly normal, and since they have zero covariance, they are independent too.

Jointly normal random variables that are uncorrelated (a.k.a. have zero covariance) are independent normal random variables.
Normal random variables that are uncorrelated (a.k.a. have zero covariance) are not necessarily independent.

A common example of normal uncorrelated $X$ and $Y$ that are not independent is  $X$ being a standard normal random variable and $Y = BX$ where $B$ is a discrete random variable (independent of $X$) that takes on values $\pm 1$ with equal probability $\frac 12.$. So, a little extra work is needed because we need to supplement the fact that $X$ and $Y$ are normal random variables (which is immediate from the definition of joint normality of the $Z_i$) with the additional fact that $X$ and $Y$ are also jointly normal in order to claim that since $X$ and $Y$ are assumed to be uncorrelated, they are also independent.
Answer: This must be a duplicate, but impossible to find. Since $Z_a, Z_2, \dotsc, Z_n$ are iid normal, the vector $Z$ have a multinormal distribution (with a diagonal covariance matrix.) Now, a linear combination of the components of a multivariate normal distribution is itself multivariate normal, as proved at Proof for linear combination of multivariate normal X? and elsewhere.
So your vector $(X,Y)$ is bivariate normal, and a bivarite normal with correlation zero have independent components. So the answer is yes.


Pegar valor da String (.net core para JQuery)

Question: Estou desenvolvendo um site com .net core e estou utilizando o JQuery. Na pagina Index.cshtml.cs eu tenho uma função que tem as validações e la me passam as mensagens (se está ok, se houve algum erro), atraves de uma string. Me ajudem, pois sou novo em .Net e eu nao tenho ideia de como fazer.
Eu preciso, no JQuery, pegar o valor desta string para eu retornar a mensagem tratada.
Agradeço a vcs.
Codigo:
public async Task OnPostAsync(parametros)
{
    ....
    await AtivacaoVerificarAsync2(Parametros);

   //*Pegar o valor da mensagem aqui*

    return;
}

public async Task AtivacaoVerificarAsync2(Parametros)
{
     Mensagem = "deu certo";
     return;
}

JQuery:
$(document).ready(function () {
    $("#numeroSerie").focus();

    $("#form-login").on("submit", function () {
        $.ajax({
            url: "https://localhost:44390/",
            data: {},
            complete: function (xhr, statusText) {
                if (xhr.status == 200) {
                    alert(myValue);//*ALERTAR A MENSAGEM AQUI*
                } else {
                    alert(myValue);//*ALERTAR A MENSAGEM AQUI*
                }
            }
        });
    });
});

Não consigo usar o ScriptManager.RegisterStartupScript, pois da erro no ScriptManager, dizendo que ele nao existe no contexto atual, e alem disso nao consigo tambem usar o System.Web.UI
Comment: Seu projeto é ASP.NET Core Razor Pages?
Comment: Para pegar um valor de um **`input`** com jQuery é só fazer **$("id_ou_classe_ou_input[name='seuInput']").val()**
Comment: mas nao é o valor de um input, que eu preciso... preciso do valor de uma string que esta dentro de um metodo
Comment: Sem código disponível, não tem como saber.
Comment: adicionei um codigo base pra vc ter uma noção aí, se puder me ajudar eu agradeço
Comment: Quando você acessa o https://localhost:44390/, oque ele retorna?
Comment: ele retorna a minha pagina index, normal
Comment: @Rafael sim, ele é
Answer: Olá, você pode alterar a action para retornar o que precisa, provavelmente o AntiforeryToken() também será um problema já que ele é ligado como default e suas chamadas retornarão erro 400. Se você não utilizar os recursos do Razor Pages talvez seja interessante usar o ASP.NET Core MVC, seria legal também atualizar e melhorar suas chamadas ajax.
Ex.:
Script: (Index.cshtml)
    @page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

Welcome

Learn about building Web apps with ASP.NET Core.

<form id="form-login">
    @Html.AntiForgeryToken()
    <input id="NumeroSerie" type="text" />
    <button type="submit">Submit</button>
</form>

@section scripts{

}

E na model:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApplication4.Pages
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public string NumeroSerie { get; set; }

        public void OnGet()
        {

        }

        public Task<JsonResult> OnPostAsync() {
            var result = ValidaAlgo();
            return Task.Run(()=> new JsonResult(result));
        }

        private string ValidaAlgo()
        {
            return NumeroSerie;
        }
    }
}


Commerce: Setting Custom Form Default Values

Question: I would like to set custom default values for both the Customer Shipping and Billing forms. I built a custom page/pane that occurs at the beginning of the Commerce Checkout process. This page/pane has 5 fields that pull basic user information before depositing the user at the 'express' checkout form (part 2 in the multi-step form -- or better known as the typical Shipping/Billing forms). My objective is to be able to use the data saved in $form_state['order']->data; in order to pass it into the default_values in certain textfields within the Shipping/Billing forms.
Using hook_form_alter does nothing to modify the Shipping/Billing in either $form_state or $form. There doesn't appear to be a declaration of default_value within the forms. Even if I do declare a value/values, it does not show up on the page. Any ideas?
Answer: The trick is to use
function hook_field_widget_addressfield_standard_form_alter(&$element, &$form_state, &$context) { }
Comment: This is a known issue for the addressfield module, and was solved via v1.2. See: https://www.drupal.org/node/2392855


How to Find the Square Root of -1 in mod 1130

Question: I am currently taking an introductory abstract algebra course and I am at a loss as to how to start approaching this problem (I find myself struggling in this field so far). I am currently being asked in this exercise to find the square root of -1 in mod 1130 given the fact that we know that:
    $$ 1130 = (17^2) + (29^2)$$
Can anyone please walk me through the steps for the solution? I apologize for the formatting of the numbers as I do not know how to have them displayed in mathematical symbols and numbers on this site.
Thank you.
Comment: Do you know about inverses modulo $m$? We get "lucky," since $(29)(39)=1131$.
Comment: I do not, could you possibly expand a little on it for me?
Answer: We have $17^2\equiv -(29)^2\pmod{1130}$.  Let $c$ be the inverse of $29$ modulo $1130$. It so happens that $c$ can be taken to be $39$.  Then multiplying through by $c^2$ we get $(39\cdot 17)^2\equiv -1\pmod{1130}$.
Remark: When $a$ is relatively prime to $m$, finding the inverse of $a$ modulo $m$ can be done quite efficiently using the Extended Euclidean Algorithm.
If we are given a representation of $m$ as a sum $x^2+y^2$, where $x$ and $y$ are relatively prime to $m$, we can use the procedure of the main post to solve the congruence $w^2\equiv -1\pmod{m}$.


SVG mouseover does not work on nested elements

Question: I would like to make it so that when you hover over a nested group #sec7kpi-c and then further into the text inside the animation effect when you mouseover continues.
<g transform="matrix(1 0 0 1 150 150)" id="sec7kpi">
  <g transform="matrix(1 0 0 1 0 0)" id="sec7kpi-c">
    <ellipse fill="#372356" stroke="#27AE60" stroke-width="16" stroke-miterlimit="10" cx="0" cy="0" rx="71" ry="71" />
    <text id="sec7text" x="-33" y="15" fill="#27AE60" font-family="LatoRegular" font-size="38.8363">KPI</text>
  </g>
</g>
<animateTransform attributeType="XML"
                  xlink:href="#sec7kpi-c"
                  attributeName="transform"
                  type="scale"
                  dur="1s"
                  from="1"
                  to="2"
                  restart="whenNotActive"
                  begin="mouseover"
                  calcMode="spline"
                  values="1;1.5;1"
                  keyTimes="0;0.5;1"
                  keySplines=".16,.59,.46,.98;.88,.27,.37,1.52"
                  fill="freeze"
                  id="c-hover">
</animateTransform>

Answer: You can set the text pointer-events property to none to avoid this.
Note that your keySplines values are invalid (they must all be <= 1) so your animation should not work as written (if it does you should raise a bug on that UA). I've corrected that in my version.
Also I've removed the from and to attributes as they are ignored if you provide a values attribute.

body, html {
  width: 100%;
  height: 100%;
}
<svg width="100%" height="100%">
  <g transform="matrix(1 0 0 1 150 150)" id="sec7kpi">
    <g transform="matrix(1 0 0 1 0 0)" id="sec7kpi-c">
      <ellipse fill="#372356" stroke="#27AE60" stroke-width="16" stroke-miterlimit="10" cx="0" cy="0" rx="71" ry="71" />
      <text id="sec7text" x="-33" y="15" fill="#27AE60" font-family="LatoRegular" font-size="38.8363" pointer-events="none">KPI</text>
    </g>
  </g>
  <animateTransform attributeType="XML"
                    xlink:href="#sec7kpi-c"
                    attributeName="transform"
                    type="scale"
                    dur="1s"
                    restart="whenNotActive"
                    begin="mouseover"
                    calcMode="spline"
                    values="1;1.5;1"
                    keyTimes="0;0.5;1"
                    keySplines=".16,.59,.46,.98;.88,.27,.37,1"
                    fill="freeze"
                    id="c-hover">
  </animateTransform>
</svg>


is_specialization type trait for a static constexpr member

Question: I need a type trait that determines if a class is a specialization of a given template. This answer provides an implementation that works in most cases.
However, it does not seem to work for static constexpr member types. In the following example (also available on wandbox), the last static_assert fails on Clang and GCC trunk:
<code>#include <type_traits>

// from https://stackoverflow.com/questions/16337610/how-to-know-if-a-type-is-a-specialization-of-stdvector
template<typename Test, template<typename...> class Ref>
struct is_specialization : std::false_type {};

template<template<typename...> class Ref, typename... Args>
struct is_specialization<Ref<Args...>, Ref>: std::true_type {};

template<typename T>
struct bar {
  bool x;
};

struct foo {
  bar<int> y;
  static constexpr bar<bool> z{true};
};

int main() {
  static_assert(is_specialization<decltype(foo::y), bar>{});
  static_assert(is_specialization<decltype(foo::z), bar>{});
}
</code>
I have two questions: is this correct behavior, and how can I write a type trait that will work when I refer to the type of a static constexpr member?
Answer: I just discovered that works if you decay the type of the static constexpr member to strip the cv-qualifiers.
<code>static_assert(is_specialization<std::decay_t<decltype(foo::z)>, bar>{});
</code>


If $\sum_{n=1}^\infty|x_{n+1}-x_n|$ converges, show that $\lim_{n\to\infty} x_n$ exists.

Question:
Question: If $\sum_{n=1}^\infty|x_{n+1}-x_n|$ converges, show that $\lim_{n\to\infty} x_n$ exists.

Solution: Let $(a_m)_{m\ge 1}$ be the series defined by the partial sum $$a_m=\sum_{n=1}^m (x_{n+1}-x_n), \forall m\in\mathbb{N}.$$ Note that by our definition, it follows that $$a_m=x_{m+1}-x_1, \forall m\in\mathbb{N}.$$ Now since it is given that $\sum_{n=1}^\infty|x_{n+1}-x_n|$ converges, implies that the series $(a_m)_{m\ge 1}$ is absolutely convergent, which in turn implies that $(a_m)_{m\ge 1}$ is convergent. From here we can conclude that the sequence $(x_{m+1}-x_1)_{m\ge 1}$ converges, which implies that the sequence $(x_{m+1})_{m\ge 1}$ converges, that is, the sequence $(x_k)_{k\ge 1}$ converges. Hence we are done.
Is this solution correct and rigorous enough and is there any other way to solve this problem (possibly without using absolute convergence)?
Comment: I guess I have never mentioned that in the solution, rather I have mentioned that since $\sum (x_{n+1}-x_n)$ converges, implies that $(x_{m+1}-x_1)_{m\ge 1}$ converges.
Comment: Ok, that was my mistake. What you have written makes sense then.
Comment: not a proof but a potentially fruitful thought: since $\sum_{n\ge1}|x_{n+1}-x_n|$ converges, we have $\lim_{n\to\infty}|x_{n+1}-x_n|=0$. That's all I can think of for now
Answer: The solution is correct, the most important step is to derive convergence from absolute convergence,I think this is the most concise solution. For another way, you can prove that $x_{n}$ is a Cauchy sequence by conditions, and then get the conclusion. But I think there is no essential difference between the two solutions.


Computing an infinite product $\prod_{n=1}^{\infty} \frac{1}{2}(1+\cos\frac{x}{2^n})$

Question: I would like to compute the infinite product
$\displaystyle f(x)=\prod_{n=1}^{N\rightarrow\infty} \frac{1}{2}\left({1+\cos\frac{x}{2^n}}\right)$ for a given real $x$.
Since the terms in the product are positive and smaller than $1$, the product is bounded by $0$ and decreases. Therefore the limit $N\rightarrow\infty$ is well defined.
I know that
$\displaystyle \prod_{n=1}^{\infty} \cos\frac{x}{2^n}=\frac{\sin(x)}{x}$ and I wonder if $f$ also has a simple analytical expression.
Thank you.
EDIT : Using the expression $\cos^2(x)=(1+\cos(2x)/2)$ I can reducethe first sum to the second and get
$f(x)=\left(\frac{\sin(x)}{x \cos(x/2)}\right)^2$
Comment: Thanks for spotting the mistake, I edited.
Comment: Wolfram [says](http://www.wolframalpha.com/input/?i=Product+(1%2BCos%5Bx%2F2%5Ek%5D)%2F2) it's actually: $$\prod_{n=0}^\infty \frac{1}{2} \left( 1+\cos \frac{x}{2^n} \right)=\frac{\sin^2 x}{x^2}$$ if we start with $n=0$, not $n=1$
Comment: Yes, thanks, I solved it by reducing to the known product (I have edited with the answer)
Comment: Well, I've already posted an answer, hope you don't mind
Answer: Take the well known product and square:
$$\prod_{n=1}^{\infty} \cos\frac{x}{2^n}=\frac{\sin(x)}{x}$$
$$\prod_{n=1}^{\infty} \cos^2\frac{x}{2^n}=\frac{\sin^2(x)}{x^2}$$
Now use the formula:
$$\cos^2 \frac{t}{2}=\frac{1}{2} (1+\cos t)$$
To get:
$$\prod_{n=0}^\infty \frac{1}{2} \left( 1+\cos \frac{x}{2^n} \right)=\frac{\sin^2 x}{x^2}$$


Jquery click code being called multiple times

Question: I tried adding my code into a fiddle and it works fine in there so please, try to analyze it straight on my site.
Here is the page: http://cacharro.ole32.com/shopping/
if you go to groceries.js, at line 39 there is the code for the clic event on the #addNewSection image.
then in the page you click in the big gree + buton, a formulary will pop up, and click again in the big green + symbol. You'll notice that the code inside the .click() function is called more than once..
does anyone knows why ??
EDIT:
I found the source of my error. Y added the hooking to the event in a function called init, something like:
function init() {
     $("#addNewSection").click( function(e){
          newSectionButtonClicked();
     });
}

and added a call in the $(function() .... BUT I also call this init() from other sites so everytime I call it a new instance of the function is hooked to the click event!! Is there a way to hook on the event only if we are not hooked already????
Comment: can you share the click event code.
Comment: @javirs pls check my code
Comment: for doing action only once you can use boolean variable var isInitialize = false; and check it function init(){ if (isInitialize) return; isInitialize = true;
Answer: You should call init() function only 1 time, or remove the assignment of click event inside this function and put in in a function that will be called only one time, for example:
$("#addNewSection").click( function(e){
  newSectionButtonClicked();
});

this function is called every time you call the init() function, so this event will be trigged one more time for every init() you call.
You should call this registration only one time
Comment: That was my first guess as well, but using a breakpoint shows that the init() is run just once
Comment: i've put a lot of breakpoint and i pass through init() more times, i'll check again
Comment: this is definitelly what Im doing .. init is called more than once. and the hooking is done more than once. Is there a way to check if we are already hooked ??? I will clean up my code to hook in a differente function but .. is there a way to check that ??
Comment: or.. is there a way to delete the old hooks ??
Comment: with $('#NAME').off('click'); you can remove the old handler
Answer: Is your code registering the click handler more than one time on the same element. If so try to check the code. This is the situation which i have also faced. for first time click called once, for second time twice and so on every click register an a click handler on the same handler.
Also if you can show us the code for review.
Answer: function drawMarket(){
    $("#market").html("
");
    $.each(sections, function(idx, obj){
        var name = htmlDecode(obj.Name);
        var listItem = $('
');
        listItem.append(name);
        var innerComponent = $("
");

            var ItemName = htmlDecode(ItemObj.Name);
            innerComponent.append("
"+ItemName+"
");

        listItem.append(innerComponent);
        listItem.append("
");
        $("#marketList").append(listItem);
    });
    init();
}

Please replace this function inside your groceries.js  it will help you
You don't need to each loop inside this function because it will always append inner text
Comment: Sorry, I dont get it... I have sections and every section has items. The outer each loops for every section. and for every section I want to add every item it contains. There is no way to avoid the inner loop.
Comment: can you try this once and see results
Comment: ItemObj will be unknown .. isnt it ?
Comment: yes I did and, as expected, ItemObj is NULL, never filled with nothing, ItemObj.Name is unknown, `Uncaught ReferenceError: ItemObj is not defined `
Answer: You call function drawMarket() in the newSectionButtonClicked() each time when you click on the plus button, and call init() function in the drawMarket(), so you define click event many times
You can do something like this for make only one initial definithion:
jQuery(document).ready(function() {
    $("#addNewSection").click( function(e){
        newSectionButtonClicked();
    });
});

or
jQuery(document).ready(function() {
    init();
});


language back to default language after Ajax reload

Question: To simplify the question and maybe reproduce the problem, I made a simplier version of what I am doing. I have a form field with ajax. When it triggers it reloads a small piece of html. In it is t('text in one of tree languages'); If I open the page for the first time the same html is loaded and it is in the correct language. But after the reload from the ajax call it is in the website's default language. This only happens when logged in. It is possible that this has to do with the administrator language module. Any help would very much be appreciated.
Ajax Code at hook_form
function hook_form($form, &$form_state) {
  $form['update'] = array(
    '#value' => t('Update'),
    '#type' => 'button',
    '#ajax' => array(
              'callback' => 'callback_function',
              'wrapper' => 'div-to-replace',
              'method' => 'replace',
              'effect' => 'fade')
  );

  // Other form elements

}

Ajax callback function
function callback_function($form, $form_state) {
    return t('test string that should get translated');
}

Comment: Could you add the code you use for the ajax integration in your form? How is the language negotiation configured (in URL, session, browser, ...)?
Comment: I have added the code. I use url detection for the language. nl/de/en
Answer: The ajax callback should return the dynamic form element (and not directly the value). I've created some sample code where the translated content / string is correct after an ajax reload.
function YOURMODULE_form($form, &$form_state, $file_group)
{
    $form['update'] = array(
        '#value' => t('Update'),
        '#type' => 'button',
        '#ajax' => array(
            'callback' => 'YOURMODULE_form_ajax_cb',
            'wrapper' => 'ajaxWrapper',
            'method' => 'replace',
            'effect' => 'fade'
        )
    );

    $form['ajax'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => 'ajaxWrapper',
        ),
    );

    $form['ajax']['text'] = array(
        '#type' => 'markup',
        '#markup' => t('My translated string'),
    );

    // Rest of the form
}

function YOURMODULE_form_ajax_cb($form, &$form_state)
{
    return $form['ajax'];
}

Comment: No this is not is. I found the problem all i need now is a sollution. I added the problem to my original question.
Comment: If you disable the `administration language` module, do you still have the same problem? When Drupal executes the ajax, does the language is included in the URL request? (i.e.: /nl/system/ajax/)
Comment: I removed system/ajax from the basic configuration. This however is likely to cause problems when making ajax calls on administrator pages wehere administrator language should be used.
Answer: I see in my installations that when i disable the administration language module, the problem is solved :)
Answer: $referrer = explode('/', $_SERVER['HTTP_REFERER']);
$current_lang = $referrer[5];

This can solve your problem
Answer: Having the same problem. On ajax callback t function is complealty ignored and strings are not even on TI.  I can enforce them to appear in TI using locale function, but then I also need to pass language to it. What is the real problem is that I can't pass language to ajax callback, whenever I try to pass it, it goes to default english.
Comment: This is not an answer.


Unable to send data to ThingsBoard gateway through MQTT

Question: I have installed ThingsBoard server on one PC (UBUNTU16.04) and ThingsBoard Gateway on another PC(UBUNTU18.04) ,In order to send data to ThingsBoard Gateway I installed Mosquitto MQTT broker on another PC.I followed configuration guides to connect broker to Gateway as well as server (using access token and host ip).
I connected temperature sensor to ESP32. While I am trying to send the data to gateway through MQTT the data is not getting to the gateway.The topic I used here is "v1/gateway/telemetry" in order to publish the data.
Can we use Gateway Device ID to send data?
How can I send data either by using topic or by using device id or by using device access token?(from device)
All the PC 's are connected to the same network(Private network).
I am facing this issue can Someone please sort it out...
Answer: You need to create a Proxy Layer Between MQTT Broker and your server.
<code>var mqtt = require('mqtt'), url = require('url');
var client = mqtt.connect('mqtt://localhost:1883',
{
username: '<username>',
password: '<password>'
});

console.log("Connected to MQTT Broker:- localhost" + client.toString());
var awsIot = require('aws-iot-device-sdk');
var device = awsIot.device({

keyPath:  Certificate key file path,
certPath: Certificate file path,
caPath:   Certificate root file path,
clientId: AWS Thing Name,
region:   AWS IoT Broker region,
});

device.on('connect', function ()
{
console.log("Connected to AWS IoT Broker:- " + device.toString());
});

client.on('connect', function()
{
//subscribe to a topic (#)
client.subscribe('#', function ()
{
client.on('message', function (topic, message, packet) {
console.log("Received :-" + message + " on " + topic);
device.publish(topic, message);
console.log("Sent :-" + message + " on " + topic);
});
});
});
</code>
Something like this might help you.
Comment: Thank you for reply,I have seen AWS in your code which I am not understanding.I installed ThingsBoard server on premise,I mean it is not deployed on cloud.


Redis, find by hash, find by field value

Question: I want to create hashes with books info in redis, for instance:
HMSET books key "83-7197-669-0" title "Access. DB desing"  price 79.0 publisher "Helion" year 2002
 HMSET books key "83-7197-786-7" title "Access XP"  price 65.0 publisher "Helion" year 2003
Then I just want to find a book with a key 83-7197-669-0, I tried:
1) HGET books key "83-7197-669-0"
(error) ERR wrong number of arguments for 'hget' command
2) HGETALL books
 1) "key"
 2) "83-7197-786-7"
 3) "title"
 4) "Access XP"
 5) "price"
 6) "65.0"
 7) "publisher"
 8) "Helion"
 9) "year"
10) "2003"

I dont know why, but I see here only the second book ..
Next, I wanted to find a book with a given price, with no success. I dont even know what to try. Any ideas?
Comment: @tabreaz answer is the valid solution for your requirements, but if you'll need to "find by field value" in the future you should check the RediSearch module
Comment: The reason `HGETALL` returns only the second book is because your second `HMSET` overwrote the fields in the `books` key. If you want to keep them separate, treat `books:` as a namespace and add indexes (which you can manage with `INC` or `HINCRBY`). So it should be `HMSET books:1 ...` and `HMSET books:2 ...`. Then you can use `HGETALL books:1` and `HGETALL books:2`. Your application logic would have to handle looping the index.
Answer: HSET in redis is like a MAP of MAP, where the books in your example is the key of outer map, where as the key, title, price, and other fields are like keys of inner map.
To get book by key, you can set key as HSET name which and use HGET key to get the book by key.
HMSET books:83-7197-669-0 title "Access. DB desing"  price 79.0 publisher "Helion" year 2002

HGETALL books:83-7197-669-0

should return all the fields of the HSET. I hope this gives you good start to redis Hashes.
Comment: No from the above structure, if you want to get books by price range you have to consider storing them in sorted set (ZSET, which is sorted by scores which can be price in this case). Similar to Indexes in RDBMS, you have to index them in other sets and query back the actual rows by keys.

`ZSET books  83-7197-669-0`
then you use `ZRANGEBYSCORE books 70.0 80.0` this will return all the books within that price range.

Then you can take the id's and hit HGETALL books: good read on this [https://redis.io/topics/indexes]
Comment: But it is possible to find a book with a given price then?
Comment: OK, I found a way: `HGET key:"83-7197-786-7" price `
Comment: `127.0.0.1:6379> HMSET books:83-7197-669-0 title "Access. DB desing"  price 79.0 publisher "Helion" year 2002
OK
127.0.0.1:6379> zadd books 79.0 books:83-7197-669-0
(integer) 0
127.0.0.1:6379> zrangebyscore books 79.0 79.0
1) "books:83-7197-669-0"
127.0.0.1:6379> HGETALL "books:83-7197-669-0"
1) "title"
2) "Access. DB desing"
3) "price"
4) "79.0"
5) "publisher"
6) "Helion"
7) "year"
8) "2002"`
Answer: As you probably see, you are having all those attributes like "key" and "title" in your Redis hash.
Solution is simple, just omit the key and store rest of the data in serialized form. Redis is basically key-value store on steroids, so turn the first command to
HMSET "83-7197-669-0" title <title> price <price> ...
Depending on your use case, you could also use hset, store everything in books and encode values as a single serialized entry.
If you are looking way to access Redis through multiple keys, you are likely using a wrong tool. Relational data stores are better for that; Redis is still high-speed key-value store with some nice extra stuff baked in.


How can I show an input when a checkbox is checked?

Question: I'm using React an got a problem.
The problem is to show an <input type="text"> under a checkbox if this checkbox isChecked. I tried
option.checked ? <input type="text" id={`input_${'option.name'}` name={`name_${'option.name'}`> : null

but it doesn't work.
I got an example of my code sandbox
Answer: It's working. You just need an empty React Fragment to enclose the tags.
{
  options.map((option, index) => (
    <>
      <Checkbox
        key={option.name}
        isChecked={option.checked}
        checkHandler={() => updateCheckStatus(index)}
        label={option.name}
        index={index}
      />
      {option.checked ? (
        <input
          type="text"
          id={`input_${option.name}`}
          name={`name_${option.name}`}
        />
      ) : null}
    </>
  ));
}

and to your second question, you can simply use filter and map to take out only selected options.
const handlePrintResults = () => {
  // Filter only checked options
  const onlyChecked = options.filter((e) => e.checked);

  // Take out only the names of it
  const values = onlyChecked.map((e) => document.getElementById(`input_${e.name}`).value);

  console.log(values);
};

// Add an onClick listener for the button
<button onClick={handlePrintResults}>Print result</button>

Comment: thank you so much for your help. It just works fine. You know any way to also `console.log` the value of the `` if the checkbox is checked?
Comment: added the same in the answer.
Comment: Your answer just logs the name of the `checked` checkboxes but not the value of the ´´ or am I wrong?
Comment: Check now.. You can fetch it using `getElementById()`


ipv6 multiple addresses and firewall on remote machine

Question: I have an ubuntu server (serverA) which has a couple of IPv6 addresses. One of these is based on it's MAC address, and is known to the network, the other one I presume ubuntu created as a 'private' address which hides the MAC address.
I have another server (serverB) which hosts a database, and requires an incoming connection from serverA. serverB has a firewall, only allowing incoming connections from serverA. I've specified serverA's MAC-based IP address in serverB's firewall exceptions, but not knowing the private address, didn't add this in. However, packers from serverA seem to be defaulting to come from the private address.
Is the private address deterministic? How can I disable it? Should I disable it?
Answer: The privacy address is supposed to be random, and change often.  It shouldn't be deterministic; that would be antithetical to the concept.  It should be used for outgoing connections.
I don't recommend disabling it, because it is useful for not disclosing your MAC like the SLAAC (the proper term for the MAC-derived address) does.  However, some people who value the ability to determine which host made a connection later on prefer to disable it.
If you must use IP-based ACLs, you're going to have to disable it.  You can do so by adding ip6-privacy=0 to the ipv6 section of /etc/NetworkManager/system/connections/.  You may also want to inspect /etc/sysctl.d/10-ipv6-privacy.conf if that doesn't put a stop to it.
Comment: You mention IP-based ACLs - are there any alternatives at the network/firewall level? Would a DNS-based firewall be any better in this case, as the private address is not static, hence not ideal for DNS? Are you suggesting dropping the firewall and relying on application-level security?
Comment: I find that there is only very rarely any reasonable use case for *egress* IP-based ACLs.  If you happen to have one, you probably can't use ipv6 privacy extensions is all.  You could certainly assign a static address that is not a SLAAC, though really this is no better than using the SLAAC from a security standpoint.
Comment: I don't care about the egress from serverA; it is the ingres ACL on serverB that was causing the issue.
Answer: I will focus on your last question: Should you disable private addresses?
I agree with @Falcon that Privacy Extensions as defined in RFC 4941 are useful. I would always enable them on clients/workstations that may connect to services on the Internet, and I hope mobile phone producers will soon enable them per default on all their devices.
But in your setup, you are talking about two servers, where one of them is (not only, I assume) acting as a client to the other server. First questions would be: What is your setup? Are these servers within your company network? What external access will they have? Will serverA ever connect to the Internet (without a proxy)? If all traffic is internal and you do not see a threat by an adversary that maps your internal network traffic patterns, just disable Privacy Extensions on the servers. A server must by definition have at least one address that is well-known to its clients, mostly via DNS, so an attacker can use this address to attack the server. Hiding its address is not a valid attack mitigation strategy for a server. (Placing load balancers in front with its address is, of course.)
The US "DoD IPv6 Standard Profiles For IPv6 Capable Products" (sorry, I could not find a link to a version newer than 5.0) also demand Privacy Extensions for hosts/workstations "that will operate on networks requiring privacy address extensions or otherwise need to maintain anonymity" and strongly recommend them for other hosts/workstations. This requirement goes for servers only if they also act as clients (as in your setup) and need to maintain anonymity (which you must decide). So, the general server does not need Privacy Extensions activated.
Concerning the ACLs: If hard-coded IPv6 addresses must be used in several places, I would even consider defining fixed IPv6 addresses on your servers. You can set them on the servers and DNS or distribute them via DHCPv6, but you will have less work, compared to SLAAC addresses, if you ever have to replace a NIC or a server.
So, in short: If your servers only communicate internally and do not have advanced security requirements against traffic analysis, you should disable Privacy Extensions. In any other case, you must balance your pros and cons.
HTH.
Comment: Thanks; serverA will connect to the Internet occasionally. Both servers are virtual so movement isn't really a problem, but I think I'll move to a static, non-SLAAC address.
Answer: Hello from 10 years later...
if serverA and serverB are in the same company's network (even if that is subdivided with firewalls), it could be possible to create "private" addresses in fd00::/8 network (or subnets thereof)
E.g., if serverA got additional address  fd00::a and  serverB got additional address fd00::b, and the routes are defined appropriately for fd00::/8, then serverA reaching serverB by that fd00-address will let it show up with its own static fd00-adress,   whereas any connections to the outside (e.g. google.com at 2a00:1450:4016:80b::200e) would then still use the non-constant private dynamic addresses.


Date in Firebase displays as yyyy-mm-dd format whereas form date is dd-mm-yyyy

Question: I have a problem my data that I submit in the Firebase Database is submitted  as yyyy-mm-dd  which is the date whereas the date in the form is dd-mm-yyyy.
I used slice in order to get the necessary 000z which worked but when I want to display the date it will not display because of the stored date in Firebase which is in the yyyy-mm-dd format.
Does anybody know how change the format submitted to firebase or any other way to get the date in the form like it was set?
Comment: In your JavaScript you should keep all dates as either ISO8601 format or as date structures using the Date object or a moment using Momentjs. Submitting to the server should occur using ISO8601. The **presentation layer** can then show the date in whatever format you want using the various built in date filter settings in Angular. In the database it should **always** persisted as a DateTime type.
Comment: dateofbirth: user.date.toJSON().slice(0, 10).toString(),      this what i use to push the date dateofbirth:
"2016-02-12"
 this is what is the output in the db  i had a look at moment.js but  what is the best way to do it so I can  return the date in case it needs to be edited
Comment: don't use `slice` or `toString` on date values.  if you are using a JavaScript `Date` object, the date is stored as the number of milliseconds since midnight Jan 1 1970.  This can then be formatted however you like.
Answer: Try this in your  HTML template binding, see if it works.
{{date_expression (e.g 1288323623006) | date:'dd-MM-yyyy HH:mm:ss Z'}}


Remote Root Login

Question: I know one of the first things you do to secure a server is disallowing remote root login.
Passwords are pretty weak; what do people think of only allowing root login via ssh keys or other password-less methods.
Which methods are the best?
Is it better just not to risk it?
Is ssh-ing with a secondary account and using su - really adding any security?
How do people on serverfault.com access root on a remote server?
Answer: For the most part there is little gained by actually disabling remote root logins.  It marginally helps enforce a policy that admins log in via their own accounts and su to root as necessary (or use sudo possibly with sudosh ... depending on your policies).
Creating extremely long and cumbersome root passwords (effective so long as you're not still using the ancient DES+12-bit salt hashing for your passwords) is about as effective at enforcing such a policy.
One site with which I'm familiar had a system whereby the unique passwords were randomly generated for each host, stored in a database, and pushed out to the systems.  Admins were required to use ssh with their normal accounts, and sudo for most operations.  However, the root password was accessible to them via an SSL based internal web service (which further required their RSA SecurID token and PIN).  Fetching a root password entailed entering a justification (usually a link to a Remedy(TM) ticket number) and accesses where periodically audited.  One of the few acceptable reasons for using the root password directly were in those cases where a system was stopped on fsck during the boot process ... and sulogin was requiring a real root password in order to manually run filesystem check and repair processes.  (There was some discussion of alternative methods for this --- which are relatively easy for Linux, but get far more difficult as you try to extend your procedures to account for the many legacy HP-UX, AIX and older SunOS and Solaris systems that were still in production in that environment).
There are corner cases where a root password is necessary --- or at least is the best available alternative.  Keeping it available while making it sufficiently robust against the sorts of threats you can anticipate is generally your best strategy.
Another site that I know of has a rather elegant approach to decentralized account management.  They have user-* and sudo-* packages (think RPMs) which are installed into the systems using the normal package management procedures and automation infrastructure.  In their case the sudo-* package has a dependency on the corresponding user-* package.  This is nice because it allows you to have clusters of machines with localized accounts (all accounts are admins, developers, support staff or "headless" accounts) and eliminates dependency on LDAP/NIS or other networked identity and authentication services.  (This reduces the coupling among systems makes them significantly more robust).
One think I like about that approach is that it gives flexibility.  Anyone with sudo access can issue a command to add a normal user or another sudo user account.  So, if I'm working on a ticket any of the people who already have access to a system can easily give me access.  There's no delays while a ticket to add me to some access control list in some central database grinds through some centralized approval process and finally propagates a change back out to the system in question.  Any of the authorized sudo-ers on the system can give me access and later remove me.  (Yes if I were evil and they game me sudo I could maliciously modify things to retain access ... in fact there are some things I could do just as a normal user to retain access past such removal.  However, that's not the threat they're worried about.  My access is still limited to a relatively smaller number of systems overall; so the impact of a compromised account is still more limited than most similar schemes I've seen.
Answer: If you disable remote root access them you prevent remote attackers from directly getting root - they have to break another account, get access to the machine, and then try and get access to root. It's an extra step.
Generally root is disabled for remote access. SU works well. If something really breaks there is always direct access to the box to fix it.
If you want to be stricter - just disable root entirely, it's what sudo is there for. Again, with that approach you can still get root access by dropping to single-user mode - a la Ubuntu. Although, I believe they used a patched init for that, as per their docs.
In addition you can setup idled to kick off idle users in case their terminals are left open, and PCs are open too. You can force all users to use keys, but key management can be difficult.
A single pass-through logging host as a breakglass type system also forced an additional layer of protection and an audit trail.
Answer: I suggest that you setup the system to allow root access ONLY at the console.
Otherwise, using sudo with the password option, allow selected users access to priv'd commands. BTW, realize that sudo can be designed to restrict a user account to certain commands if you wish.  Sudo, leaves a "mark" in the system log that it was used.  sudo is better than su because the root password does not get disclosed.  Thus you can change the root password and the user using sudo would not be any wiser.
The allowed use of sudo to get to priv'd commands should be accompanied by forced periodic password changes with the frequency depending on the environment.
Comment: I feel like the problem with sudo is that it uses the user's normal password. Because of this, if the account is compromised, then root access is just a 'sudo -s' away. Using 'su' requires the attacker break two passwords.
Comment: Also, I will need some sort of remote root access because it's a hosted server, and I don't have access to the physical console.
Comment: If I recall, you can configure sudo to use the password of another account other than the users' account.
Answer: never allow root
set up the system to allow access via  keys only no passwords
then set up sudo for users allowed to make changes via root account
Comment: While I agree for most situations, there are certain times that I feel alright in allowing remote root access (particularly using keys)
Comment: i would rather take the extra time to sudo in to do something than have root access to machine , even w a key

from just a quick glance at any live server auth logs one usually sees the root login being used to try to gain access to the box, at around a 90% of all login attempts!

if you have any info on a box you dont want just anyone to get access to its just in bad form to leave a box open to root
Comment: On a desktop, yes. But on a server administrated by a single user, use of sudo is a bit like playing "simon says". IMO only if you have multiple admins and you want/need their actions logged, then use of sudo users is legit. Even then, I'm not convinced that disabling root is required (although limiting remote root logins to key only is wise).

Remote Root Login


Can I remove Zen Default Regions if Im not using them

Question: I want to remove regions such as 'navigation' & 'highlighted' from structure/blocks just so I can visually see what is in use, and not have a list of Blocks im not using sitting there.
Answer: You cannot remove regions that have blocks in them - at least not without consequences. If you will do so, blocks will disappear and there is a chance for Drupal and PHP errors. To get rid of unneeded regions, you need to proceed in that order:

Remove all blocks from them
Remove them from .tpl files, to be sure nothing will try to render region that does not exist anymore
Now you can delete them from .info file
Answer: You can remove entire regions by taking them out of your .info file for that theme. Your .info file will be located in the Zen theme folder and should be called zen.info. Open your .info file and remove the line that states:
regions[navigation]     = Navigation bar
If you want to keep things clean and orderly, you should also remove any call to those regions in any page.tpl.php files you have. They'll look something like:
<?php print $header ?>

And you may want to make a custom theme of your own if you plan on making a bunch of modifications.


Evaluating fitlm (linear model) in matlab on a separate test set

Question: I've built a linear model with Matlab using fitlm to predict the next value in a series of doubles. Now I would like to test this model on a different dataset so I get accuracy, p-value etc.
I've used predict, but that just outputs a prediction curve and a confidence interval.
How do I get an accuracy for this new data? What would be the correct way to evaluate this model on the test set? Could I somehow specify the testset when I am building fitlm in the first place?
I know this can be done in packages such as Weka, so I was wondering about the options in Matlab.
Answer: You could compute the mean squared error on the test set,
<code>testmse = mean(Ytest - predict(lm,Xtest)).^2
</code>
and compare it with the mse that is computed from the training data in the original model.
This function does ordinary least squares. It uses classical statistical approaches to adjust mse for the number of parameters in the model, perform t and F tests, and compute an adjusted R-square. It doesn't do regularization and it takes the model as given. So it doesn't take a test set.
Your ideas are interesting and could help you build up the model that you specify to fitlm. For example, you could watch the relationship between the computed mse and testmse as you add more terms to the model. I haven't seen this done (of course I haven't seen everything), but it seems plausible.
Comment: Thanks, that's an interesting idea. It does seem like the extra data could be used to help build the model, have to think about that...


Probability of 2 appear before 3 or 5?

Question:
Independent trial consisting of rolling a fair die perform. What is the probability of $2$ appear before $3$ or $5$??

Well, different explanation of the same question is available on some sites......But I could not figure out what's been asking for? And is there only one trial of rolling?
Comment: the question is far to be clear, so it cannot be uniquely interpreted. The probability, as you said, depends on the number of trials. If this number is not specified then it is meaningless.
Answer: We are repeatedly rolling a die until one of $2$, $3$, or $5$ appears. If it is a $2$ we have won. The probability that this is the case is ${1\over3}$, by symmetry.
Comment: This is easy to understand. Thanks for ur time.

Probability of 2 appear before 3 or 5?


For arbitary dimensions, showing that the square root of the identity matrix is diagonalizable

Question: For arbitrary size, let $A$ be a square matrix such that $A^2=I$ where $I$ is the identity matrix. Then how do I show that $A$ is diagonalizable? Also, is $A$ diagonalizable when $A^2=B$ for some arbitrary diagonalizable matrix $B$?
Comment: You have a polynomial that annihilates $A$. The minimal polynomial must by definition be a divisor of it.
Comment: What are its possible minimal polynomials?
Comment: I cannot see how to get the minimal polynomial of $A$ from that of $I$.
Comment: Oh, (on the premise that $A$ is not a multiple of $I$), the minimal polynomial for $A$ must be $t^2-1$. Now I see that $A$ must be diagonalizable. How about more general case $B$?
Comment: That's only one possibility for the minimal polynomial when $A^2=I$. There are two others.
Answer: Every vector $x \in \mathbb{R}^n$ can be written as $x = \frac{1}{2}(x + Ax) + \frac{1}{2}(x - Ax)$ where $\frac{1}{2}(x + Ax)$ is in the eigenspace for $\lambda = 1$ and $\frac{1}{2}(x - Ax)$ is in the eigenspace for $\lambda = -1$.  Therefore, the eigenvectors for $\lambda = \pm 1$ span $\mathbb{R}^n$, implying that $A$ is diagonalizable.

More generally, we can apply a useful decomposition theorem: suppose $T \in L(V)$ is a linear operator, and we have pairwise relatively prime polynomials $p_1, \ldots, p_r \in F[t]$, where $F$ is the scalar field, and let $p(t) := p_1(t) \cdots p_r(t)$.  Then $\ker p(T) = \ker p_1(T) \oplus \cdots \oplus \ker p_r(T)$.
In this particular case, we can use $p_1(t) = t-1$, $p_2(t) = t+1$; so $p(t) = t^2-1$, $\ker p(A) = \ker 0 = \mathbb{R}^n$, and thus $\mathbb{R}^n = \ker(T-I) \oplus \ker(T+I)$.

(Do note, however, that these proofs only work if the scalar field does not have characteristic 2.  In fact, the statement is false over characteristic 2 scalar fields; for example, $\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}^2 = I$ in this case but $\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}$ is not diagonalizable.)
Answer: The polynomial $x^2-1$ annihilates $A$, so its minimal polynomial must be one of $x-1$, $x+1$ or $x^2-1=(x-1)(x+1)$. All of these are products of distinct linear factors, therefore $A$ is diagonalizable.
One the other hand, consider $B=-I_2$. For $A=\tiny{\begin{bmatrix}0&-1\\1&0\end{bmatrix}}$ we have $A^2=B$, but $A$ is not diagonalizable over the reals.
Answer: For every matrix $A$, there exists an invertible matrix $T$ such that $J:=TAT^{-1}$ is in Jordan form. It is then easily seen that
$$J^2 = TAT^{-1}TAT^{-1} = TA^2T^{-1} = TIT^{-1} = TT^{-1} = I$$
The diagonal of $J^2$ contains just the diagonal values of $J$ squared, therefore on the diagonal, so to get $I$, there can only be $1$ or $-1$ on the diagonal. It is also easily checked that on squaring, for each Jordan block, the subdiagonal is replaced by $2\lambda$ where $\lambda$ is the eigenvalue ($=$ value on the diagonal). But to be equal to the identity matrix, the subdiagonal of the square must be zero;but we've seen before that $\lambda=\pm1\ne 0$. Therefore the only way the condition can be fulfilled is if all Jordan blocks have no subdiagonal, that is, are of size $1$, which means that $J$ is actually a diagonal matrix. But that means that $A$ is diagonalizable.
Comment: Thank you for your answer. How about $A^2=B$ for some arbitrary diagonalizable $B$?
Comment: Oops there is a counterexample.
Answer: Let $K$ be an algebraically closed field with characteristic not $2$ and $A\in M_n(K)$ be  a diagonalizable invertible matrix. We consider the equation $(*)$ $X^2=A$ where $X\in M_n(K)$.
$\textbf{Proposition}$. Then $(*)$ has at least one  solution $X$ and each solution is diagonalizable.
$\textbf{Proof}$. We may assume that $A=diag(\lambda_1I_{i_1},\cdots,\lambda_kI_{i_k})$ where the $(\lambda_i)$ are non-zero distinct.
i) Thus, $2^k$ obvious solutions are $X=diag(\pm \sqrt{\lambda_1}I_{i_1},\cdots,\pm \sqrt{\lambda_k}I_{i_k})$. Obviously, the existence stands even if $A$ is singular.
ii) Conversely, $X$ is in the form $X=diag(X_1,\cdots,X_k)$ where ${X_j}^2=\lambda_jI_{i_j}$. If $X$ is not diagonalizable, then some $X_j$ is not diagonalizable; since we may assume that $\lambda_j=1$, that implies that there is $m\geq 2$ s.t. $(\pm I_m+J_m)^2=I_m$, where $J_m$ is the nilpotent Jordan matrix of dimension $m$. Note that $(\pm I_m+J_m)^2=I_m\pm 2J_m+{J_m}^2\not =I_m$ because $charac(K)\not= 2$. That is contradictory.  $\square$


Correct rewrite paths for .htaccess file for silex?

Question: I've just begun experimenting with silex. I'm following the documentation and am confused which way to go with the .htaccess paths. Some background:

I'm using WAMP for my dev webserver, with mod_rewrite enabled
I have the "slim" copy of Silex unzipped and copied to c:\wamp\www\silex\
I have the example hello world route in c:\wamp\www\silex\web\index.php
I have an .htaccess file that lives in the silex directory

The .htaccess file:
<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On
    RewriteBase /silex/web
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

If I go to localhost/silex/web/hello/world, I get a working "Hello world" page, which is great.
...but if I go to localhost/silex/hello/world, I get the silex error:

No route found for "GET /silex/hello/world"

That error makes sense to me... but does this mean that "web/" must be included in all of the site's URLs? Is that normal for silex apps?
Some questions come to mind:

Which directory should the .htaccess file be  in -- silex/ or silex/web/? Are there any problems I might run into with having it in either spot?
Should the RewriteBase go to /silex or /silex/web? (documentation vaguely says "/path/to/app"; to me that means /silex)
Answer: The Silex example assumes that web directory is set as document root of the virtual host.
You should have one VHOST per application, e.g. silex.local with a document root set to c:\wamp\www\silex\web. Then use the .htaccess example from the Silex site and put it into c:\wamp\www\silex\web\.htaccess.
Comment: And keep in mind for htaccess files to work at all you have to allow overriding the default settings by adding AllowOverride all in a  directive in your virtual host file.
Answer: Try this in /silex/.htaccess:
<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On
    RewriteBase /silex/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ web/index.php [L]
</IfModule>

Comment: That seems to produce the same results as what I have above. Is there a reason why this is better?
Comment: Yes, in general `RewriteBase` should match the relative directory of the .htaccess.
Comment: For testing comment out `RewriteCond` line and try `localhost/silex/hello/world` URL again.
Answer: If you don't have a DNS server use your local hosts file as a DNS :
note:
Make sure you apache mod_rewrite is enabled.
1: Add this to your hosts file:
linux /etc/hosts
windows c:\Windows\System32\drivers\etc\hosts

127.0.0.1   silex.local

2: Create a new virtual host ( i'm using apache ):
linux ( Centos )
/etc/httpd/conf/httpd.conf

<VirtualHost *:80>
    DocumentRoot /var/www/html/silex/
    ServerName silex.local
</VirtualHost>

windows ( WAMP )
c:\wamp\bin\apache\Apache2.6\conf\httpd.conf

<VirtualHost *:80>
    DocumentRoot C:/wamp/www/silex/
    ServerName silex.local
</VirtualHost>

3: Restart apache
4: In your silex root folder create .htaccess file :
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    RewriteRule ^(.*)$ web/index.php [QSA,L]
</IfModule>


Set up test with Jest, MongoDB and typescript using jest documentation

Question: When I try to set up a simple test file, as per the jest documentation I get a number of linter errors:

connection: Type 'Promise<MongoClient> & void' is missing the following properties from type '{ db: (arg0: any) => any; close: () => any; }': db, closets(2739)
globalThis.MONGO_URI_: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017)
useNewUrlParser: No overload matches this call. Overload 1 of 4, '(url: string, callback: Callback<MongoClient>): void', gave the following error. Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'Callback<MongoClient>'....
I've tried setting up a global.d.ts (as per these solutions) file with the following declarations in:
export interface globalThis {}
declare module globalThis {
    var __MONGO_URI__: string;
    var __MONGO_DB_NAME__: string;
}

export interface global {}
declare global {
    var __MONGO_URI__: string;
    var __MONGO_DB_NAME__: string;
}

I think this solved the globalThis.__MONGO_URI__ error previously, but I've turned VS Code back on and the error has re-appeared.
package.json dependencies:
 "dependencies": {
    "cross-env": "^7.0.3",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "node-cron": "^3.0.0",
    "snoostorm": "^1.5.2",
    "snoowrap": "^1.23.0",
    "mongodb": "^4.6.0"
  },
  "devDependencies": {
    "@babel/core": "^7.18.2",
    "@babel/preset-env": "^7.18.2",
    "@babel/preset-typescript": "^7.17.12",
    "@shelf/jest-mongodb": "^3.0.1",
    "@types/express": "^4.17.13",
    "@types/jest": "^27.5.1",
    "@types/mongodb": "^4.0.7",
    "@types/node": "^17.0.36",
    "@types/node-cron": "^3.0.1",
    "@types/request": "^2.48.8",
    "jest": "^28.1.0",
    "jest-environment-node": "^28.1.0",
    "ts-jest": "^28.0.3",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.7.2"
  },

Comment: Please provide a [mvce](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: Thanks! I've added the package.json dependencies. The file with the errors is a copy and paste from step 3, here: https://jestjs.io/docs/mongodb
Answer: For me, it worked using process.env.MONGO_URL to replace globalThis._MONGO_URI_:
connection = await MongoClient.connect(process.env.MONGO_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})

This way you will be using the test database from the lib @shelf/jest-mongodb.


Is there an option to somehow display all nodes that that doesn't have a menu link?

Question: As almost all users here know, you can set up a menu link to each node from the "Menu settings" tab in the node's edit form.
Is there an option to show all nodes that don't have a menu link?
I tried to create a view and use the filter criteria to achieve that, but no relevant filtering option appeared for me there.
Answer: I think the best approach to handle this would be to get all of the menu items, and the nodes associated to them.  Then perform a EntityFieldQuery on nodes.  Making sure that your query includes a 'NOT IN' condition, and use the ids from the nodes you discovered in the menu as the values.
This would return all nodes not in your menus.
Comment: Maybe use menu_tree_all_data() for get all menu items and filter the NIDs?
https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_tree_all_data/7.x
Answer:
I tried to create a view and use the filter criteria to achieve that, but no relevant filtering option appeared for me there.

A workaround would be:
1) Add a Boolean type field to your content type.
2) Check-mark the field for all the nodes that have a menu link
3) Filter view by your boolean field. (where the boolean is false, unchecked, equal to 0)

Bonus: If you're using Drupal 7 you could use Menu Rules which lets you add the a condition

Conditions:
  - Node has menu entry - checks if the node has a menu link.

Therefore, you can use rules to automatilly check or uncheck your boolean field, that way you don't have to remember to check it or uncheck it, when you check or uncheck the menu link option.

Note: As pointed out, if you have lots of menu link nodes, which would make ✓ check marking all their boolean field annoying and time
  consuming, you can create a Rule Component that uses Views Bulk Operations with the Node has menu
  entry condition to check mark all of those nodes boolean fast.

Bonus 2: If you did Bonus 1, you can use Field Permissions to hide your boolean field from the edit page.
Comment: Didn't know about "Menu rules", interesting! However what about "existing content" (before you'd implement as you suggested in your answer)? How about adding VBO for some type of one time only conversion, whereas you'd trigger a Rules Component (with a condition like NOT 'Node has menu entry') to update the existing content also?
Comment: @Pierre.Vriens If I could down vote your last comment, I would too. `trustworthy solution` is not the right description. If he tries my answer it will work. I think `not totally thorough` would be the better way to describe it. I agree with @Clive, it's not our duty to cover every possibility. It is actually the OPer's duty to tell us if he has lots of menu links or just a few. Since he did not tell us, common sense tells me to assume he has few menu links. If the OPer forgot to mention he has lots, he can always post a comment and I'll adjust my answer accordingly.
Comment: @Pierre.Vriens thanks, forgot to take into account that.
Comment: @Pierre.Vriens `with a condition like NOT 'Node has menu entry'` actually we don't need to. Because the boolean will be false by default. The nodes that need updating would be the menu link ones, where we checkmark the boolean (setting it to TRUE). Unless he has a ton of menu link nodes, no need to VBO.
Comment: actually I need to test my answer, to see if we need VBO or not.
Comment: yeah, no need to VBO unless you have a ton of menu link nodes, which need to be updated to (1 aka true aka be checkmarked).
Comment: Please do not add a "part 2" to this, the answer is already more than sufficient for the question that was asked, and will end up being another overblown, unreadable mess that we have to consider deleting if you keep editing and adding to it. We are not trying to write documentation here, or cover every possible eventuality that the OP doesn't mention, just to **answer the question that was asked** in a **brief** and **succinct** manner. The overblown "this covers every possibility ever, even if you didn't ask for it" answers are going to be clamped down on, they're poisonous to Q+A. Thanks!
Comment: @Pierre.Vriens In addition, remember that we are doing this on our free time. Being totally thorough can be time consuming. Time that we could be using for something else. The onus is on the OPer to make the question as specific as possible and not on the answerer. Although, a small note or comment talking about the possibility is always welcomed and fine in my books **:)**
Comment: @NoSssweat : ok, "fair" (further edited) answer!


Query returns 0 rows on JQGrid filter due to translated rows

Question: I have a JQGrid table that can be displayed in different languages. The data for this table is stored as English text and translated when output. The JQGrid table can be filtered by text.
The issue I have, is that when the JQGrid table is filtered, the query will run against the English text. E.g.
Original table:
Yes
No
Translated table:
Oui
Non
User is French and tries to filter for 'Oui':
Database query will return zero results because 'Oui' does not exist in the database table. If the French user queries for 'Yes' then Oui will show because it matches the database and is translated on output.
This is using custom integration with JQGrid.
Since all string translation is cached and as far as I know there are no database tables available to join on, how can I get translated filtering to work?
Any ideas on the best way to handle this?
Answer: Ok. I've solved this in what I believe is a reasonable way but it won't really scale:
As I build up the data for the table and translate each cell, I store that into an array with the foreign language string as the key and the untranslated string as the value. (This could work either way round).
<code>$strings[t($my_string)] = $my_string;
</code>
I save that array after I've done everything with the last snippet. This array is read at the beginning of loading the table data:
<code>$strings = $saved_strings = variable_get('my_translated_strings_' . $language->language, array());
</code>
If the array has changed then I will save it:
<code>if ($strings != $saved_strings) {
  variable_set('my_translated_strings_' . $language->language, $strings);
}
</code>
I can then manipulate the filter rules to filter on the original untranslated strings instead of the user's language.


How load data from mySql in an HTML button?

Question: I want to load data from my MySql database and put one field of this database into the text of a button :
<?php
  $servername = "localhost";
  $username   = "prova";
  $password   = "";
  $dbname     = "prova";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  $sql    = "SELECT nomeCantiere,codiceCommessa,indirizzoCantiere FROM Cantiere";
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
      // output data of each row
      while ($row = $result->fetch_assoc()) {
          echo "nomeCantiere: " . $row["nomeCantiere"] . " - codieCommessa: " . $row["codieCommessa"] . " - indirizzoCantiere" . $row["indirizzoCantiere"] . "
";
      }
  } else {
      echo "0 results";
  }
  $conn->close();
?>
<input type="button" value="button" />

I'm a beginner with this type of programming.
For now I have managed to do is generate a simple "echo".
How can I automatically generate buttons with a value="nomeCantiere"?
Answer: You are almost done with the code. You just need to add the value here:
if ($result->num_rows > 0) {
  // output data of each row
  while ($row = $result->fetch_assoc()) {
    //// Look at this line ////
    echo '<input type="button" value="' . $row["nomeCantiere"] . '" />';
  }
} else {
  echo "0 results";
}
$conn->close();

The above will generate a few rows of buttons. If that's what you would need. :)
Comment: Ha ha... Is that helpful? @NarcosZTK_10
Comment: @NarcosZTK_10 Glad that you got it solved. Have a nice day. Will wait for 5 mins... `:)`
Answer: You can echo html tags in php
ie.
echo "<button>". $row["nomeCantiere"] ."</button>"

or
echo "<input type='button' value='". $row["nomeCantiere"] ."'/>"

Comment: `` not a ``!
Comment: @RiggsFolly isn't it the same ? Or this is because NarcosZTK_10's code was an  ?
Comment: Because the OP's code uses an ``
Comment: @RiggsFolly is it because of the submit issue? we can specify type=button in  right


Drills to prevent standing up on the downswing

Question: After a few years off, I'm getting an interest in golf again. My main problem, after getting a few basic pointers correcting my stance and backswing from a clubfitter I was working with to find the right driver, is a tendency to back away from the ball with my upper body at impact, causing me to hit the ball thin, top it or whiff it. I know I'm doing it, and correct it on the next swing, but that's only an option at the driving range, not on the course. The only advice the clubfitter could give was "don't do that".
Is there a common drill that can help reduce this tendency and integrate it into my muscle memory? It seems to only happen with woods, sometimes my hybrid, never on irons, so I'm thinking it's caused by the longer shaft length and the desire for distance making me put my back into it too much.
Answer: I have exactly the same problem. My teachers said that's because I want to do one of two things:

See where it will land before I even hit it.
Trying to hit harder to get more distance.

I have two drills that my teacher make me do, I think it depends exactly on the error you have.

Put your head (your forehead) againts a wall. Then practice your
swing avoiding moving your head from the wall.. it you hurt yourself,
well you hit the wall ;). Anyway try it at home, and also at driving,
because I felt that this particular drill seems to fail at home (I
never get up at home, I usually did that at the driving).
the other is not a drill, but a way to hit. Just keep your eyes on
the tee (or the floor) for at least one more second after hitting
the ball. This will take out the pressure on where did it fall.

Of course I'm not a teacher, and I have a horrible handicap, but I have this drills working it out to avoid at least this problems (my mental problems on the fields has another issues by itself :) )
Answer: Rickie Fowler does something similar. "How far back I move my head is a matter of timing that varies day to day. If I'm feeling super on, I shift back real far."
I would start out using driving with control, and the way Rickie does that is to choke down on the driver and tee the ball low and perpendicular to your left heel. I think this promotes less of a "rip it" mentality and more of a "make a solid strike" one.
Last year, I was in such ball-striking mess that I considered giving up the game of golf. Rickie's control tip really helped me to gain confidence off the tee, even though I wasn't bombing it. Now, when I get a good hold of a drive, I'm driving it 50 yards past my playing partners, and if it's not working for me that day (usually any day), I fall back to the control drive.
A drill Hank Haney would do with Charles Barkley (I know) is to place his hand on the Charles's forehead as he would make a swing. I would do that if someone was willing to assist with that.
Answer: Not so much a drill but a thought process in how you swing the club - I think the key to this is what you do in the backswing, not the downswing.  If you set yourself up well in the backswing then the downswing will take care of itself (i.e. I'll bet your head is coming up in the backswing too).
Try to imagine yourself rotating within a barrel when you swing the club and try to keep your belt-line level throughout the backswing.  With the longer clubs (esp. the driver) we're told that the motion should be a longer sweeping one to encourage you to sweep the ball off the tee on the up-swing. Whilst correct this can also encourage more lateral/sideways body movement on the backswing, which if taken to extremes can result in a lifting of the head/upper body - your hands and arms go back and up in the backswing and your upper body follows.
For me having a mental image that I'm rotating my shoulders around two fixed points (i.e. my head and my feet firmly planted on the ground) works very well because it prevents me from swaying, which in my case can cause me to "stand up" on the backswing.
Nick Bradley proposes a "3 barrels" visualisation in his book, which I can very much  recommend:
The 7 Laws of the Golf Swing
It's a bit technical at times, but really gives you an understanding of how the golf swing should work, and includes some great skeletal illustrations unlike any I've seen in other books.


Game theory: power and mod

Question: Given two non negative integers $a, b$. Two players alternate turns. If at any state of the game the two integers are $a\le b$ then the player with the turn can either replace $b$ with $b\bmod a$ or $b-a^k\ge 0$ where $k$ is any positive integer chosen at that turn. The first player to yield a $0$ wins (if one of initial values is $0$ the player $1$ wins). Under what conditions on $a, b$ shall player $1$ have a winning strategy?
Answer: Firstly, let me say that for consistency, it would make sense if player 1 loses if one of the initial values is $0$. Imagine the position were, say, "$1,5$" and Alice is to move, then Alice could win by replacing $5$ with $5\text{ mod }1=0$. If we allowed the game to go on for one more step, then Alice's opponent could be faced with $0,1$ and would have lost. I will follow the convention that player 1 loses if the game starts with a $0$ in the discussion below.
Well, the important thing about simple combinatorial games like this is that the position is a win for the second player precisely if all of the pairs the player can move to are wins for the first player. Since there are no pairs to move to if 0 is in the pair, those are "wins for second" (not wins for first). Since a positive pair with a 1 in it, or with both numbers the same, necessarily has a move to a position with a 0, those are all wins for first, etc.
Using white squares to mark wins for the second player and black squares to mark wins for the first player, we get something like this for small pairs:
$$\begin{matrix}
&0&1&2&3&4&5&6&7&8&9\\
0& \square & \square & \square & \square & \square & \square & \square & \square & \square & \square  \\
1& \square & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \blacksquare  \\
2& \square & \blacksquare & \blacksquare & \square & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \square \\
3& \square & \blacksquare & \square & \blacksquare & \square & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \blacksquare  \\
4& \square & \blacksquare & \blacksquare & \square & \blacksquare & \square & \square & \blacksquare & \blacksquare & \blacksquare \\
5& \square & \blacksquare & \blacksquare & \blacksquare & \square & \blacksquare & \square & \square & \square & \blacksquare  \\
6& \square & \blacksquare & \blacksquare & \blacksquare & \square & \square & \blacksquare & \square & \square & \square  \\
7& \square & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \square & \square & \blacksquare & \square & \square  \\
8& \square & \blacksquare & \blacksquare & \blacksquare & \blacksquare & \square & \square & \square & \blacksquare & \square \\
9& \square & \blacksquare & \square & \blacksquare & \blacksquare & \blacksquare & \square & \square & \square & \blacksquare  \\
\end{matrix}$$
The rows for 0 and 1 and the main diagonal are what I described, but the rest is a little complicated. To get a broader picture of what's going on, we can use a computer, telling it what the moves are for a pair, and that a move is a win for the second player if all the moves are to first player wins, and a win for first player otherwise.
Here is a computer-generated table for pairs with max up to 100:

This looks pretty complicated. For fun, here's up to 1000:

Since these images are complicated, I doubt there's going to be a very nice formula/characterization. They remind me of Whythoff's game, where the corresponding image is basically two lines of dots that hug lines with irrational slopes.

Game theory: power and mod


duplicate search field appearing with just one block

Question: There's suddenly two search fields appearing on my dev site. I'm afraid I'm not sure what the last change was before this.
There's just one standard Drupal search block configured

here's the html from chrome's inspector

Configure block

  <form action="/" method="post" id="search-block-form" accept-charset="UTF-8">

Search form

  Search
 <input title="Enter the terms you wish to search for." type="text" id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">

<input type="submit" id="edit-submit--6" name="op" value="Search" class="form-submit">
<input type="hidden" name="form_build_id" value="form-siNBZmrvpwkL6N9gfwu4Li2LBMPzp0TVxw81H7C4H2U">
<input type="hidden" name="form_token" value="nxWBZ6gSMs4INvrbfpGyfd4DTr2QhLdfSrjuYA5PSC0">
<input type="hidden" name="form_id" value="search_block_form">

</form>

Comment: Have you tried clearing the cache already?
Comment: Yes, that's not it.
Answer: It's probably a css problem.
My guess is the search bar is using a background image. The image contains both the inactive search background and the active search background. It's a good thing to avoid to load 2 different images.
If you want this to work, you need to ensure that the search box has a fixed height.
So in the css, you should have something like :
#edit-search-block-form--2 {
  height: 10px;   /* 10px => replace this with the real height */
}