Why do the estimated values from a Best Linear Unbiased Predictor (BLUP) differ from a Best Linear Unbiased Estimator (BLUE)?

Question: I understand that the difference between them is related to whether the grouping variable in the model is estimated as a fixed or random effect, but it's not clear to me why they are not the same (if they are not the same).
I am specifically interested in how this works when using small area estimation, if that's relevant, but I suspect the question is relevant to any application of fixed and random effects.
Answer: The values that you get from BLUPs aren't estimated in the same way as the BLUE estimates of fixed effects; by convention BLUPs are referred to as predictions.  When you fit a mixed effects model, what are estimated initially are the mean and variance (and possibly the covariance) of the random effects.  The random effect for a given study unit (say a student) is subsequently calculated from the estimated mean and variance, and the data.  In a simple linear model, the mean is estimated (as is the residual variance), but the observed scores are considered to be composed of both that and the error, which is a random variable.  In a mixed effects model, the effect for a given unit is likewise a random variable (although in some sense it has already been realized).
You can also treat such units as fixed effects, if you like.  In that case, the parameters for that unit are estimated as usual.  In such a case however, the mean (for example) of the population from which the units were drawn is not estimated.
Moreover, the assumption behind random effects is that they were sampled at random from some population, and it is the population that you care about.  The assumption underlying fixed effects is that you selected those units purposefully because those are the only units you care about.
If you turn around and fit a mixed effects model and predict those same effects, they tend to be 'shrunk' towards the population mean relative to their fixed effects estimates.  You can think of this as analogous to a Bayesian analysis where the estimated mean and variance specify a normal prior and the BLUP is like the mean of the posterior that comes from optimally combining the data with the prior.
The amount of shrinkage varies based on several factors.  An important determinate of how far the random effects predictions will be from the fixed effects estimates is the ratio of the variance of the random effects to the error variance.  Here is a quick R demo for the simplest case with 5 'level 2' units with only means (intercepts) fit.  (You can think of this as test scores for students within classes.)
library(lme4)   # we'll need to use this package
set.seed(1673)  # this makes the example exactly reproducible
nj = 5;    ni = 5;    g = as.factor(rep(c(1:nj), each=ni))

##### model 1
pop.mean = 16;    sigma.g = 1;    sigma.e = 5
r.eff1   = rnorm(nj,    mean=0, sd=sigma.g)
error    = rnorm(nj*ni, mean=0, sd=sigma.e)
y        = pop.mean + rep(r.eff1, each=ni) + error

re.mod1  = lmer(y~(1|g))
fe.mod1  = lm(y~0+g)
df1      = data.frame(fe1=coef(fe.mod1), re1=coef(re.mod1)$g)

##### model 2
pop.mean = 16;    sigma.g = 5;    sigma.e = 5
r.eff2   = rnorm(nj,    mean=0, sd=sigma.g)
error    = rnorm(nj*ni, mean=0, sd=sigma.e)
y        = pop.mean + rep(r.eff2, each=ni) + error

re.mod2  = lmer(y~(1|g))
fe.mod2  = lm(y~0+g)
df2      = data.frame(fe2=coef(fe.mod2), re2=coef(re.mod2)$g)

##### model 3
pop.mean = 16;    sigma.g = 5;    sigma.e = 1
r.eff3   = rnorm(nj,    mean=0, sd=sigma.g)
error    = rnorm(nj*ni, mean=0, sd=sigma.e)
y        = pop.mean + rep(r.eff3, each=ni) + error

re.mod3  = lmer(y~(1|g))
fe.mod3  = lm(y~0+g)
df3      = data.frame(fe3=coef(fe.mod3), re3=coef(re.mod3)$g)

So the ratios of the variance of the random effects to the error variance is 1/5 for model 1, 5/5 for model 2, and 5/1 for model 3.  Note that I used level means coding for the fixed effects models.  We can now examine how the estimated fixed effects and the predicted random effects compare for these three scenarios.
df1
#         fe1     re1
# g1 17.88528 15.9897
# g2 18.38737 15.9897
# g3 14.85108 15.9897
# g4 14.92801 15.9897
# g5 13.89675 15.9897

df2
#          fe2      re2
# g1 10.979130 11.32997
# g2 13.002723 13.14321
# g3 26.118189 24.89537
# g4 12.109896 12.34319
# g5  9.561495 10.05969

df3
#         fe3      re3
# g1 13.08629 13.19965
# g2 16.36932 16.31164
# g3 17.60149 17.47962
# g4 15.51098 15.49802
# g5 13.74309 13.82224

Another way to end up with random effects predictions that are closer to the fixed effects estimates is when you have more data.  We can compare model 1 from above, with its low ratio of random effects variance to error variance, to a version (model 1b) with the same ratio, but much more data (notice that ni = 500 instead of ni = 5).
##### model 1b
nj = 5;    ni = 500;    g = as.factor(rep(c(1:nj), each=ni))
pop.mean = 16;    sigma.g = 1;    sigma.e = 5
r.eff1b  = rnorm(nj,    mean=0, sd=sigma.g)
error    = rnorm(nj*ni, mean=0, sd=sigma.e)
y        = pop.mean + rep(r.eff1b, each=ni) + error

re.mod1b = lmer(y~(1|g))
fe.mod1b = lm(y~0+g)
df1b     = data.frame(fe1b=coef(fe.mod1b), re1b=coef(re.mod1b)$g)

Here are the effects:
df1
#         fe1     re1
# g1 17.88528 15.9897
# g2 18.38737 15.9897
# g3 14.85108 15.9897
# g4 14.92801 15.9897
# g5 13.89675 15.9897

df1b
#        fe1b     re1b
# g1 15.29064 15.29543
# g2 14.05557 14.08403
# g3 13.97053 14.00061
# g4 16.94697 16.92004
# g5 17.44085 17.40445

On a somewhat related note, Doug Bates (the author of the R package lme4) doesn't like the term "BLUP" and uses "conditional mode" instead (see pp. 22-23 of his draft lme4 book pdf).  In particular, he points out in section 1.6 that "BLUP" can only meaningfully be used for linear mixed-effects models.
Comment: +1. But I am not sure I fully appreciate the terminological distinction between "predicting" and "estimating". So a distribution parameter is "estimated", but a latent variable can only be "predicted"? Do I then understand correctly that e.g. factor loadings in factor analysis are "estimated", but factor scores are "predicted"? Apart from that, I find it remarkably confusing that something called "best linear unbiased predictor" is actually a *biased* estimator (because it implements shrinkage and hence must be biased) if one were to treat it as an "estimator" of the fixed effects...
Comment: At least it's clear what "linear" means :-) Seriously though, I have found [this very helpful answer](http://stats.stackexchange.com/questions/17773) by @whuber on terminological difference between "prediction" and "estimation". I think it clarified the terminology to me, but even reinforced my feeling that BLUP is rather an estimator, despite its name. [cont.]
Comment: @amoeba, yes that's all reasonable. But I wouldn't want to use the same name for both, because you are doing something different (ie the equations differ) & it's useful for the names to be distinct.
Comment: @amoeba, I tweaked the phrasing in the first paragraph to deemphasize those terms, so as not to reify "prediction", but to maintain the distinction. See if you think I threaded the needle or if it should be clarified further.
Comment: @amoeba, what does "best" mean anyway? *Best* what? Is it the best estimate of the data's mean, or the best combination of the information contained in the data & the prior? Does the Bayesian analogy help you?
Comment: So I checked and saw that [wikipedia article on BLUP](https://en.wikipedia.org/wiki/Best_linear_unbiased_prediction) says right in the first paragraph that P in BLUP `is a bit strange since the random effects have already been "realized"`. Wikipedia cites Robinson's [overview paper on BLUP](http://projecteuclid.org/download/pdf_1/euclid.ss/1177011926) that states the same in Section 7.1. Robinson says that he prefers to use the term "estimation" for both fixed and random effects, and seems to agree that P in BLUP is confusing.
Comment: Yes, I agree with that. But I do see some issues with the 1st paragraph of your answer (and even with the first sentence: `The values that you get from BLUPs aren't estimates; they're predictions.` etc.). Perhaps you will want to clarify/update it somehow. (The "main" part of the answer and the simulation are great.)


Zen theme not showing second level menu items

Question: I am creating a zen sub-theme and I edited the menu called "Main menu" to have on root level item that has 5 children (second level). The root level item shows up fine but none of the children are ever output in the HTML.
I verified they are all enabled. Just not sure why they aren't being sent back to the client. Does the Zen theme need some modification to support menus that are deeper than one level?
Comment: The parent item is set to `expanded` in the menu settings, right?
Answer: Edit your page.tpl.php
Edit the section where the primary_links are printed to show the whole primary links menu instead of only showing the first level links of your primary links menu.
<?php if (isset($primary_links)) { ?>

<?php print theme('menu_tree',variable_get('menu_primary_menu',0)); ?>

<?php } ?>

In Drupal 6
<?php
$menu_name = variable_get('menu_primary_links_source', 'primary-links');
print menu_tree($menu_name);
?>

Drupal 7
<?php

    $menu_name = variable_get('menu_main_links_source', 'main-menu');
    $tree = menu_tree($menu_name);
    print drupal_render($tree);
?>

Answer: Use Superfish or Nice Menus module to show 2nd level menu items.


How can I measure which function is a better fit to a set of datapoints

Question: The problem is from here. Namely, I have set of data points
data = [[90.00, 2.0], [97.40, 5.0], [104.8, 14.0], [112.2, 12.0], [119.6, 11.0], [127.0, 6.0], [134.4, 3.0], [141.8, 1.0], [149.2, 2.0], [156.6, 1.0]]

I have to fit a curve of the form $$\frac{m}{\sigma\sqrt{2\pi}}\cdot e^{-(x-\mu)^2/(2\sigma^2)}$$
to this data.
In the link, Volker Brown got the values
$$m = 405.75796954829985, \mu = 111.86913960269014, \sigma = 11.968861052746961$$
and as I tried my version of Sage to the same to that set of data, I got
$$m = 405.7572223708457, \mu = 111.86914614035226, \sigma = 11.96881745593664$$
What kind of ways there are to measure which one is better fit to that set of data? I heard that sometimes one can use log-likelihoods to select the best model and sometimes Akaike's information criterion is suitable for that. But which one should I choose in this situation? Thusfar, I haven't studied the theory behind the AIC.
Another thing that confuses me is Brown's comment "You need to give some hint for the initial values." Does that mean that there is no standard way to measure how good a particular curve fits to the data?
Or is that just a bug in a previous version of Sage that has been fixed in the version  5.6, 21 January 2013?
Comment: How did you measure the values of your data points?  What do they represent?  What is the purpose of fitting this curve?  And why are you concerned about differences in the seventh decimal place in estimates with data that appear to have at most three decimal places of precision and to be limited in quantity?
Comment: @whuber I don't know where the data is originally from. I found that discussion, tried it and found that my version of Sage outputs different results that the version original poster uses. I'm just curious if there are some methods to evaluate which curve fits better to the data.
Comment: These data almost surely are counts associated with numbers representing midpoints of bins.  For such data this entire approach would be terribly misguided (and wrong, due to the inclusion of $m$ as a parameter): there are far better ways to fit distributions.  Moreover, as a simple plot will show, no Normal distribution will fit these data even approximately well.  Your question is a good one but this example is spectacularly bad.
Answer: Akaike's information criterion and (log)-likelihood
You are right that the (log-)likelihood and Akaike's information criterion can be used to discriminate between different models.
However, if the two models have the same number of parameters the approaches are equivalent. Akaike's information criterion is defined by (see link)
$$
\mathit{AIC} = 2k - 2\ln(L),
$$
where $k$ is the number of parameters of the model and $L$ is the likelihood function.
In your case, the number of parameters is $k=2$ for both models such that it is sufficient to consider the likelihood function.
Fitting curves
There are a number of methods to fit curves to data, e.g. least-square fitting or maximum likelihood fitting. Different methods are used in different situations: least-square fitting is appropriate if you want to determine the relationship between two variables. Maximum likelihood fitting is appropriate if you want to determine parameters of a probability distribution.
Because the original problem mentions "I have a problem with fitting my data set with a Gauss (Normal) distribution" I will take a maximum-likelihood approach in the following.
Fitting the parameters (assuming a probability distribution)
The likelihood function is defined as the probability to observe a given sample (your data values) given a set of parameters ($sigma$ and $mu$).
Consider a single data point with value $x$. Assuming that your model is Gaussian, the probability to observe this point is $$p(x|\sigma,\mu)=\frac{1}{\sqrt{2\pi}\sigma} \exp\left(-\frac{1}{2}\frac{(x-\mu)^2}{\sigma^2}\right).$$
Assuming that your samples are independent and are members of a vector $\bf{x}$, the probability to observe them is
$$
\begin{align}
p({\bf x}|\sigma,\mu)&=\prod_{i=1}^Np(x_i|\sigma,\mu)\\
&=\frac{1}{\sqrt{2\pi}\sigma}\exp\left(-\frac{1}{2\sigma^2}\sum_{i=1}^N(x_i-\mu)^2\right).
\end{align}
$$
We can maximise this probability (the likelihood) by differentiating with respect to $\sigma$ and $\mu$. You can look up the details here.
We thus find $$\hat{\mu} = \overline{x} \equiv \frac{1}{n}\sum_{i=1}^n x_i, \qquad
    \hat{\sigma}^2 = \frac{1}{n} \sum_{i=1}^n (x_i - \overline{x})^2.$$
I have used the following python code to fit the parameters (assuming that the second value of each tuple is a count).
import numpy as np
data = np.array([[90.00, 2.0], [97.40, 5.0], [104.8, 14.0], [112.2, 12.0], [119.6, 11.0], [127.0, 6.0], [134.4, 3.0], [141.8, 1.0], [149.2, 2.0], [156.6, 1.0]])
#Determine the total number of points
number_of_points = np.sum(data[:,1])
#Determine the mean using a weighted average
mu = np.sum(map(lambda (value, count): value * count, data)) / number_of_points
#Determine the standard deviataion
sigma = np.sqrt(np.sum(map(lambda (value, count): (value - mu)**2 * count, data)) / number_of_points)
print "\\mu = {0}, \\sigma = {1}".format(mu, sigma)

The results are $\mu = 115.056140351, \sigma = 14.1192790625$. Note that we do not need to determine $m$ because it is fixed by the condition that the probability distribution needs to be properly normalised.
Comparing results
The following code evaluates the log-likelihood of the different parameter values
def ll(data, mu, sigma):
    #Determine the total number of points
    number_of_points = np.sum(data[:,1])
    #Determine the variance
    var = np.sum(map(lambda (value, count): (value- mu)**2 * count, data)) / number_of_points

    return - number_of_points*(.5 * np.log(2*np.pi)\
        + np.log(sigma) + var / (2 * sigma ** 2))

print "First result"
print ll(data, 111.86913960269014, 11.968861052746961)
print "Second result"
print ll(data, 111.86914614035226, 11.96881745593664)
print "My result"
print ll(data, mu, sigma)

The results are
First result
-235.552835278
Second result
-235.552923018
My result
-231.789343246

Thus, the result obtained by Volker is marginally better than your SAGE result. However, neither of them maximises the log-likelihood.
Note that all of the above assumes that we are fitting a probability distribution.
Answer: You should note that AIC is just a penalized liklihood where the penalty is based on the number of parameters fit.  Since the 2 models that you are comparing both fit the same number of parameters (just found different values) they will both receive the same exact penalty.  So for your case comparing AIC values will give the same results as comparing liklihoods.
The advantage of AIC is when comparing models with different numbers of parameters (i.e. a linear model with additional covariates, interaction terms, polynomial terms, etc.).  The more complicated model will tend to have a higher liklihood, possibly due to random chance.  The AIC value looks to see if the increase of liklihood is enough to justify the added complexity.  Since your 2 models are equally complex the liklihood part is the only thing that will change.
The comment about the starting values is because many algorythms are sensitive to starting values.  You may have found a local max/min or the process may have stopped because the last improvement was small compared to previous steps.  Think about the question "Where is your home?", if you are asked this while in your own neighborhood you are likely to give your street name and possibly the exact address, if in a different country you are more likely to only give the city, or possibly even a nearby city that is more likely to be recognized.  Similarly the closer your starting values are to the "Truth" the stricter the criteria for stopping.
Have you tried actually plotting your data and the 2 fitted equations?  Given that the 2 sets of parameters don't differ until after the 7th significant digit, I doubt that you will see any practical difference.  That level of difference is easily explained by differences in starting values rather than bugs or changes in the software  (rarely do we ever get the exactly correct answer, just reasonably good approximations).
Comment: I thought that the curve fitting algorithm runs until it converges to the solution which has at least 17 correct digits. I haven't plotted the equations but I think I won't see difference between curves.
Comment: @JaakkoSeppälä, how can the algorithm know if there are 17 correct digits? unless it knows the exact correct answer, but then why iterate at all?  These algorithms only look at the degree of improvement in the last step.  Since machine precision for a double precision floating point number is about 16 or 17 digits it is not reasonable to expect meaningful steps/comparisons at 17 digits.  I am not familiar with Sage, but I would guess that the convergence criteria is probably at around 8 significant digits.


Drupal Commerce Shopping Cart Form Alter

Question: I'm trying to use hook_form_FORM_ID_alter() in my theme's template.php file to change the 'Remove' button in the Commerce add to cart form to an image button. To do this I'm using the following code:
function tempestra_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
  foreach($form['edit_delete'] as $item) {
    if($item['#type'] == 'submit') {
      $item['#type'] = 'image_button';
      $item['#src'] = base_path() . drupal_get_path('theme', 'tempestra') . '/images/search.png';
      unset($item['#name']);
      dpm($item);
    }
  }
}

When I look in the array printed by dpm() everything is as it should be, however the HTML for the image button isn't printed.
Thanks in advance.
Answer: Simple mistake, you don't change $form but only $item if you did
foreach($form['edit_delete'] as &$item) {

or
foreach($form['edit_delete'] as $key => $item) {
  ...
  $form['edit_delete'][$key] = $item;
}

it should work.
Comment: Yeah that now works perfectly, I hadn't thought about it that way or even realised you could use `&` in a foreach statement. Thank you!
Answer: function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form') !== FALSE) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Buy now'),
    );
  }
}


C# Complicated Json Deserialize

Question: I am trying to deserialize this json but this is complicated json and I couldn't. Actually I tried to create a class in http://json2csharp.com/ but it didn't work again. Can you help me to figure it out
<code>    {

    "?xml":{

    "@version":"1.0",

    "@encoding":"utf-8"

    },

    "ArrayOfPerson":{

    "@xmlns:xsd":"http://www.w3.org/2001/XMLSchema",

    "@xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",

    "alert":[

    {

    "@xmlns":"urn:url:taces:numarates",

    "identifier":"489756",

    "sender":"example.com",

    "sent":"2015-08-19T23:44:00+00:00",

    "status":"Actual",

    "msgType":"wait",

    "source":"Company",

    "scope":"Public",

    "info":{

    "category":"known",

    "event":"event created",

    "responseType":"Execute",

    "urgency":"Expected",

    "severity":"Severe",

    "certainty":"Likely",

    "effective":"2015-08-19T23:44:00+00:00",

    "expires":"2015-08-20T00:29:00+00:00",

    "senderName":"Company",

    "headline":"headlineExample",

    "description":" description string ",

    "instruction":" instruction description.",

    "contact":"mail adress",

    "parameter":[

    {
    "valueName":"city",
    "value":"city time"
    },

    {
    "valueName":"severity",
    "value":"High"
    },

    {
    "valueName":"POLYGON",
    "value":"POLYGON ((25.8600349687548 -100.744518850353, 25.8335161877637
    -100.664518850353, 25.8346209950992 -100.624518850353, 25.8442798845219
    -100.61828081562, 25.8842798845219 -100.602879447141, 25.9242798845219
    -100.604707951971, 25.941798102096 -100.624518850353, 25.9243730812152
    -100.684518850353, 25.9242798845219 -100.684661516991, 25.9095974027013
    -100.704518850353, 25.9042798845219 -100.710343745251, 25.8642798845219
    -100.747917201708, 25.8600349687548 -100.744518850353))"
    },

    {
    "valueName":"direction",
    "value":"2"
    },

    {
    "valueName":"speed",
    "value":"27 km"
    }

    ],

    "area":{
    "areaDesc":"Latitude: 25.885, Longitude: -100.664",
    "polygon":"26.1256671949002 -100.814556141911, 25.5230724567197
    -100.823124650158, 25.5734941016972 -100.397349654998, 26.1574195901602
    -100.546429706446, 26.1256671949002 -100.814556141911"
    }

    }

    }

    ... array items

    ]
    }
    }
</code>
Comment: Did you convert this from XML?  Would it be easier to deserialize the XML directly?
Comment: I tried but I don't know how to parse it as xml so I've changed to json and parse
Answer: It seems your issue is because your JSON property names can't be used as C# variables "as is" therefore json2charp returns names like "invalid-name__@version"
Almost all Json desializers including DataContractJsonSerializers and Json.Net can support custom datamember names. It doesn't need to be identical as property name in your class. Refer to DataMember attribute on MSDN
Alternatively  you can use Json.Net library and JsonReader to manually address properties by name http://insidethecpu.com/2013/06/19/json-parsing/

C# Complicated Json Deserialize


Using different threads to read from a consumer group in Kafka using reactor-kafka

Question: I need to consume from a Kafka topic that will have millions of data. Once I read from the topic, i need to transform and write it to another topic. I am able to consume messages from the topic, process the data by multiple threads and write to another topic.
I followed the example from here https://projectreactor.io/docs/kafka/1.3.5-SNAPSHOT/reference/index.html#concurrent-ordered
Here is my code:
<code>public Flux<?> flux() {
            KafkaSender<Integer, Person> sender = sender(senderOptions());
            return KafkaReceiver.create(receiverOptions(Collections.singleton(sourceTopic)))
                                .receive()
                                .map(m -> SenderRecord.create(transform(m.value()), m.receiverOffset()))
                                .as(sender::send)
                                .doOnNext(m -> m.correlationMetadata().acknowledge())
                                .doOnCancel(() -> close());
        }

</code>
I have multiple consumers to read from and was looking into adding different reader threads to read from the topic due to the volume of data. However, the reactor-kafka documentation mentions KafkaReceiver is not thread-safe since the underlying KafkaConsumer cannot be accessed concurrently by multiple threads.
I am looking for suggestions on reading from a topic concurrently.
Answer: So basically what you are looking for called Consumer Group, the maximum parallel consumption you can run is limited by the number of partitions your topic has.
Kafka Consumer Group mechanism allows you to seperate the work of consumption a topic to diffrent "readers" which belongs to the same group, the work would be divided by that each consumer in the group would be solely responsible for a partition (1 or more, based on number of consumers in the group, and number of partitions to the topic)
Comment: Yup that's all, the kafka mechanism handles all the rest, you can run the instance of reader (with same consumer group) parallel,  remember that it is limited by your topic configuration - the number of partitions
Comment: Okay, that makes sense. Thanks!
Comment: I have added my code in the question. If I have to consume messages  in parallel from the topic,  can I do that along with processing the data in multiple threads?
Basically, I am trying to figure out how to update the code to handle concurrent reading from topic along with processing the data and sending to another topic.
Comment: consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "sample-group");
Comment: If i set the consumer group in the properties would my code read from the topic in parallel from each consumer in the consumer group? Is there no need to add a Scheduler to read from different consumer group in the code?


Repositioning a custom registration link on WooCommerce login page

Question: I have a WooCOmmerce Login Page which I am customizing at the moment, by default the login and registration page are in one page. I had seperated the login and registration pages into 2 seperate forms right now. Currently I would like to put a link for the seperated registration page right below the "Forgot Password" link.
But my output is as follows :

I would like for it to appear as follows:

Below is the action hook I am using for my login page.
add_action( 'woocommerce_after_customer_login_form', 'register_link' );
function register_link() {

    ?>

<?php _e( 'Register a new account here' ); ?>

    <?php

}

Any help would be much appreciated.
Answer: This can be done in multiple ways:

You can edit the template myaccount/form-login.php to insert your code in the right location.

you can use Javascript/jQuery to insert your code in the right location, without editing any template:

// The jQuery Ajax request
add_action( 'wp_footer', 'wc_separated_login_form_js' );
function wc_separated_login_form_js() {
    // Only my account for unlogged users
    if( ! is_user_logged_in() && is_account_page() &&
    'yes' === get_option('woocommerce_enable_myaccount_registration') ):

    // Your button html to insert
    $html = sprintf(
        '
%s
',
        home_url('/registration/'), // <== Here set your registration link
        __( 'Register a new account here')
    );

    // jQuery
    ?>

    <?php
    endif;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Comment: Hi @LoicTheAztec, Thanks for the provided action hook, applied to functions.php on active child theme and it worked as intended. Tough I disabled the woocommerce registration page, and used a 3rd party registration plugin like "WPEverest" to accommodate for new users sign up. I just changed from `'yes' === get_option('woocommerce_enable_myaccount_registration')` to `'no' === get_option('woocommerce_enable_myaccount_registration')`. Output as follows on the attached screenshot. [Screenshot of Corrected Link Position](https://imgur.com/9HRrhoj)


Set a theme for a single content types edit page

Question: How do you set the theme for the edit page for just one content type on your site?  I am using bootstrap for non-admin pages and using the default seven for the admin pages. So basically I need to override the admin theme of seven with the bootstrap theme, but only for one content type.
Any help is much appreciated.
Answer: Using hook_menu_alter you can override even the theme a path uses.
<code>function hook_menu_alter( &$items)
{
    $items['path']['theme callback'] = 'variable_get';
    $items['path']['theme arguments'] = array('theme_default');
}
</code>
like this you set the theme for that path to whatever the user theme is, even for admins.
Comment: How would you do thus for an edit if a node because the path would be /node/{nodeid}/edit.  You cant set a path.
Comment: 'node/%nid/edit'. When in doubt, you can look for the hook_menu of the module that declared the path you want work on.
Answer: Use Content Theme module to assign theme for content creating, editing, and viewing pages.
This module features are :

Assign a theme to all content. (This overrides the system default
theme)
Assign a theme to a content type. (This overrides content wide themes
and system default)
Assign a theme to a content node. (This overrides content type
themes, content wide themes, and system default)
Allow to use different themes on content creating/editing pages than
on viewing pages.
   Fine-grained permission control.
Comment: I appreciate the feedback, nothing seems to be working for overriding the seven them on the edit page. I loaded the content theme and it still did not change. When I debug it is showing boostrap sub theme being loaded first but then the seven theme loads last which I assume is causing this issue. Any ideas how to overcome this issue?
Comment: what seemed to work is setting the admin to default theme (bootstrap subtheme) and changing the theme for /admin/* to the seven theme.


Make Duplicity list files to be backed up?

Question: When using --dry-run with rsync it can list the files that will be backed up. But when I with duplicity do
duplicity --dry-run --name pchome --encrypt-sign-key xxx --include $HOME/Desktop --exclude '**' $HOME file:///mnt/backup

it just gives the statistics.
Question
How can I get duplicity to list the changes (copy/dalete) it will preform?
Answer: Increase the verbosity of output. According to duplicity man:
       --verbosity level, -vlevel
          Specify output verbosity level (log level).  Named levels and corresponding values
          are 0 Error, 2 Warning, 4 Notice (default), 8 Info, 9 Debug (noisiest).
          level may also be
          a character: e, w, n, i, d
          a word: error, warning, notice, info, debug

          The options -v4, -vn and -vnotice are functionally equivalent, as are the
          mixed/upper-case versions -vN, -vNotice and -vNOTICE.

--verbosity info worked for me


Evaluating $\oint_c x\,dx-y\,dy$ (and others) over unit circle $c$. I'm not sure I understand how those separate derivatives are supposed to work.

Question: The question says:

Solve the following line integrals, where $c$ is the circle with radius $1$ centered at the origin, that can be parametrized by $ c : [0,2\pi]\rightarrow \mathbb{R}^2 : t \mapsto c(t) = (\cos(t),\sin(t))$.
(i) $\;\oint_c x\,dx-y\,dy$
(ii) $\;\oint_c x\,dx+x\,dy$
(iii) $\;\oint_c y\,dx$
(iv) $\;\oint_c dy$

I think I'm supposed to use Green's theorem and solve these integrals as a double integral on the region of a circle, and then use polar coordinate substitution? But I'm not sure I understand how those separate derivatives are supposed to work like in "$x\,\mathrm{d}x-y\,\mathrm{d}y$" for example.
Comment: @J_P I'm really asking what notation like $xdx-ydy$ means, but I could use some help in how to use green's theorem to compute those integrals, although I think I might be able to do it myself once I understand how this notation works
Comment: Is your question how to use Green's theorem to compute these integrals, or is it what precisely notation like $x\,\mathrm{d}x - y\,\mathrm{d}y$ means?
Answer: I think the best explanation for this $\mathrm{d}x$ notation is in terms of differential forms, but that may be too advanced, so let's use simpler notions.
Suppose $\gamma:[a,b]\longrightarrow\mathbb{R}^2$ is a continuously differentiable curve and suppose further that $f:U\longrightarrow\mathbb{C}$ is a differentiable function defined on some open neighborhood of the image of $\gamma$ (so, in the case of the circle, it would be defined at least on some thick annular region around the circle). Then if $g$ is any continuous function defined on the image of $\gamma$, we set
$$
\int_\gamma g\,\mathrm{d}f = \int_a^b g(\gamma(t)) \nabla\!f(\gamma(t))\cdot\frac{\mathrm{d}\gamma(t)}{\mathrm{d}t}\,\mathrm{d}t
$$
What happens if we reparametrize $\gamma$? If $[c,d]$ is another interval and $\phi:[c,d]\longrightarrow [a,b]$ is continuously differentiable with $\phi(c)=a$, $\phi(d)=b$, we have that
\begin{align*}
\int_c^d \!\!g(\gamma(\phi(s))) \nabla\!f(\gamma(\phi(s)))&\cdot\frac{\mathrm{d}\gamma(\phi(s))}{\mathrm{d}s}\mathrm{d}s=\!\!\int_c^d\!\!g(\gamma(\phi(s))) \nabla\!f(\gamma(\phi(s)))\cdot\frac{\mathrm{d}\gamma}{\mathrm{d}t}\bigg\vert_{t=\phi(s)}\!\frac{\mathrm{d}\phi(s)}{\mathrm{d}s}\mathrm{d}s=\\
&= \int_a^b g(\gamma(t)) \nabla\!f(\gamma(t))\cdot\frac{\mathrm{d}\gamma(t)}{\mathrm{d}t}\,\mathrm{d}t
\end{align*}
by the change of variables formula, so the integral is unchanged.
Morally speaking,
$$
\mathrm{d}f=\nabla\!f(\gamma(t))\cdot\frac{\mathrm{d}\gamma(t)}{\mathrm{d}t}\,\mathrm{d}t
$$
The dot product of the gradient with the tangent vector of the curve tells us how much the function $f$ changes when we move infinitesimally along the curve. The integral then just sums all these infinitesimal changes. Now if we have several pairs of functions $g_1, f_1$, $g_2, f_2$, ..., we can just set
$$
\int_\gamma g_1\mathrm{d}f_1+g_2\mathrm{d}f_2+ ...=\int_\gamma g_1\mathrm{d}f_1 + \int_\gamma g_2\mathrm{d}f_2+...
$$
as a sum of integrals.
Let's examine your example with $x\,\mathrm{d}x-y\,\mathrm{d}y$: we have $x(c(t))=\cos(t)$, $y(c(t))=\sin(t)$, $\nabla x(c(t))=(1,0)$, $\nabla y(c(t))=(0,1)$, $\frac{\mathrm{d}c}{\mathrm{d}t}=(-\sin(t),\cos(t))$. Hence
$$
\int_{\mathbb{S}^1}x\,\mathrm{d}x-y\,\mathrm{d}y = \int_0^{2\pi} (-\cos(t)\sin(t)-\sin(t)\cos(t))\,\mathrm{d}t=-\int_0^{2\pi}\sin(2t)\,\mathrm{d}t=0
$$
As for Green's formula, if $\gamma(a)=\gamma(b)$ and $\gamma$ is injective, then your curve bounds a region $D$. The formula is then that for any continuously differentiable $g_1, g_2$ defined on a neighborhood of $D$:
$$
\int_\gamma g_1\mathrm{d}x + g_2\mathrm{d}y = \iint_D \bigg(\frac{\partial g_2}{\partial x}-\frac{\partial g_1}{\partial y}\bigg)\,\mathrm{d}x\,\mathrm{d}y
$$
Importantly, the curve must be oriented counterclockwise, otherwise there would be a factor of $-1$ in this equality. In the case we just looked at, $g_1=x$ and $g_2=y$, so the partial derivatives entering into the double integral are $0$ and the answer is again $0$, as it should be.
Answer:
Since there is no indication to apply Green's theorem
it rather seems we are expected to calculate the line integral by using the given closed path parametrisation of the unit circle
\begin{align*}
c:[0,2\pi]\rightarrow \mathbb{R}^2 : t \mapsto c(t) = (\cos(t),\sin(t))
\end{align*}
as it is stated.
So we want to calculate the four line integrals
\begin{align*}
\oint_c x\,dx-y\,dy&\qquad\qquad\oint_c x\,dx+x\,dy\tag{1.1,$\quad$1.2}\\
\oint_c y\,dx&\qquad\qquad\oint_c dy\tag{1.3,$\quad$1.4}
\end{align*}

Note, the line notation used here is just a space-saving notation for the vector-based notation which is often used when parametrisation comes into play. Since then we can conveniently write, given the parameter $t$ varies in the interval $[t_1 ,t_2]$ and $c=(x(t),y(t))$
\begin{align*}
\color{blue}{\oint_c a(x,y)\,dx+b(x,y)\,dy=\int_{t_1}^{t_2} \left(a(x(t),y(t))\dot{x}(t)+b(x(t),y(t))\dot{y}(t)\right)dt}\tag{2}
\end{align*}
In fact we have a shortcut for some of the four line-integrals in (1.1) to (1.4). We recall a fundamental theorem of line integrals which states that if we integrate within a simply connected region the integral
\begin{align*}
\color{blue}{\oint_c a(x,y)\,dx+b(x,y)\,dy=0}\qquad\mathrm{iff}\qquad
\color{blue}{\frac{\partial a(x,y)}{\partial y}=\frac{\partial b(x,y)}{\partial x}}\tag{3}
\end{align*}

Example 1.1: We have according to (2)
\begin{align*}
\oint_c a(x,y)\,dx+b(x,y)\,dy=\oint_c x\,dx-y\,dy
\end{align*}
It follows
\begin{align*}
\frac{\partial a(x,y)}{\partial y}=\frac{\partial x}{\partial y}=0
\qquad\mathrm{and}\qquad
\frac{\partial b(x,y)}{\partial x}=\frac{\partial (-y)}{\partial x}=0\\
\end{align*}
and we conclude according to (3)
\begin{align*}
\color{blue}{\oint_c x\,dx-y\,dy=0}
\end{align*}

Example 1.2: We have according to (2)
\begin{align*}
\color{blue}{\oint_cx\,dx+x\,dy}
&=\int_0^{2\pi} \left(\cos (t)\left(-\sin(t)\right)+\cos^2(t)\right)\,dt\\
&=-\int_{0}^{2\pi}\cos(t)\sin(t)\,dt+\int_{0}^{2\pi}\cos^2(t)\,dt\\
&=-\frac{1}{2}\int_0^{2\pi}\sin(2t)\,dt+\frac{1}{2}\int_{0}^{2\pi}\left(\cos(2t)+1\right)\,dt\\
&=-\frac{1}{4}\cos(2t)\Big|_{0}^{2\pi}+\frac{1}{4}\sin(2t)\Big|_{0}^{2\pi}+\frac{1}{2}t\Big|_{0}^{2\pi}\\
&\,\,\color{blue}{=\pi}
\end{align*}

Example 1.3: We have according to (2) and example 1.2
\begin{align*}
\color{blue}{\oint_c y\,dx}
&=\int_0^{2\pi} \sin (t)\left(-\sin(t)\right)\,dt\\
&=-\int_{0}^{2\pi}\left(1-\cos^2(t)\right)\,dt\\
&=-t\Big|_{0}^{2\pi}+\pi\\
&\,\,\color{blue}{=-\pi}
\end{align*}

Example 1.4: We have according to (2)
\begin{align*}
\oint_c a(x,y)\,dx+b(x,y)\,dy=\oint_c dy
\end{align*}
It follows
\begin{align*}
\frac{\partial a(x,y)}{\partial y}=0
\qquad\mathrm{and}\qquad
\frac{\partial b(x,y)}{\partial x}=\frac{\partial y}{\partial x}=0\\
\end{align*}
and we conclude according to (3)
\begin{align*}
\color{blue}{\oint_c dy=0}
\end{align*}


Eigen value of $ A^{\theta}A $

Question: Let $A$ be $n \times n$ nonsingular complex matrix and let $B = A^{\theta}A$ where $A^{\theta} $ is the conjugate transpose of $A$. If $k$ is eigen value of $B$ then what can be said about $k$:

$k$ is real or complex?
$k <0$ $k \le  0$, $k \ge 0$, $k > 0$. What is true?

My textbook says B is hermetian, so k is real. But why is it hermetian?
Comment: @ketan If an $n\times n$ matrix $M$ is hermitian, it satisfies $M^*=M$, where $^*$ denotes complex conjugation followed by transposition. Here, we have that $B=A^*A$, so that $B^*=(A^*A)^*=(A)^*(A^*)^*=A^*A=B$. Therefore $B$ is indeed hermitian. Now, the answers to both your questions follow from the [spectral theorem](http://en.wikipedia.org/wiki/Spectral_theorem).
Comment: complex conjugate of the the transpose of $A$ is usually denoted by $A^*.$ i have never seen $\theta$ in place of $*$ i almost assumed you were talking about non integer powers of $A$ by looking at the title of your question.
Comment: Theta denotes conjugate transpose
Comment: @abel In linear algebra, the conjugate transpose of $A$ is indeed noted $A^*$, although the notation $A^{\dagger}$ ("A-dagger") is widely used in physics.
Comment: @Demosthene thank a lot
Answer: Hint:
Let $x$ be an eigenvector for $B$ at eigenvakue $k$. Try to calculate the inner product
$\langle Bx,x\rangle$.

Eigen value of $ A^{\theta}A $


Translations on flat torus

Question: I'm confused about isometries of the flat 2-torus and could't find anything online that cleared my confusion. My problem is the following:
Let $T^2=\mathbb{R}^2/\Gamma$ be a 2-torus for $\Gamma \cong \mathbb{Z}$ a lattice in $\mathbb{R}^2$. I know that any isometry of the euclidean plane which preserves the lattice $\Gamma$ induces an isometry of the flat torus $T^2=\mathbb{R}^2/\Gamma$ and conversly any isometry of the flat torus lifts to an isometry of the euclidean plane which preserves the lattice $\Gamma$.
But my geometric intuition is that any translation in $\mathbb{R}^2$ should descent to an isometry of the flat torus, since translating any "amount" should preserve length of curves on the torus. But when I take for example the standard torus $\mathbb{R}^2/\mathbb{Z}^2$ and a translation $f(x,y)=(x,y+\lambda)$ for $\lambda \not\in \mathbb{Z}$, then for any lattice point $(k,l)$ we have $f(k,l)=(k,l+\lambda)\not\in \mathbb{Z}^2$, hence $f$ does not preserve the lattice $\Gamma$ and hence does not descent to an isometry of the torus. Why is this?
Comment: Not every isometry of $\mathbb{R}^2$ descends to an isometry of $T^2$. An isometry of $\mathbb{R}^2$ descends to an isometry of $T^2$ if and only if it descends to a well-defined map (i.e. it preserves the lattice).
Answer: One has to look carefully at what it means for $f$ to "preserve the lattice". I find that phrase to be a little vague and ambiguous, so I'll avoid it, and instead use a more precise phrase. I suspect that if you the source that you are consulting is written with full and precise definitions (and this is a big "if" when using only on-line sources), then it will have the definition that I write, or something equivalent.
Consider a lattice $\Gamma \subset \mathbb R^2$, meaning an additive subgroup which is discrete and isomorphic to $\mathbb Z^2$. We'll say that an isometry $f : \mathbb R \to \mathbb R$ preserves the cosets of $\Gamma$ if for every $(k,l) \in \Gamma$ and every $(x,y) \in \mathbb R^2$ we have
$$f(x+k,y+l) - f(x,y) \in \Gamma
$$
Equivalently, $f$ preserves the cosets of $\Gamma$ if for every $(k,l) \in \Gamma$ and every $(x,y) \in \mathbb R^2$ there exists $(k',l') \in \Gamma$ such that
$$f(x+k,y+l) = f(x,y) + (k',l')
$$
This condition is necessary for $f$ to induce an isometry of $T^2$.
In fact, even more is true, this condition it is necessary just for $f$ to induce a well-defined function from $T^2$ to itself.
To see why, fix $(x,y) \in \mathbb R^2$. The point $(x,y)$ is a representative of the coset $(x,y) + \Gamma \in \mathbb R^2 / \Gamma = T^2$. In order for $f$ to induce a well-defined function from $\mathbb R^2 / \Gamma$ to itself, as $(k,l)$ varies over $\Gamma$ it must be true that all of the points $f(x+k,y+l)$ are contained in a single coset of $\Gamma$. That coset contains the point $f(x+0,y+0)=f(x,y)$ (by taking $(k,l)=(0,0)$), and so it follows that for each $(k,l) \in \Gamma$ there exists $(k',l') \in \Gamma$ such that $f(x+k,y+l) = f(x,y) + (k',l')$.
Notice that I have not even talked about isometries, nonetheless I think this addresses your question already: you seem to have overlooked the importance of "preserving cosets".
Comment: This clears things up. Thank you!

Translations on flat torus


Fulltext search multiple columns for multiple search terms

Question: I have a requirement from a client to have a search-field where he wants to input any text and search for every word in that text field in multiple full-text indexed columns which contain customer information, from a customer information table.
So, for example, if he inputs FL Diana Brooks Miami 90210, he wants all of these terms (FL, Diana, Brooks, Miami, 90210) to each be searched into the State, FirstName, LastName, City and Zip columns.
Now, this seems totally a bad idea to begin with and as an alternative I suggested using multiple fields where to input this information separately. Nonetheless, the point I am at is having to make a proof of concept as to why this won't work, from a performance perspective, and that it's better to have multiple fields where you input the term you want to search for.
So, getting to my query, I'm trying to write a Full-Text query to do what the client has asked for in order to get a benchmark for performance.
What I have so far doesn't seem to work, so I guess I am asking if it's even possible to do this?
declare
    @zip varchar(10)            = 90210
    , @lastName varchar(50)     = 'Brooks'
    , @firstName varchar(50)    = 'Diana'
    , @city varchar(50)         = 'Miami'
    , @state char(2)            = 'FL'
    , @searchTerm varchar(250)  = ''
    , @s varchar(1) = ' '

set @searchTerm = @state + ' ' + @firstName + ' ' + @lastName + ' ' + @city

select *
from freetexttable(contacts, (zip, lastName, FirstName, city, state), @searchTerm) ftTbl
inner join contacts c on ftTbl.[key] = c.ContactID

The query I have above seems to work, but is not restrictive enough in order to find only the single record I'm looking for and is returning a whole lot more (which I'm guessing that it's because I'm using FREETEXTTABLE).
I've also tried replacing it with CONTAINSTABLE, but I get an error saying:

Msg 7630, Level 15, State 3, Line 26
Syntax error near 'Diana' in the full-text search condition 'FL Diana Brooks Miami'.

With using regular indexes I have been able to solve this, but I'm curious if it's even possible to do the same thing with Full-Text.
Using regular indexes I have a query with a adaptable WHERE clause, like below:
WHERE C.FirstName like coalesce(@FirstName + '%' , C.FirstName)
    AND C.LastName like coalesce(@LastName + '%' , C.LastName)
    etc.

Answer: You can create a view WITH SCHEMABINDING with id and concatinated columns:
CREATE VIEW dbo.SearchView WITH SCHEMABINDING
AS
SELECT  id,
        [State]+' ',
        [FirstName]+' ',
        [LastName]+' ',
        [City]+' ',
        [Zip] as search_string
FROM YourTable

Create index
CREATE UNIQUE CLUSTERED INDEX UCI_SearchView ON dbo.SearchView (id ASC)

Then create full-text index on search_string field.
USE YourDB
GO

--Enable Full-text search on the DB
IF (SELECT DATABASEPROPERTY(DB_NAME(), N'IsFullTextEnabled')) <> 1
EXEC sp_fulltext_database N'enable'
GO

--Create a full-text catalog
IF NOT EXISTS (SELECT * FROM dbo.sysfulltextcatalogs WHERE [name] = N'CatalogName')
EXEC sp_fulltext_catalog N'CatalogName', N'create'
GO

EXEC sp_fulltext_table N'dbo.SearchView', N'create', N'CatalogName', N'IndexName'
GO

--Add a column to catalog
EXEC sp_fulltext_column N'dbo.SearchView', N'search_string', N'add', 0 /* neutral */
GO

--Activate full-text for table/view
EXEC sp_fulltext_table N'dbo.SearchView', N'activate'
GO

--Full-text index update
exec sp_fulltext_catalog 'CatalogName', 'start_full'
GO

After that you need to write some function to construct a search condition. F.e.
FL Diana Brooks Miami 90210

Became:
"FL*" AND "Diana*" AND "Brooks*" AND "Miami*" AND "90210*"

And use it in FREETEXT or CONTAINS searches:
DECLARE @search nvarchar(4000) = '"FL*" AND "Diana*" AND "Brooks*" AND "Miami*" AND "90210*"'

SELECT  sv.*
FROM dbo.SearchView sv
INNER JOIN CONTAINSTABLE (dbo.SearchView, search_string, @search) as c
    ON c.[KEY] = sv.id

Comment: I just found your answer after I tested a similar approach. I created a new column where I concatenated all of the search columns (a bit redundant, I know - I like your indexed view better) and used a `WHERE CONTAINS(searchColumn, @searchTerm)` and it worked mostly. The only issue I'm getting is with e-mail addresses where it appears if I include an e-mail address like `firstname.lastname@example.com` in my `@searchTerm` variable, I don't get back the correct line.


scratch sprite not registering hit consistently

Question: This simple shooter game is supposed to result in the sprite shattering and disappearing when hit. It will work maybe 40% of the time. Here's the link to the project and the relevant code block:
https://scratch.mit.edu/projects/524150880/editor
Answer: So turns out that by simplifyingthe sprite's movements from:

to:

fixed the problem. Sprite consistently breaks up and disappears when hit. So it was just a matter of streamlining I guess?
Answer: If you are going to make a shooter game, you probably want to use create clone of [myself] block and then do this:
when i start as a clone
show
repeat until < <touching [YOUR TARGET SPRITE HERE]> or <touching [edge]> >
|| point in direction (DIRECTION OF YOUR SHOOTER)
|| move (ADD YOUR NUMBER HERE)
start sound (meow)
change [score] by (1)
repeat (5)
|| change [mosaic] effect by (2)
delete this clone
For the bullet, you would need this script:
when green flag clicked
forever
if <key [ANY KEY YOU WOULD LIKE TO USE TO SHOOT] pressed> then
|| create clone of myself
However if you would like to add a cooldown to the bullets, make a new variable called cooldown and reduce it by 0.1 every millisecond (0.1 second), but do make sure that when cooldown is 0 it doesn't go into the negatives, and when cooldown is 0, you can shoot and it resets the cooldown to the number of seconds you want it to be, if you want it your code should look like this:
when green flag clicked
forever
if <key [ANY KEY YOU WOULD LIKE TO USE TO SHOOT] pressed> then
|| if cooldown < 0.1
|| || create clone of myself
The reason it is || if cooldown < 0.1 and not || if cooldown = 0 is because if you screw up and accidentally make it 4.25 instead of 4.2 the bullet would still shoot
Comment: Sorry but this time, sprite doesn't shatter or disappear at all. Thanks anyway.
Comment: Did you remember to put ```delete this clone```? If you didn't it won't delete the clone of your bullet. Are you confused by the formatting?
Comment: I did delete the clone and I did pick up on your formatting. If the code were wrong then it would be wrong all the time, not just part of the time. I hate to say scratch is buggy since I've always believed the computer is never wrong, but I'm going in that direction.
Comment: Hey! I'm sorry for only replying after 5 months, but you would need to delete your old code for it to work.
Comment: Better late than never, thanks! It's working pretty much as it should after I streamlined the code.


What does the notation $\pi$ mean in probability and statistics

Question: I have noticed that in the presentation of probability distribution, sometimes a certain probability is dentoed by $\pi(...)$. For example, in the wike page of Beta binomial distribution https://en.wikipedia.org/wiki/Beta-binomial_distribution, they use $P(X=k|p,n)$ to denote the distribution of $X$, while using $\pi(p|\alpha,\beta) = Beta(\alpha,\beta)$ to denote the distribution of $p$. May I ask why the notation $\pi$ is used here? Is there a specific meaning?
Comment: (1) n hypothesis-testing, $\pi$ is sometimes designates power [1 - P(Type II Error)];  (2) In Bayesian stat $\pi$ is used by some authors to designate a prior or posterior dist'n (3) In connection with binomial dist'ns $\pi$ is can be used instead of $p$ to denote Success probability, especially when authors want to use Greek letters for parameters. (4) If $\pi$ is used for a quantity other than 3.14159..., it is customary to make a comment to avoid confusion. The alternate form of  'pi' ($\varpi$) is not often used in stat or math, perhaps to avoid confusion with $\omega.$ or $\bar\omega.$
Comment: Here it is used for density function of variable p given $\alpha, \beta$
Comment: $P(X=k|p,n)$ is also the density function, why they use $\pi()$ to denote the density function of $p$
Comment: $P$ is the probability mass function. $\pi$ notaion is usually used for continuous variable.
Comment: thanks for the explanation, it is bayesian stat I am talking about. So, $\pi$ can be used to designate prior or posterior distribution, and does not necessary need to be conjugate?
Answer: ISLR (An Introduction to Statistical Learning) states:

Let $π_k$ represent the overall or prior probability that a randomly
chosen observation comes from the kth class.

This above is in reference to the the Bayes Theorem.
Bayes theorem is given by
$Pr(Y = k|X = x) = \frac{π_kf_k(x)}{\sum_{l=1}^{K}π_lf_l(x)}$
Note that the meaning of $f_k(x)$ as the following:

Let $f_k(x) ≡ Pr(X = x|Y = k)$ denote the density function of X for an
observation that comes from the kth class.

see page 138 and 139 (corresponds to the 152nd and 153rd page due to index etc.) in this link
https://hastie.su.domains/ISLR2/ISLRv2_website.pdf


Is a midi track in a DAW called a sequencer?

Question: Say we create a midi track in a DAW like Logic or Ableton and we record some notes to it via some midi controller. I'm wondering if that track is now considered to be a sequencer? And if we created multiple midi tracks, do we now have multiple sequencers?
Context: I've noticed hardware devices like Korg Volca, Electron Digitakt, and others are step sequencers. But what they are essentially doing is looping a series of notes. So isn't that what a DAW is doing on one of its midi tracks? (especially if we set that track as a loop).
Comment: A midi track can be considered a sequencer with greater PPQN.
https://music.stackexchange.com/questions/94123/ppqn-in-a-16-step-sequencer-vs-daw
Answer: Let me take a try at this and hopefully I don't mix up my terms...
A sequencer is an application storing a sequence of events for tracks each of which sends MIDI data to a MIDI voice to be performed by some machine like a synthesizer.
The key point being that MIDI is a type of data or protocol. The sequencer knows how to communicate with the MIDI protocol.
Comment: a sequencer doesn't have to send midi data, check out 'volca keys' for example. It just sequences notes, much like a track in a daw.
Comment: No one said a sequencer is exclusively MIDI. The point is just that a MIDI track cannot sequence something, it's basically the other way around. A sequencer can make a sequence of MIDI events.
Answer: Back in the days before home computers were powerful enough to process audio, applications like Cubase and Logic were themselves called MIDI sequencers - they were the software counterparts of hardware sequencers like the Alesis MMT-8. Both software and hardware MIDI sequencers at this point could handle multiple tracks of MIDI data, usually transmitted on different MIDI channels.
If I remember correctly, in the mid 90s when computers started to become powerful enough to also handle a few tracks of audio, the term "MIDI and audio sequencer" tended to be used - I believe 'DAW' become the preferred term later.

If we created multiple midi tracks, do we now have multiple sequencers?

because a 'sequencer' can also be a simple thing that stores a simple, one track sequence, that's a perfectly reasonable supposition! However, because in the case of Cubase and Logic, historically the whole program was considered the 'sequencer', and because people had become used to MIDI sequencers being multi-track, the answer is no - a sequencer track is simply considered to be a track, not a separate 'sequencer'.


Vulnerabilities of PHP's (deprecated) mysql module vs. MySQLi & PDOs

Question: I am in charge of maintaining and extending a PHP codebase which began in 2007 and uses the original mysql module. All user input is escaped using casting for values expected to be numerical, mysql_real_escape_string() quoted using single quotes for strings, possibly being further filtered through in_array() for ENUM fields or array_intersect() for SET fields. All unconstrained string fields are then passed through either htmlspecialchars() or htmlentities() when outputting HTML. Where a value represents a foreign key, that key is verified extant first.
I believe that by following these procedures rigorously, the app is as safe as it can be against injection and other forms of attack. (bonus points: am I correct? If not, what am I missing?)
Converting this app to mysqli or PDOs would be a fairly large task (and, to avoid accidental breakage, not something I would want to automate). So finally to my question: Are there any specific vulnerabilities that cannot be mitigated when using the old mysql module, which require migration to the newer modules?
Bounty Info:
To be clear, I am hoping for a list of CVE numbers or a statement from the PHP developers that the mysql module is patched against all known vulnerabilities as of such-and-such a date. I am also assuming that following Best Current Practices in using the module does not expose me to additional attack vectors. BCPs already include escaping data taken from the db before inserting it into a new statement. Going on and on about that isn't really addressing the question.
Comment: If you look at the [`mysql_real_escape_string()` page](http://php.net/mysql_real_escape_string), there is a yellow banner saying you need to set the charset (either directly on the server or by using [`mysql_set_charset()`](http://www.php.net/manual/en/function.mysql-set-charset.php)) for mysql_real_escape_string to take effect.
Comment: I'd suggest to split this question into 2 separate ones. Deprecated mysql module has absolutely nothing to do with XSS (as well as XSRF and dozens other) attacks.
Comment: Nicholas, please check if the mysql extension you use is using internally the mysqlnd driver which is under active development. I would go with that "internal upgrade" and keep an eye on the progress of that mysqlnd development as it's one of PHPs key feature with Mysql. Next to that you haven't shown any code nor configuration, so it's not clear which kinds of your application and database server interaction is potentially more exploitable and by which CVE report. http://dev.mysql.com/downloads/connector/php-mysqlnd/
Comment: @Mogria Please add your comment as a full answer so I can up-vote it :)
Comment: I was holding myself from this comment desperately, but now I can't help it :) May be I am too greedy a person, but 50 reputation points is too cheap, in my point of view, for the "complete list of CVE numbers". To make it clear, I wouldn't be able/do it even for 500 though.
Comment: @YourCommonSense That's fine. I was not expecting you to provide the answer I would like, the bounty is to bring this question to the attention of folks who have not yet seen it. Hopefully one of them will either know of a URL providing this info or have superior Googling abilities to me :)  Also I am trying to get to 2k rep so that I can edit posts without moderation, and this was my first ever bounty offer, so I have started small! You don't need the rep anyway ;-) When I get to 62½k I would certainly offer more on bounties.
Comment: @hakre Fair point regarding code and config. I was trying to solicit general responses rather than post anything specific to my own configuration as we are currently running on an older PHP and am intending to update it to the latest version sometime soon. I did not know about the libmysql/mysqlnd split, so that is certainly helpful. I will make sure I compile in the newer one.
Answer: I have but 2 objections

All user input is escaped is a critical fault, leading to second order injection. "All dynamical data for SQL" is the right approach and phrasing
there are no identifiers mentioned in your post but I can't believe you don't have a query with dynamical identifier in your code since 2007.

There is also a minor inconvenience: in a couple of years (3-4 probably), your PHP will start issuing E_DEPRECATED level errors. But they can be simply turned off.
Anyway, just a mechanical move from one API to another won't make too much sense.
Refactor your SQL handling code only to make use of some abstraction mechanism, be it ORM, AR, QueryBuilder or whatever else technology which will wipe raw API calls from the application code. It will not only make your code less bloated, but also will make it independent from whatever else whim that will strike PHP developers in the future.
To answer the edited question.
There are no essential vulnerabilities in the old mysql ext. The only way it is commonly used is vulnerable and error-prone.
So, instead of looking for strains on the module, better audit your code. If it is not using a centralized library for database interaction utilizing prepared statements, most likely it is vulnerable.
Comment: Thanks for your response. Could you expand those bullet points a bit? By "user input" I was meaning "stuff that isn't hard-coded". The only source for such data I can think of is the $_POST variable (or php://input stream for non-POST, non-safe [in the HTTP sense] methods). Please provide examples of 'second-order' sources. Also, I am not sure what you mean by 'identifiers' and 'dynamical identifiers' (are they the same thing?). Are you referring to primary keys?
Comment: I think by 'second order injection', he means SQL-Injection by data which has already been stored on the server. For Example: Filtering a text for an username from your DB. And the username happens to contain a `'` and some nasty code.
Comment: I bet you if you can provide one example for Blind or Second Order Injection in case that the application uses mysql_real_escape_string()+Correct Charset and nothing more.
Answer: My answer will be somewhat off, and instead of answering your specific questions, I would rather suggest the approach that will actually help you out.
No matter what vulnerabilities could be left or could arise in the future using mysql, and no matter how solid your current codebase approaches (rather avoids for) SQLinjection (it seems to do so pretty well, though), I get the feeling you still would rather migrate to mysqli anyhow but aim for delaying in doing so by seeing short term possibilities to further hack your way around the unsafe and to-be-fully-deprecated mysql.
I would suggest refactoring. Period. Just do that. Keep in mind to refactor, and not to change or extend your codebase while doing so - it's a nasty pitfall. Eventhough it'll be some work - the refactoring, just start your refactoring process (branched of course). It will be very satisfactory on completing it. Expect some long tail issues.
I assume every functionality you describe is wrapped already, so refactoring should be fairly doable. If things had not been wrapped.. ($#@!), figure out a way to uniquely track your function calls (including context) project-wide, (possibly using regular expressions in finding them all) and replace with new unique to-be-used wrapper functions. First explore this, thoroughly. In half a day you would be able to enlist all your regular expression that you will need. So plan it first, by exploring your path first.
Fill the new wrappers with the current (old) functional code and see if all still works as was.
Then start migrating to mysqli, and rebuild your wrappers internally.
Seems to be a simple as possible approach, avoiding all the matters and questions that will stay in the back of your mind despite whatever you try do in hacking your way deeper around common mysql. I don't need to tell you about the benefits mysqli will bring, you know those already. Futhermore, it simply is good practice to every once in while actually undertake those kind of issues for once and for all. Plan, discuss, branch, try, do, test, complete, and conquer! On top off all: make sure you don't fall for the opportunities to extend your codebase and functional scope while refactoring - you will be tempted to do so: just refactor. Add, extend, or improve later.
Comment: Nobody's answer came close to what I was looking for, but this one is both aligned with where I am going and also the author had the lowest score so could do with the bounty points. :-)
Answer: I don't feel qualified to answer your question definitively so please be careful using the information I provide, but I do have some experience in managing the sort of changes you might be looking at.  AFAICS however your statements should protect you against XSS and SQL injection if what you say is true.
I have recently begun the process of migrating an entire large application from mysql_ to mysqli_ and in doing so I have also set the goal that all user input shall go through prepared statements.
EDIT in response to YCs fair comment below:  For the avoidance of ambiguity, I always put anything that a user has generated through a prepared statement, even if it has already been stored in the db.  Where possible I avoid using re-insertion of user data though as it is unreliable so system functions tend to depend on automatically generated indices.
In fairness, the pages are short (no more than 1000 lines) so fixing does not take long per page and they have few queries so the performance reduction is not noticeable, and certainly eaten up by improvements in server technology since I wrote the original code.  I suspect you will find that the reduction in escaping etc will far outweigh any performance hit on prep statements though you'll have to check if it's critical.
It has dismayed me how many vulnerabilities I found in my code whilst doing this review (I included security as best I could when it was written and set myself rules much the same as yours) and ultimately I have found the need to rewrite large code chunks to improve security.  Performance has improved markedly as a result of greater experience and code tweaks too.
The way I'm going about the change is to add a mysqli connection to my database header file.  All new code uses this.  As I find time, I'm updating older code and testing each page using a header file that does not have the old mysql connection.  It's dead quick to find bits you've missed that way in a dev environment and it can be quite a good way to use time that would otherwise be wasted as each page takes only a few minutes to update so can be done during brain-fade periods.
A note on the second order injection BTW as this was the most common vulnerability I had built in:
Most SQL injection prevention kind of assumes that the injection attack will only take place at login, from a malicious non-registered user who once foiled will never return and that registered users can be trusted.  Not so.
It is conceivable that code could be injected through your protection then used later.  This is most unlikely to work as it is heavily dependent on clumsy db and application design, but some of the smartest people in the world are hackers.  Why make their life easier?
The attack is made more probable if your sql is simple and your application does any subquerying using data previously obtained from the db.  Remember that
' OR 1=1 gets converted to
\' OR 1=1 by mysql_real_escape_string but is stored as
' OR 1=1 in the db

so if retrieved and placed into a PHP variable which is then used unescaped in a sql query, it can then cause problems just the same as if it had never been escaped.  If you just use prep statements for all queries, the risk goes away permanently though do remember the prep statement will still store the malicious code so you still have to use a prepared statement again when you next need to use the data that has been entered.
This Blog gives a decent discussion and examples so I'll not expand further, but if you ensure that all user input data is passed through prepared statements if it is to be used as part of a query, even after it has been stored in the db, you should be safe.
At the risk of repetition, it is worth also becoming very friendly with the OWASP site which has valuable security discussions.
Comment: -1 for contradicting "**user input** shall go through prepared statements" vs. "second order injection" and mentioning OWASP site which actually advocate unsafe solutions.
Comment: IMHO not contradictory but I deserve the -1 for being unclear.  Correction made and your comments always appreciated!  Which security site would you advise?
Comment: So, you're dividing data to "user-supplied" and "non-user supplied" and always keep in mind data source, and treat it differently.
Comment: That is the idea.  Some data is inherently safe, being generated internally.  Wherever possible I use a reference to the user data, usually a SERIAL rather than the data itself, The user data is displayed (through htmlspecialchars for XSS) but not re-integrated in the database save through prepared statements.  The db is fully normalized so it is most unusual to have to reintroduce user-entered data as it tends to exist in only one place.  I am aware of the risk though of making a mistake so tend to be very conservative and if in doubt use prep stmnt.
Comment: And as soon as it grows to a more-one-man project and another developer has no idea of your separation - it become a scenario of an injection, as it was 1000 times already. Very clever.
Comment: @YourCommonSense, can you supply details for things OWASP does incorrectly?
Comment: @OwenBeresford [SQL Injection Defense Option 3: Escaping All User Supplied Input](https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_3%3a_Escaping_All_User_Supplied_Input)
Answer: Okay so i've made a little research and the only vulnerability I've found in regard to mysql extension also seems to affect mysqli equally extension is CVE-2007-4889
 which is a "Safe Mode Bypass" vulnerability and has been fixed long time ago
whats more is that both mysql.so and mysqli.so modules are sharing pretty much the same imports as can be seen -
/usr/lib/php5/20090626/mysql.so:
 0x0000000000000001 (NEEDED)             Shared library: [libmysqlclient.so.18]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000e (SONAME)             Library soname: [mysqli.so]

/usr/lib/php5/20090626/mysqli.so:
 0x0000000000000001 (NEEDED)             Shared library: [libmysqlclient.so.18]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000e (SONAME)             Library soname: [mysql.so]

There is also some sort of likelihood where new vulnerabilities may raise in both modules because of their shared import nature
And there is always a chance where a distinctive flaw is originated from the actual code of one of these modules.
But so far it seems like the vulnerability record of both modules is pretty much the same to this date
As mentioned here I'd invest more time in auditing the PHP source code making sure few things -

SQL injections - Parametrized SQL queries is the best solution against this kind of flaws.
XSS(Cross Site Scripting) -  use htmlspecialchars() to filter dangerous characters
CSRF(Cross Site Request Forgery) - Always perform referrer check on forms to be sure the data arrived from the right place
File Inclusion - make sure no user input can directly affect inclusion(require(), require_once() , include(), include_once()) of files
File Upload - in case where file upload is enabled for some reason make sure not to let the user control the file extension or save the files and set its presmission to be "non-execute". this is done to prevent from at attacker to upload malicious file and execute code on your server.
Comment: referer check is useless against CSRF. Only token helps.


How to read TensorBuffer

Question: I am new to Tensorflow and Android, I am trying to classify data from external accelerometer to predict weather it align to left, right, forward , back or center. So I trained model using colab and converted it to tflite and added it to Android App, I could not make any sense of output
package com.yogai.tensorflowlava;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.Toolbar;

import com.yogai.tensorflowlava.ml.Adxl345;

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.TensorFlowLite;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import java.io.IOException;
import java.nio.ByteBuffer;

public class MainActivity extends AppCompatActivity {
        Button submitButton;
        EditText editText;
        String text;
        String TAG = "My_APp";
   // private Context context;

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

        editText = findViewById(R.id.editText);
        submitButton = findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                text = editText.getText().toString().trim();
                //String str = "geekss@for@geekss";
//                String[] arrOfStr = text.split(",", 3);
//
//               // String[] strings = new String[] {"1", "2", "3", "4"};
//                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
//                    Float[] floats = Arrays.stream(arrOfStr).map(Float::valueOf).toArray(Float[]::new);
//                }
                String[] parts = text.split(",");
                float[] numbers = new float[parts.length];
                for (int i = 0; i < parts.length; ++i) {
                    float number = Float.parseFloat(parts[i]);
                    float rounded = (int) Math.round(number * 1000) / 1000f;
                    numbers[i] = rounded;
                }

//                float[][] array2d = new float[1][3];
//
//
//
//                for(int j=1;j<4;j++) {
//                    array2d[1][j] = numbers[j];
//
//
//                }
//                Float testValue = array2d[1][1]+1;
                Log.d(TAG,String.valueOf(numbers[1]));
                ByteBuffer.allocate(4).putFloat(numbers[0]).array();
                byte[] byteArray= FloatArray2ByteArray(numbers);
                ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
                getOutput(byteBuffer);

            }
        });
    }

        public static byte[] FloatArray2ByteArray(float[] values){
            ByteBuffer buffer = ByteBuffer.allocate(4 * values.length);

            for (float value : values){
                buffer.putFloat(value);
            }

            return buffer.array();
        }

    private void getOutput(ByteBuffer byteBuffer) {

        try {
            Adxl345 model = Adxl345.newInstance(getApplicationContext());

            // Creates inputs for reference.
            TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 3}, DataType.FLOAT32);
            inputFeature0.loadBuffer(byteBuffer);

            // Runs model inference and gets result.
            Adxl345.Outputs outputs = model.process(inputFeature0);
            TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();

            String converted = new String(buffer.array(), "UTF-8");

            Toast.makeText(this,"output: "+outputFeature0.toString(),Toast.LENGTH_SHORT).show();

            // Releases model resources if no longer used.
            model.close();
        } catch (IOException e) {
            // TODO Handle the exception
            Toast.makeText(this,"Error: "+ e.toString(),Toast.LENGTH_SHORT).show();
        }
    }

}

Comment: Check the output using `tensorBuffer.getFloatArray()`.
Answer: You can use outputFeature0.getDataType().toString() to check the type of the data.
It would return a string among "FLOAT32","INT32","UINT8","INT64","STRING","INT8".
If the type of the data is FLOAT32, you can get the data like below:
float[] data=outputFeature0.getFloatArray()

How to read TensorBuffer


In Olympics gymnastics competition, what are the requirements to compete for a Country?

Question: Watching the Olympics, I came across an athlete, Kylie Rae Dickson, representing Belarus. However, she was American and the commentator briefly touched on how she had no Belarus heritage. I did a quick Google search and found this on Dickson's Wikipedia article:

"She competed for Belarus at the 2015 World Artistic Gymnastics Championships, with club teammate Alaina Kwan. Neither she nor Kwan had familial ties to Belarus or had visited when they acquired Belarussian citizenship and competition rights."

How can an athlete with no ties to a country (say, Belarus) still compete for them?
Answer: The Olympics, in general, only requires an athlete to be a citizen of their country for them to be eligible to compete under their flag.
The Olympic charter states the following:

41 Nationality of competitors*

Any competitor in the Olympic Games must be a national of the country of the NOC which is entering such competitor.
All matters relating to the determination of the country which a competitor may represent in the Olympic Games shall be resolved by the IOC Executive Board.
Answer: I think this depends on the sport association and what it's rules are.
We have Chinese table tennis players that are associated with the USATT (United States Table Tennis).  They represent America in the Olympics but they weren't born here and (probably) don't have citizenship.
Maybe some associations require country citizenship, maybe not.
Comment: The question is explicitly about Olympic regulations, which will take precedence over what any association wants to do. The other answer makes clear that citizenship is a necessity for entry under the NOC.


Editing UITableviewCell when table is inside scroll view not working

Question: I'm trying to put a UITableView inside a UIScrollView. The scroll view is a horizontal paging setup to switch between a few pages/views.
One of those views has a table with editable cells. The problem arises when I try to swipe horizontally on the table to edit them. The scroll view captures the swipe first and pages over. I know the tableview is collecting touches because I can scroll vertically on it no problem.
As soon as I disable scrolling on the scrollview I can swipe to edit the cells in the table.
Is there anyway to get it so I can swipe on the table to edit cells but then still scroll on the view if I don't swipe on the table, or a header of the table that isn't editable?
Thanks
Answer: You should subclass the UIScrollView and implement below method
    - (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
This will make the UIScrollView to pass on touches to content view which is UITableview.


How to check if all async tasks have finished

Question: I am building a HERE MAPS based web application. I'm trying to implement getting the driving directions to work from >= 2 waypoints.
So the user inputs his adresses. Firstly, the application has to geocode these addresses to avoid errors.
This is the form submit event handler:
$('.form-directions').on('submit', function () {
    waypoints = [];
    $('.waypoint').each(function () {
        geoCode($(this).val());
    });
    return false;
});

This is the geoCode() function:
function geoCode (address) {
    nokia.places.search.manager.findPlaces({
        searchTerm: address,
        onComplete: onGeoCodingCompleted,
        searchCenter: map.center
    });
}

This is an async task, when finished it calls onGeoCodingCompleted(), which is the following:
function onGeoCodingCompleted(data, requestStatus, requestId) {
    if (requestStatus == "OK") {
        var locations = data.results.items;
        waypoints.push(locations[0].position);
    } else if(requestStatus == "ERROR") {
        alert("error");
    }
}

So after the geocoding process is completed, I'd like to plan the driving directions. The problem is, that I don't know if all the geocoding processes have finished. If the user submits ex. 150 addresses, it would take longer than if 2 addresses were submitted.
tl;dr
How can I set up a handler that calls a function when all of the geoCode() tasks have finished?
Comment: look into [jquery deferred](http://api.jquery.com/category/deferred-object/)
Answer: You can use promises.
$('.form-directions').on('submit', function () {
    var promises = [];
    waypoints = [];
    $('.waypoint').each(function () {
        promises.push(geoCode($(this).val()));
    });
    $.when.apply(null, promises).then(function() {
        // Everything is done, do something
    });
    return false;
});

And then in your geoCode function
function geoCode (address) {
    var deferred = $.Deferred();
    nokia.places.search.manager.findPlaces({
        searchTerm: address,
        onComplete: function(data, requestStatus, requestId) {
            onGeoCodingCompleted(data, requestStatus, requestId);
            deferred.resolve();
        },
        searchCenter: map.center
    });
    return deferred.promise();
}

Comment: Thanks! Seems like it works, I get the geocoding data from the addresses, however the $.when.apply() function never fires. I put an alert inside, I log all the results, but even when all of the results are logged, there isn't any alert. Maybe it's because it's in the form submit event?
Comment: @Trisztan I'm not sure why that's not working. I set up a jsfiddle (using google maps geocoding since I have access to it) and it's working: http://jsfiddle.net/EkLr7/. Hopefully it can help lead you in the right direction.
Answer: Use jquery deferred. Example code:
function do_stuff(){
    var deferred = $.Deferred();

    $.getJSON('/whatever.php/?callback=?',params,
        function(response){
            deferred.resolve(response);
        });

    });
    return deferred;
}
$.when( do_stuff() , do_stuff() ).done(function(a1, a2) {
    console.log('Stuff 1:' + a1);
    console.log('Stuff 2:' + a2);
});


A question about Non-Abelian Tensor Product

Question: Recently, I read an old paper "Some computations of Non-Abelian Tensor Products of Groups" By R. Brown, D.L Johnson and E.F Robertson. There are some assumptions to construct this structure. They pointed that :

"Let $G$ and $H$ be groups which acts on themselves by conjugation and each of which acts upon the other in such a way that the compatibility conditions hold."

What is the action in which two groups acts on each other? I see the relations in a tensor product is the same as for commutators. Please send me a useful link about this structure. Thanks
Comment: A good example for groups acting on each other compatably is to suppose $G,H$ are **normal** subgroups of a group $K$. Then the commutator map $G \times H \to K$ is well defined, is a biderivation, and factors through the morphism $\kappa: G \otimes H \to K$.
Answer: The actions of the general nonabelian tensor products can be any actions; you just need $G$ to act on the underlying set of $H$, $H$ to act on the underlying set of $G$, and for the actions to satisfy the compatibility conditions.
In practice, though, the most common action is given by some kind of conjugation, especially when $G$ and $H$ are either equal or subgroups of some larger group; or by automorphisms, but they need not be. For example, Zac Thomas has considered the problem of computing all possible tensor products of cyclic groups, where the mutual actions are arbitrary (though compatible).
There is a close connection between nonabelian tensor products (particularly nonabelian tensor squares when the action is conjugation) and commutators. See in particular L-C Kappe's Nonabelian tensor products of groups: the commutator connection, Groups St Andrews in Bath, 1997, II, 447-454, London Math. Soc. Lecture Notes Ser. 261, Cambridge University Press, 1999.
In the case where $G=H$ and the mutual action is conjugation, you obtain the nonabelian tensor square of $G$. In this case, the connection to commutators is even stronger. There is a nice commutative diagram that connects the nonabelian tensor square, the nonabelian exterior square, and the second homology group of $G$:
$$\begin{array}{cccccccc}
& & & & 0 & & 0 \\
& & & &\downarrow & & \downarrow\\
H_3(G)& \longrightarrow& \Gamma(G/G') & \longrightarrow & J_2(G) & \longrightarrow & H_2(G) & \to& 0\\
& & \downarrow & & \downarrow & & \downarrow\\
0 & \longrightarrow & \nabla(G) & \longrightarrow & G\otimes G & \longrightarrow & G\wedge G & \to & 1\\
& &\downarrow & &\downarrow & &\downarrow\\
& & 1 & & [G,G] & = & [G,G]\\
& & & & \downarrow & &\downarrow\\
& & & & 1 & & 1
\end{array}$$
The maps from $G\otimes G$ and $G\wedge G$ to $[G,G]$ are the "obvious" ones: you map $g\otimes h$ to $[g,h]$. One can interpret $H_2(G)$ as the group that contains all relations satisfied by the commutators in $G$ that are not universally satisfied (see, e.g., Clair Miller, The second homology group of a group; relations among commutators, Proc. Amer. Math. Soc. 3 (1952) 588, 595, MR 0049191 (14,133c)). All rows and columns are exact.
The connection in  the general case can be also be realized thanks to a construction of Rocco (and independently by Graham Ellis and Frank Leonard) which gives the nonabelian tensor product by first constructing a group generated by copies of $G$ and $H$, and realizing the nonabelian tensor product precisely as the subgroup $[G,H]$ sitting inside it. (Although the papers discuss the case of the nonabelian tensor square, they generalize easily; N.R. Rocco, On a construction related to the nonabelian tensor square of a group, Bol. Soc. Brasil. Math. (N.S.) 22 (1991) no. 1, 63-79, MR 1159385 (93b: 20060); Graham Ellis and Frank Leonard, Computing the Schur multipliers and tensor products of finite groups, Proc. Roy. Irish Acad. Sect. A 95 (1995) no. 2, 137-147, MR 16603783 (99h: 20084)).
Comment: +1: once again, an incredible amount of information has been packed into this answer.
Comment: @Babak Sorouh: The nonabelian tensor square is generated by symbols of the form $g\otimes h$, with $g\in G$, $h\in H$, subject to certain relations. So the elements of the nonabelian tensor square are products of tensor symbols,$$(g_1\otimes h_1)(g_2\otimes h_2)\cdots(g_k\otimes h_k),$$but you have all sorts of relations among them. Finding a nice description of the nonabelian tensor square as a "known" group is generally a hard problem, even for simply groups (e.g., nil-2 groups).
Comment: Thanks for an incredible amount of information as Pete pointed. May I ask you: Does an element of G⊗H look like a WORD? If not, how can consider any elemnts of this group? I am new to this beautiful structure and sorry for asking long. :)
Comment: Indeed, as you pointed, working with these elements seems strange. For the last question about this structure, may I ask you kindley to give me a hint of how to proof the CM1 or CM2 (Crossed module rules) in Proposition 2 in the paper I mentioned above? :)
Comment: @Babak: I don't have the paper with me, so I don't know what those rules may be, sorry.
Answer: The trick is to expand $mm' \otimes nn'$ in two ways to obtain the equation
$$ ^{mn}(m' \otimes n')(m \otimes n)= (m \otimes n) \; ^{mn} (m' \otimes n'). $$
For more details, see the 1987  paper by Brown and Loday in Topology from my publication list.
For more recent papers search the arXiv for "nonabelian tensor product" and see the bibliography
http://groupoids.org.uk/nonabtens.html
Edit: May 16,2013  I realise I need to make one comment on Arturo's answer, namely that when we say $G,H$ act on each other that means as groups, not just as sets. A very good example of this is when $G,H$ are both normal subgroups of a group $P$ say, so that $G$ acts on $H$ via $P$ and similarly for $H$ on $G$. More generally,  this happens if $G,H$ are crossed $P$-modules.
Another example is when two copies of the additive group of integers $Z$ act on the other one by $n \mapsto -n$ and on itself trivially. The paper by Gilbert and Higgins on the list calculates the nonabelian tensor product as $Z \times Z$.
It should be helpful to look at arXiv:1106.2136 for generalisations.
Comment: Thanks for your considreation. +1


$\sum_{r=1}^n \frac{1}{\sqrt{a+rx} + \sqrt {a+(r-1)x}}$

Question: Find the value of $$\sum_{r=1}^n \frac{1}{\sqrt{a+rx} + \sqrt {a+(r-1)x}}$$
Comment: Square covers the whole bracket part
Comment: You use way too many brackets.
Answer: Hint: rationalise the denominator , and see what you get when you write done a few terms of this series.
Comment: We get $$\sum_{r=1}^n  \frac{(\sqrt(a+rx) )-(\sqrt(a+(r-1)x))}{(x) }$$
Comment: Oh yes they are cancelling out
Comment: Thanks. I got then ans which is by the way $$\frac{(n)}{\sqrt( a+nx)+(\sqrt a) }$$
Comment: Yep ,now write down a few terms of this series. Some terms could be cancelled.
Comment: No problem , that's it yeah


Design ImageView with curved edges Android

Question: image of the modal designThis is the design I want to achieve in android, where the center one is image and the edges are rounded corners, when scrolled up it should scroll till the last
Answer: You can achieve this by using an imageView and a shape as background.
Also, you could use this library: https://github.com/hdodenhof/CircleImageView


How to override the display of a field in a view: is preprocessing possible?

Question: I want to override the display of a field in a particular view, so that rather than printing:

Content here

I just want:

Content here

Is this something which is best done in a template (I assume):
views-view-field--view-name--field-tagline.tpl.php

Edit: I've solved this using the above template, and then removing the wrapping elements from the view in via the Views UI. If using preprocessing is more performant, I'd still be interested to know, so please drop a line below if so. Otherwise, this question is solved.
Answer: I would suggest implementing the Semantic Views module. This allows you to easily customize the HTML that Views outputs for each level of elements (the entire view, row wrappers and field wrappers) from the UI. It is a bit easier to use and maintain than custom templates and preprocess functions.
Comment: Thanks for the heads up - I try to keep everything where possible in code and use version control for my development - ideally I'd be looking to keep this stuff in code too to ensure portability between sites and platforms. I'm not sure Semantic Views handles this?
Comment: Semantic Views is basically implemented as a Views display widget, so its settings can be exported with all other Views settings via the Views export.
Comment: Ah ok - interesting. Unfortunately I'm using Views3 and D7, so I'll just keep to overriding the templates for the moment. Thanks for the heads up, will mark this as a potential answer.
Comment: Most of the features of Semantic Views are already integrated into Views 3. Going by your last edit on your question, it seems that you have found that functionality :)
Comment: Yes indeed - thanks for the heads up - as I found out Views3 appears to incorporate much of what SV did, so thats a great step forward. Cheers for your help!


Cayley's theorem. Corollary 5 Dummit and Foote

Question: This is Corollary 5 in Dummit&Foote from chapter 4.2

It says it is isomorphic to a subgroup of $S_p$? Why $p$? What does $H$ having $p$ cosets have to do with this?
I am trying to understand all the definitions in Dummit/Foote. Is $H \stackrel{\pi_H}\to S_H$  defined as where $\pi_H(g)(aH) = \pi_H(aH) = gaH$?

They calls a given action of $G$ affords the associated permutation representation of $G$ (page 114). Is this the same as the action? I am really confused over the terminologies.
\strike 3. They also says Lagrange's theorem imply $pk$ divides $p!$. What does Lagrage have to do with this?\strike~~
The image is a subgroup of $S_p$, with divides the order of the group $|S_p| = p!$
Comment: Dummit & Foote has more than one author, so please say "they" rather than "he".
Comment: Every group of order $n$ embeds in $S_n$.
Comment: Look for Cayley's Theorem.
Answer: Let $X$ be the set of (left) cosets of $H$, so $|X|=p$. Then $G$ induces an action on $X$ via left multiplication: for a coset $xH \in X$, $G$ acts on $X$ via $g.xH = (gx)H$. With this action each $g\in G$ permutes the elements of $X$. That is, each element of $g$ corresponds to a permutation, and since $X$ has $p$ element, that permutation will live in $S_p$. This correspondence gives us a homomorphism $\pi_H \colon G \to S_p$, and the kernel of this map is $K$. By the first isomorphism theorem, we get $G/K \cong \mathrm{Im}(\pi_H) < S_p$.
Comment: igot another question. Is $\pi_H$ also the action? They way they describe $\pi_H$, makes it sound like it is a different map. But I know from the Cayley arguments that they are equivalent. Here $\pi_H: G \to S_p$, but normally actions are $\pi_H: G \times X \to X$
Comment: @Hawk Nah, $\pi_H$ isn't exactly the action. You invent $\pi_H$ based on the action.