Test which distribution has a "longer tail"

Question: I have measured two non-negative random variables, A and B. Their true underlying probabilities are unknown, however, it may be assumed that the probabilities are largest at zero and monotonically decrease for larger values. Most certainly, those values also have an upper bound and I have a guess for it, but that guess is not very good.
I would like to test if the "tail" of $P(A)$ "goes further" than the tail of $P(B)$. It looks like it does, but maybe that is by chance? What metrics could I consider? I have tried to check the mean, but it seems comparable for both variables.
Comment: Long tails, fat tails, and heavy tails are not synonyms: https://stats.stackexchange.com/questions/10726/differences-between-heavy-tail-and-fat-tail-distributions, https://stats.stackexchange.com/questions/168851/example-of-heavy-tailed-distribution-that-is-not-long-tailed. It will help if you can identify the kind of difference you want to identify. If your distributions are not bounded, then neither "goes further" than the other, as both shoot off to $\pm \infty$.
Comment: @Dave Thank you for the suggestion. Please pardon my ignorance, I am not an expert in statistics. I will read the provided link
Comment: Thanks for clarifying
Comment: When you say that you have measured the variables, how many observations do you have ? Can you repeat those observations ? If yes, you can probe your random variables to obtain an estimate of the densities $P(A)$ and $P(B)$, and hence compare their tails.
Comment: @CamilleGontier I am afraid the answers to those questions are not very important. (1) I have several thousand datapoints, but what matters is how close the tails are, that number may be too much or too few (2) I can't repeat the experiment, but I can split data into training and test set (3) I will not to density estimation, because it is not robust, especially at the tail which is guaranteed to be undersampled. I require a hypothesis test, something that will give me a rigorous number as an answer
Comment: From the question it sounds possible that what you're actually interested in is not the tail behavior per se -- that is, not the thickness of the tails -- but rather just the maximums of the two variables, i.e., max(A) vs. max(B). Do you agree with this?
Comment: @JakeWestfall I don't think I completely agree. Imagine a distribution consisting of several bins. We can take the last smallest bin and stretch it as far as we like, making it less an less probable. I believe that estimating max(A) of an unknown distribution is impossible with finite data sample. Instead, I need something like an "effective" maximum - the one that can realistically be falsified given the number of measurements is known
Answer: The essential features of this question are:

It does not make strong distributional assumptions, lending it a non-parametric flavor.
It concerns only tail behavior, not the entire distribution.

With some diffidence--because I have not studied my proposal theoretically to fully understand its performance--I will outline an approach that might be practicable.  It borrows from the concepts behind the Kolmogorov-Smirnov test, familiar rank-based non-parametric tests, and exploratory data analysis methods.
Let's begin by visualizing the problem.  We may plot the empirical distribution functions of the datasets on common axes to compare them:

The black curve shows dataset $A$ (here with $m=50$ values) and the red curve shows dataset $B$ (here with $n=100$ values).  The height of a curve at a value $x$ shows the proportion of the dataset with values less than or equal to $x.$
This is a situation where data in the upper half of $A$ consistently exceed the data in the upper half of $B.$  We can see that because, scanning from left to right (low values to high values), the curves last cross around a height of $0.5$ and after that, the curve for $A$ (black) remains to the right of -- that is, at higher values than -- the curve for $B$ (red).  That's evidence for a heavier right tail in the distribution from which data $A$ are drawn.
We need a test statistic. It must be a way of somehow quantifying whether and by how much $A$ has a "heavier right tail" than $B.$  My proposal is this:

Combine the two datasets into a dataset of $n+m$ values.
Rank them: this assigns the value $n+m$ to the highest, $n+m-1$ to the next highest, and so on down to the value $1$ for the lowest.
Weight the ranks as follows:

Divide the ranks for $A$ by $m$ and the ranks for $B$ by $n.$
Negate the results for $B.$

Accumulate these values (in a cumulative sum), beginning with the largest rank and moving on down.
Optionally, normalize the cumulative sum by multiplying all its values by some constant.

Using the ranks (rather than constant values of $1,$ which is another option) weights the highest values where we want to focus attention.  This algorithm creates a running sum that goes up when a value from $A$ appears and (due to the negation) goes down when a value from $B$ appears.  If there's no real difference in their tails, this random walk should bounce up and down around zero.  (This is a consequence of the weighting by $1/m$ and $1/n.$)  If one of the tails is heavier, the random walk should initially trend upwards for a heavier $A$ tail and otherwise head downwards for a heavier $B$ tail.
This provides a nice diagnostic plot.  In the figure I have normalized the cumulative sum by multiplying all values by $1/\sqrt{n+m+1}$ and indexing them by the numbers $q = 0/(m+n), 1/(m+n), \ldots, (m+n-1)/(m+n).$ I call this the "cranksum" (cumulative rank sum).  Here is the first half, corresponding to the upper half of all the data:

There is a clear upward trend, consistent with what we saw in the previous figure.  But is it significant?
A simulation of the cranksums under the null hypothesis (of equally heavy tails) will settle this question.  Such a simulation creates many datasets of the same sizes as the original $A$ and $B$ (or, almost equivalently, creates many arbitrary permutations of the combined dataset) according to the same distribution (which distribution it is doesn't matter, provided it is continuous); computes their cranksums; and plots them.  Here are the first thousand out of 40,000 that I made for datasets of size $50$ and $100:$

The faint gray jagged curves in the middle form the assemblage of a thousand cranksum plots.  The yellow area, bounded in bold curves (the "envelope"), outlines the upper $99.25$ and lower $0.75$ percentiles of all 40,000 values.  Why these percentiles?  Because some analysis of these simulated data showed that only 5% of the simulated curves ever, at some point, go past these boundaries.  Thus, because the cranksum plot for the actual data does exceed the upper boundary for some of the initial (low) values of $q,$ it constitutes significant evidence at the $\alpha=0.05$ level that (1) the tails differ and (2) the tail of $A$ is heavier than the tail of $B.$
Of course you can see much more in the plot: the cranksum for our data is extremely high for all values of $q$ between $0$ and $0.23,$ approximately, and only then starts dropping, eventually reaching a height of $0$ around $q=0.5.$  Thus it is apparent that at least the upper $23\%$ of the underlying distribution of data set $A$ consistently exceeds the upper $23\%$ of the underlying distribution for dataset $B$ and likely the upper $50\%$ of ... $A$ exceeds the upper $50\%$ of ... $B.$
(Because these are synthetic data, I know their underlying distributions, so I can compute that for this example the CDFs cross at $x=1.2149$ at a height of $0.6515,$ implying the upper $34.85\%$ of the distribution for $A$ exceeds that of $B,$ quite in line with what the cranksum analysis is telling us based on the samples.)
Evidently it takes a little work to compute the cranksum and run the simulation, but it can be done efficiently: this simulation took two seconds, for instance.  To get you started, I have appended the R code used to make the figures.
#
# Testing whether one tail is longer than another.
# The return value is the cranksum, a vector of length m+n.
#
cranksum <- function(x, y) {
  m <- length(x)
  n <- length(y)
  i <- order(c(x,y))
  scores <- c(rep(1/m, m), rep(-1/n, n)) * rank(c(x,y))
  cumsum(scores[rev(i)]) / sqrt(n + m + 1)
}
#
# Create two datasets from two different distributions with the same means.
#
mu <- 0          # Logmean of `x`
sigma <- 1/2     # Log sd of `x`
k <- 20          # Gamma parameter of `y`
set.seed(17)
y <- rgamma(100, k, k/exp(mu + sigma^2/2)) # Gamma data
x <- exp(rnorm(50, mu, sigma))             # Lognormal data.
#
# Plot their ECDFs.
#
plot(ecdf(c(x,y)), cex=0, col="00000000", main="Empirical CDFs")
e.x <- ecdf(x)
curve(e.x(x), add=TRUE, lwd=2, n=1001)
e.y <- ecdf(y)
curve(e.y(x), add=TRUE, col="Red", lwd=2, n=1001)
#
# Simulate the null distribution (assuming no ties).
# Each simulated cranksum is in a column.
#
system.time(sim <- replicate(4e4, cranksum(runif(length(x)), runif(length(y)))))
#
# This alpha was found by trial and error, but that needs to be done only
# once for any given pair of dataset sizes.
#
alpha <- 0.0075
tl <- apply(sim, 1, quantile, probs=c(alpha/2, 1-alpha/2)) # Cranksum envelope
#
# Compute the chances of exceeding the upper envelope or falling beneath the lower.
#
p.upper <- mean(apply(sim > tl[2,], 2, max))
p.lower <- mean(apply(sim < tl[1,], 2, max))
#
# Include the data with the simulation for the purpose of plotting everything together.
#
sim <- cbind(cranksum(x, y), sim)
#
# Plot.
#
q <- seq(0, 1, length.out=dim(sim)[1])
# The plot region:
plot(0:1/2, range(sim), type="n", xlab = "q", ylab = "Value", main="Cranksum Plot")
# The region between the envelopes:
polygon(c(q, rev(q)), c(tl[1,], rev(tl[2,])), border="Black", lwd=2, col="#f8f8e8")
# The cranksum curves themselves:
invisible(apply(sim[, seq.int(min(dim(sim)[2], 1e3))], 2,
          function(y) lines(q, y, col="#00000004")))
# The cranksum for the data:
lines(q, sim[,1], col="#e01010", lwd=2)
# A reference axis at y=0:
abline(h=0, col="White")

Comment: At first glance, this looks very similar to the log-rank statistics?
Answer: I would suggest to fit different distributions on your observations, and to perform model selection to find the distribution that fits your observations the best. Exponential and Pareto distributions seem to be the best candidates given your hypotheses (positivity, monotone decrease). Once you have fitted these candidates distributions, model selection criteria, such as the Akaike Information Criterion (AIC) or the Bayesian Information Criterion (BIC) will give you a quantitative score for each model. The following paper will propose rules on how to interpret the evidences for the different models based on the BIC :
Kass, Robert E., and Adrian E. Raftery. "Bayes factors." Journal of the american statistical association 90.430 (1995): 773-795.
You may also want to have a look at this paper which deals with model inference of long-tailed distributions :
Okada, Makoto, Kenji Yamanishi, and Naoki Masuda. "Long-tailed distributions of inter-event times as mixtures of exponential distributions." arXiv preprint arXiv:1905.00699 (2019).
Comment: This doesn't look appropriate to the question unless the fitting *is in the tails only.*
Comment: Thank you for your suggestion. As far as know, conclusions based on Bayesian Model Selection rely on the assumption that one of the models is the true model. I don't know how to ensure this, or how to estimate the error I may be introducing by choosing the wrong model. I could use Kolmogorov-Smirnov to test if the data are consistent with the proposed distribution, but for real mesured data from unknown distribution the KS test for a simple distribution is almost always negative. Further, the distributions you have suggested have infinite tails. How do I compare A and B then if I fit them?
Answer: The OP wants a metric for "tail length." While that term is not precisely defined, one might assume that "tail heaviness" is desired. Both Pearson-based and quantile-based kurtosis are measures of tail heaviness.  (This useful application of kurtosis has long been unused because of the incorrect notion that kurtosis measures "peakedness" rather than "tail heaviness.")  See here https://math.stackexchange.com/questions/3521769/graphic-representation-of-kurtosis-and-skewness/3532888#3532888 for a clear explanation of why Pearson kurtosis measures tail heaviness.
Estimate such a tail heaviness by using the data for each sample, and find the sampling distribution of the difference.  Use this sampling distribution to assess (or test, as the OP wants) the "true magnitude" of the difference between the heaviness of the tails. You could use the bootstrap here, although some kinds of parametric or smoothed bootstrap analysis may be more reliable. (Tail heaviness is very difficult to estimate because it is only the rare extreme values in the data (or outliers) that provide the relevant information, and there are by definition very few of such data points.)
Comment: Although it's good to point out the need for a more specific concept of "tail length," I would suggest that this answer over-interprets the question, because the question only asks how to test whether one tail is "fatter" than another. That doesn't require any metric nor even any concept of "heaviness" in the tail.  Kurtosis certainly is inappropriate, because it depends just as much on the *lower* tail (which is irrelevant here) as on the upper tail.
Comment: I did mention quantile-type measures; you could define one for the upper tail.   You could also define a one-sided version of Pearson kurtosis easily enough.  And the OP did ask for a metric. ("What metrics could I consider?"), so I was just trying to be helpful.
Comment: And actually, since ordinary Pearson kurtosis nearly discards the data within one sd of the mean, it probably would serve just fine for the OP's intent.
Comment: I was going to disagree ;-), but then realized you are cleverly relying on an unstated assumption that is likely true: with the positive variables described in the OP (unimodal with mode at zero), there probably isn't much to the lower tail, so higher moments might work. Why kurtosis, though? Its recommendation raises two interesting questions. First, why the *fourth* moment; second, why center it at the *mean*? For instance, an absolute moment about zero (or some standardized version thereof) would likely work better.
Comment: Sure, many other options are possible, such as right tail kurtosis, median centering, IQR scaling, etc. It just depends on how far in the weeds does the OP wish to go. At least with kurtosis, there is something tried and true; no need to justify an unusual metric.  And even if there is something the left tail, it will be negligible compared to the right. Skewness would also work here, though, as a measure of right tail heaviness for the OPs intended application.  Higher moments could work as well, but they will be perhaps too dependent on the extremes.


Como sumir com o efeito Parallax com angular?

Question: Como posso sumir com a ação do parallax quando este estiver com o um atributo?
está é a tag que possui o atributo:
<parallax-image ng-class="{{fixo}}"
src="/parallax-image/assets/images/image-01.jpg"></parallax-image>

Este é o css que está com o atributo:
[class^="fixo"] {
  background-color: color($grey, 200);
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  display: block;
  height: 0;
  overflow: hidden;
  padding-bottom: 40%;
  position: relative;
  width: 100%;
}

E o js é este:
if ('.fixo' == true) {
   return true;
} else {
  return false;
}

Answer: O seu uso de ng-class está errado. A definição correta seria:
ng-class="{'fixo': meuValor}" //Onde "meuValor" é um $scope do controller ex.: $scope.meuValor

Neste caso, a classe fixo será adicionado quando o $scope.meuValor for true
Outro método, caso você queira definir uma classe OU outra baseado no mesmo valor, seria:
ng-class="meuValor ? 'fixo' : 'nao-fixo'"

Neste caso se o $scope.meuValor for true será adicionado a classe fixo, se não será adicionado a classe nao-fixo.
Note então que o seu JS deverá mudar para ser algo semelhante a isso:
if( 'algum comparativo') {
    $scope.meuValor = true;
else {
    $scope.meuValor = false;
}

Como você não forneceu muita informação, essa parte da lógica depende do seu contexto, mas com essas informações creio que você consiga resolver o problema.
Comment: Ola Celsom eu coloquei desta forma:
o script está assim:
Comment: E o html está assim:

{{alt}}
Comment: Mas parece q o css não está carregando.
Comment: @Marcos você está colocando aquele script diretamente no corpo da página? Se sim, ele não vai funcionar mesmo. Precisa estar vinculado a um controller (ou directive - ou outro método equivalente),
Comment: Ele esta vinculado a um controler sim @CelsomTrindade...so coloquei o codigo para você ver... O script está funcionando pelo que vi no console, mas o css que criei para o fixed ele não esta retornando.
Comment: Verifique se a classe 'fixed' está sendo adicionada ao elemento. Se não estiver, certifique-se de que o valor de `hasEffect` está sendo atualizado, pois a declaração me parece tudo certo.


Determine the following subsets of R3 are subspaces of R3. If so, give a proof, and if not, explain why.

Question: U1={(x, y, 1)|x, y are real numbers}
U2={(a, a - b, b)|a, b are real numbers}
U3={(r, s, t)|r, s, t are non-negative numbers}
For U1:

According to the Zero Vector: $\lt x, y, 1\gt \neq \lt 0, 0, 0\gt$

According to Under Addition: $\lt 0, 0, 1\gt + \lt 0, 0, 1\gt = \lt 0, 0, 2\gt$ Not a part of the set
This is not a subspace of $\mathbb{R}^3$
For U2:

According to the Zero Vector: $\lt a, a-b, b\gt = \lt 0, 0, 0\gt$

According to Under Addition $\lt 0, 0, 0\gt + \lt 0, 0, 0\gt = \lt 0, 0, 0\gt$

This is a subspace of $\mathbb{R}^3$
With U3 however, (0,0,0) can work, but in order for the statement to be correct r, s, & t would all have to be greater than or equal to 0. I can use the obvious Zero Vector method, but what about Under Addition or Under Multiplication?
Comment: Hello, and welcome! Do you know what it means for a subset of $\Bbb R^3$ to be a *subspace*? If not, look it up in your notes or whatever you're studying from. For each of these subsets, try carefully checking if each requirement for it to be a subspace holds. If you get stuck on anything specific doing that, you can ask a question about it. Just get your hands dirty a bit first!
Comment: I figured I should just ask for help was all. Even looking through my notes it doesn't make sense.
Comment: It's OK if it doesn't make sense, but please just tell us specifically what doesn't make sense and show what you tried! A subset $U \subseteq \Bbb R^3$ will be a subspace if a) $0 \in U$, and b) whenever $x \in U$ and $y \in U$, we have $x + y \in U$ and c) whenever $\lambda \in \Bbb R$ and $x \in U$, we have $\lambda x \in U$. (There are some other, allegedly shorter, characterisations.) Can you write down whether or not you think each of these conditions holds for each of your subsets?
Comment: You will also need to show closure under scalar multiplication for part 2 (for part 1 it is enough to find one reason why the subset is *not* a subspace).  Keep scalar multiplication in mind when you try part 3, but your partial work is correct (non-negative entries are closed under vector addition and the zero vector is included).
Answer: $U_1$ isn't a subspace because it doesn't contain the zero vector.
$U_2=\rm {span}\{(1,1,0),(0,-1,1)\}$, and is thus a subspace.
$U_3$ is not closed under scalar multiplication.
Answer: Linear algebra can be a bit tricky when it first comes to learning subsets, but if you understand the axiomatic approach, then it becomes much clearer.
As stated in the comments, a subset $U⊆R^3$ will be a subspace if $a) 0∈U$, and b) whenever $x∈U$ and $y∈U$, we have $x+y∈U$ and c) whenever $λ∈R$ and $x∈U$, we have $λx∈U$.
In other words, $U$ must be equal to trivial solution of $(0,0,0)$ since its in $R^3$. And there must be closure under multiplication and addition by the other two axioms.
All three axioms must be true for $U$ to be a subspace. If you notice that the trivial solution $(0,0,0)$ is not equal to $U$, since $U$ = {$(x,y,1)$ for some $x,y$ real numbers}. Meaning, no $x$ and $y$ can make $U$ = {$(0,0,0)$} And so, $U$ is not a subspace of $R^3$.
After checking the first axiom, check for closure.
Closure under addition states that $m,n∈W$, then $m+n∈W$.
Closure under multiplication states that $m,n∈W$, then $mn∈W$.
By closure under multiplication, you want to see if scalar multiples of $m,n$ will be elements of $W$. So, if any scalar $c$ is multiplied by $m,n$, then you need to check if $cm$ or $cn$ will satisfy the conditions of the set $W$. So, if $W$ has the condition that elements must have non-negative numbers, then it won't be closed under multiplication since $c$ can be any scalar, so it could be negative. And so, multiplication of elements of $W$ with a negative $c$ value will give you a negative number, not satisfying conditions of $W$.
To see if $m+n∈W$ and $mn∈W$ hold, you must check to see the conditions of the set $W$. So, if $W$ has the condition that $m,n∈W$, such that $m$ and $n$ are real numbers, then you need to check if $m+n∈W$ and $mn∈W$ will give real numbers too and thus, be elements of $W$.
Hope this helps you get started. (I haven't done linear algebra in a while so if any one notices any error on my part, then feel free too comment or imporve the post)
Comment: I just edited my post. Am I on the right track or is there still more that needs to be done?
Comment: It's good that you have worked with the trivial solution! Now you if that axiom holds, you want to move onto the next axioms for closure under addition and multiplication. Have you learnt spanning sets and linear dependence yet?
Comment: Maybe try https://www.khanacademy.org/math/linear-algebra/vectors-and-spaces/subspace-basis/v/linear-subspaces
Comment: Just updated the post, I will need help on U3 since I'm a little lost on how to get the statement correct.
Comment: I made edits and explained it in the post.


Acessar function declarada na controller da directive pelos objetos transclude

Question: Estou tentando criar uma directive que tem seu scope isolado, mas que tenha algumas funções que ela estará responsável de fazer p/ directive. É uma div que contém uma table e um botão "Adicionar" ao clicar no adicionar abrirá abaixo da table um tipo formulário pra alimentar aquela table. Usei transclude p/ este formulário e gostaria de ao clicar em um determinado button (incluso no transclude) venha executar as functions que determinei na directive p/ copiar os registros pra table de forma dinamica, para que não venha a cada controller que usar esta diretiva tenho que fazer tudo na mão esta funcionalidade. Segue os códigos abaixo:
HTML Directive:

            <button type="button" class="btn btn-success" data-toggle="collapse" data-target="#divForm{{idGrid}}">Adicionar</button>

            <ng-transclude></ng-transclude>

grid-form.directive.js :
(function() {
    'use strict';

    angular
        .module('controlwebApp')
        .directive('gridForm', gridForm);

    function gridForm () {
        var directive = {
            restrict: 'E',
            transclude: true,
            scope: {
                options: '=',
                idGrid: "@idGrid"
            },
            templateUrl: 'app/components/grid/gridform/grid-form.directive.html',
            bindToController: {
                teste: '&'
            },
            controller: function (){
                this.teste = function(){
                    console.log("Teste Calling!!")
                }
            },
            controllerAs: 'ctrl'
        };

        return directive;
    }

})();

Uso da directiva:

        <grid-form id-grid="grid1" options="vm.gridOptions">

                Qtd Estoque Max1
                <input type="number" class="form-control" name="qtdEstoqueMax" id="field_qtdEstoqueMax" ng-model="vm.produto.qtdEstoqueMax" />
                Qtd Estoque Max2
                <input type="number" class="form-control" name="qtdEstoqueMax" id="field_qtdEstoqueMax" ng-model="vm.produto.qtdEstoqueMax"/>
                <button type="button" class="btn btn-primary" ng-click="ctrl.teste()">Save me</button>

        </grid-form>

Answer: Você pode criar um objeto para servir de ponte entre os escopos do controller e da directive; O conteúdo transportado terá assim acesso aos métodos implementados pela diretiva.
Exemplo funcional abaixo:

angular.module('myApp', [])
.directive('transcludeableDirective', function() {
  return {
    scope: {
      bridgeObject: "="
    },
    templateUrl: 'myTranscludeTemplate',
    transclude: true,
    controller: function($scope) {

      // Diretiva implementa evento event()
      $scope.bridgeObject.event = function(){
        alert('Evento da diretiva chamado!');
      };
    },
  };
})
.controller('myController', function($scope){
  $scope.bridge = {}; // Note que o controller não implementa o método.
});

      TESTE
      <button ng-click='bridge.event()'>CLICK!</button>

Comment: Perfeita estrategia brother, funcionou corretamente. Obrigado, infelizmente não tenho pontos ainda suficiente pra dar +1 na sua resposta =(      Tive um probleminha na minha controller da directiva, um erro(https://docs.angularjs.org/error/$injector/strictdi) que já consta na doc. do angular a correção pra Controller normais, resolvi assim:  controller: ['$scope', function($scope) {
          $scope.gridBindObject.onteste = function(){
           alert("Funcionou");
          }
         }]
Comment: @RaulMarques Nem estressa com isso, fico feliz que tenha funcionado. Se for o caso, marque como resposta aceita se seu problema tiver sido resolvido. =)


Trying to make linguistic sense of multiplication as scaling.

Question: I understand scaling of a number for it to be enlarged/shrunk by a scale factor/multiplier. Thus 3 scaled by a factor 2 means for it to become twice as big as itself. (2 units of 3 will be the new image instead of just the 1). For a factor 3 it'll be 3 times as big (3 units of 3), and for 4, 4 times as big.
However if 5 is scaled by a factor 1, that means for it to be made larger "one times" as itself which to me is translating as 5 being added to itself once. If 1 was to be scaled by a factor 5, that would mean to me that 1 was to be made 5 times larger (the new image will have 5 units of 1 instead of just 1).
I have this same confusion in 0 being scaled or something being scaled by 0 and also how negative scaling results in a negative with the same magnitude.
Sorry for the bundle of questions, I am trying to understand the scaling going on instead of the addition of multiples.
thanks
Comment: And why are you trying so hard to add confusion  to a well-understood, associative, (often) commutative and distributive (with addition) operation like multiplication? Mathematics is hard enough as it is, there's no need to make it still more obscure.
Comment: I am not "trying" to make it hard. That is exactly what I understand it to be and if it's an incorrect interpretation then I would like a better way to consider it. (scaling of an object, not multiplication itself).
Comment: No, you aren't just trying, you are succeeding. Interpreting multiplication as scaling (as you do in your title) in general is utterly wrong. Multiplication is multiplication. Scaling is a special case of multiplication of something (not a number, in general, more likely an element of some vector space, or a geometric figure, or...) by a scalar (and that's the **linguistic** reason why it's called **scalar**, by the way). So you have it almost right, just... upside down
Comment: When you scale by a factor of $1$, you should not add the original to the copy. When you scale by $5$, for example, you don't add the original either; you simply look at the result.
Comment: @Théophile then if the new image is 5 and the old was 1, then the old was made 5 times as large as 1. Can the 5 not be seen as the same result as have 5 quantities of 1 stacked in within each other?
Comment: Sure, if you like. This is fine for whole numbers. The point I was making is that when you multiply by 1, the new image is "1 quantity of 1", i.e., it's the same as before. You don't add it to the old one.
Answer: I'd like you to focus on these two sentences:

Thus 3 scaled by a factor 2 means for it to become twice as large as itself.

However if 5 is scaled by a factor 1, that means for it to be made one time larger than (larger "one times" as) itself.

The first construction is unambiguous even when adapted to the degenerate case:

3 scaled by a factor 2 means for it to become once as large as itself.

I'd advise against using it at dinner with the Queen, though.
The second construction appears to be inherently ambiguous. See Quora or anything you can google out of "three times larger than".
Comment: @salman I wouldn't use the term "composed" (because in mathematics "composition" is something else, and in fact the composition of two scalings by $y$ would be a scaling by $y^2$). I'd stick to the usual "*sum of* $y$ *copies of* $x$".
Comment: Got it, many thanks that clears up the (n+1) thing.

If 3 is scaled by a factor 1, it is to be made as large as itself once (that is to say, we're making 3 as large as how large 1 unit of 3 is).

If 3 is scaled by a factor 0, it is to be made as large as itself no times. (That quite literally is to say, it's NOT to be made bigger at all?)

In scaling of say, x by factor y, are we saying that x is being composed of itself "y times"?
Comment: ok so is it appropriate to say in the case 3 scaled by 6 that the new number (18) is as large as 6 multiples of 3 combined together. (Or is this a completely flawed way to consider scaling?). How is negative scaling done? We have (-1) to be scaled by 2, so it becomes twice as small as itself which is 2 multiples of (-1) combined together?


Extending a year range of a popup calendar

Question: Good day
Is there a way I can extend a year range of a popup calendar in drupal 7?
Answer: Provided you have a Date field, the widget you use is the "Pop-up calendar" and there is no data in the field yet, you can edit the field and it holds the settings as shown below. Increment the ending year in the field settings


Do I need that $\mathrm{Ord}$ is well-founded before proving that it is totally ordered?

Question: The ordinals are totally ordered, i.e. for $\alpha,\beta\in\mathrm{Ord}$ we have
$$\alpha\in\beta\quad\vee\quad\beta\in\alpha\quad\vee\quad\alpha=\beta.$$
Each proof I have seen so far started like this: Assume ther are incomparable ordinals. Choose an $\in$-minimal ordinal $\alpha$ so that there is an incomparable ordinal $\beta$.
But how can we do this? How do I know that there is an $\in$-minimal ordinal? I think the axiom of regularity does not help me here, because $\mathrm{Ord}$ is a proper class. Do I have to show that $\mathrm{Ord}$ is well-founded before proving totallity?
Comment: There are other proofs, that don't use well-foundedness. But another way to see an $\in$-minimal such ordinal is to say "Let $\alpha$ be such an ordinal and let $\beta$ be the minimum in $\alpha +1$. Then $\beta$ is $\in$-minimal."
Comment: What axioms are you starting with?
Comment: @Asaf ZFC and ordinals are defined as transitive sets with all elements being transitive too.
Answer: You can prove that given any ordinal $\alpha$, the ordinals below $\alpha$ are linearly ordered.
Now if $\alpha$ and $\beta$ are two ordinals, consider $x$ to be the transitive closure of $\{\alpha,\beta\}$. I claim that $x$ is a transitive set (by definition) whose elements are all transitive sets, this is because $$x=\operatorname{tcl}(\{\alpha\})\cup\operatorname{tcl}(\{\beta\})=\alpha\cup\beta\cup\{\alpha,\beta\}.$$
So $x$ is now an ordinal such that both $\alpha$ and $\beta$ are less than $x$. So they are comparable by the general proof given before.
Comment: Then we need the existence of the transitive closure. All proofs I found for this are using $\omega$ *or* using the existence of recursively defined function which itself is proved using $\omega$. Doesn't this give new problems using the smallest infinite ordinal in such an early phase?
Comment: That might depend on how you formulate some of the axioms. If you know $\omega$ is a set, you can prove what is missing with ad hoc proofs, where necessary. Then you get the existence of transitive closures.


Xamarin.Forms PCL MVVM Light > Custom Control > Best Practice?

Question: Hy
I would like to share my approach for a custom xamarin.forms control within a Xamarin PCL Project with MVVM-Light. What do you think about it?
Custom Control -> PersonPanel.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="xxx.PersonPanel">
  <StackLayout Orientation="Vertical">

    <Entry x:Name="filterText" Placeholder="{Binding FilterPlaceholderText}" Text="{Binding Filter.Lookup}" TextChanged="OnFilterTextChanged"/>

  </StackLayout>
</ContentView>

Code-Behind -> PersonPanel.xaml.cs:
public partial class PersonPanel : ContentView
{
    public PersonPanel()
    {
        InitializeComponent();

        //Init ViewModel
        BindingContext = ServiceLocator.Current.GetInstance<PersonPanelViewModel>();
    }

    private PersonPanelViewModel PersonPanelViewModel
    {
        get
        {
            return (PersonPanelViewModel)BindingContext;
        }
    }

    public string TitleLabel
    {
        get
        {
            return PersonPanelViewModel.TitleLabel;
        }
        set
        {
            PersonPanelViewModel.TitleLabel = value;
        }
    }

    public string FilterPlaceholderText
    {
        get
        {
            return PersonPanelViewModel.FilterPlaceholderText;
        }
        set
        {
            PersonPanelViewModel.FilterPlaceholderText = value;
        }
    }

    private void OnFilterTextChanged(object sender, EventArgs e)
    {
        PersonPanelViewModel.SearchCommand.Execute(null);
    }
}

ViewModel -> PersonPanelViewModel:
public class PersonPanelViewModel : ViewModelBase
{
    private IPersonService _personService;

    private decimal _personId = 0;
    private string _titleLabel = string.Empty;
    private string _filterPlaceholderText = string.Empty;
    private string _resultText = string.Empty;
    private bool _resultTextVisible = true;

    public PersonPanelViewModel(IPersonService personService)
    {
        _personService = personService;

        // Init Filter
        Filter = new PersonFilter();

        // Init Commands
        SearchCommand = new RelayCommand(Search);
    }

    public ICommand SearchCommand { get; set; }

    public PersonFilter Filter
    {
        get;
        private set;
    }

    public string ResultText
    {
        get
        {
            return _resultText;
        }
        set
        {
            Set(() => ResultText, ref _resultText, value);
        }
    }

    public bool ResultTextVisible
    {
        get
        {
            return _resultTextVisible;
        }
        set
        {
            Set(() => ResultTextVisible, ref _resultTextVisible, value);
        }
    }

    public string FilterPlaceholderText
    {
        get
        {
            return _filterPlaceholderText;
        }
        set
        {
            Set(() => FilterPlaceholderText, ref _filterPlaceholderText, value);
        }
    }

    public string TitleLabel
    {
        get
        {
            return _titleLabel;
        }
        set
        {
            Set(() => TitleLabel, ref _titleLabel, value);
        }
    }

    public decimal PersonId
    {
        get
        {
            return _PersonId;
        }
        set
        {
            Set(() => PersonId, ref _PersonId, value);
        }
    }

    private async void Search()
    {
        //Reset
        ResultText = string.Empty;
        ResultTextVisible = false;
        PersonId = 0;

        if (Filter.PersonLookup != null && Filter.PersonLookup.Length >= 3)
        {
            //Call to Person Service
            List<PersonResult> Person = await _personService.FindpersonByFilter(Filter);

            if (Person.Count == 1)
            {
                PersonId = Person[0].PersonId;

                ResultText = Person[0].PersonName;
                ResultTextVisible = true;
            }
        }
    }
}

Using of Control in another View:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:components="clr-namespace:xxx.ViewElements.Components"
             x:Class="xxx.MainPage">
  <StackLayout Orientation="Vertical">
    <components:PersonPanel x:Name="personPanel" TitleLabel="Person" FilterPlaceholderText="Type your search criteria here..."/>
  </StackLayout>
</ContentPage>

I'm using Autofac as the IOC Container.
What do you think about it? I am using MVVM the right way (it's very new to me)?
Is there a better way to deal with calling the Command from the Event (TextChanged) on the view?
What's about the properties in the Code-Behind (which do a routing to the ViewModel)?
Edit:
I'll try to describe, what I want to achieve:

Creating our own control (reusable in different views, cross-platform) -> PersonPanel.xaml
Written in XAML in our PCL Project with pure Xamarin.Forms controls in it
The control should have it's own commands (Search) and properties
One of the commands is using a Service
The control should get the Service (as an Interface) injected through IOC
The Service itself is also implemented in the PCL Project and makes a REST Call to a Webservice
The Result of the Call is than set to a property of the control -> ResultText Property
The Result is visible to the User

-> With the above implementation, all of that works, but I'm not sure if this is the right way...
Thanks for your help!
Kind regards,
Peter
Answer: The approach for mapping the event to the command is exactly as I would perform.
The rest is a little bit confusing. The general pattern is to create bindable properties in your control that are exposed to the view model when instantiated within the host view. A very basic sample structure is below:
public class TestLabelControl : Label
{
    public static readonly BindableProperty TestTitleProperty = BindableProperty.Create< TestLabelControl, string> (p => p.TestTitle, null);

    public string TestTitle {
        get {
            return (object)GetValue (TestTitleProperty);
        }
        set {
            SetValue (TestTitleProperty, value);
        }
    }
}

public class TestContentPage : ContentPage
{
    public TestContentPage()
    {
        var testLabel = new TestLabel();
        testLabel.SetBinding<TestContentPageViewModel>(TestLabel.TestTitleProperty, vm => vm.TestLabelTitle, BindingMode.Default);
        Content = testLabel;
    }
}

public class TestContentPageViewModel
{
    public string TestLabelTitle{get;set;}

    public TestContentPageViewModel()
    {
        TestLabelTitle = "Something random";
    }
}

You would then create the native renderers to handle the drawing on each platform.
By following this approach you keep the code separated and concise. It does seem a slightly long winded way of getting things done but it is highly scalable and configurable.
Comment: Is it right to have a ViewModel for my Component with for example the Logic for the search?
This Logic is setting another Property of the Component-ViewModel (ResultText), how is this
Value exposed to the view?
My idea is to have a component (ContentView) with its own ViewModel for reusing.
This component should than be used by other controls.
I think I understand the bindable properties in the Code-Behind File, but I'm not sure how they
are connected to the Component-ViewModel.
We don't need native renderers, we just use xamarin.forms components. Thanks for your help
Comment: If you are wanting to build a reusable control it should be as agnostic as possible with the logic been applied by the viewmodel of the relevant view.  This is the only way you can ensure that the control does not become bloated with conditional code. Perhaps, if you detailed what you are trying to achieve, the community would provide a more detailed example


recovering from a plaintext password in usermod -p

Question: My small office's server was under attack yesterday and today and apparently the hacker gained access through a weak password (i.e. I am to blame entirely). The moment I noticed this, I fysically disconnected the server from the internet and changed all the user passwords (with kpasswd), and the root password (with usermod -p).
I had no internet to consult and was a little stressed out, which is why I entered the plaintext password instead of the encrypted hash I was supposed to enter.
Does anybody know how I can 'compute' the un-hashed plaintext?
Comment: I would rebuild a server from scratch after an attack.  You don't know what the attacker did to anything.  If it's a file server or a web server, you can easily migrate files (after looking deeply at them).  It's worth the little bit of time.
Comment: I have already asked my system admin to have a deep look and it was about time to buy a new server, so this will be the occasion to do just that. In the meanwhile I would like to at least monitor suspicious activity, whichis what I need the root password for :(
Answer: First of all, It was good point about reinstalling server from scratch.
If you have set your encrypted root password in /etc/shadow, there is no efficient way to guess It, because It is encrypted using cryptographic hash function. If you have set it to some plaintext value, the password will be threated as invalid and will not be accepted anyway, because passwords in shadow database are stored in particular format.
If you have physical access to server, you can reboot In single user mode via bypassing kernel option single (or init=/bin/bash for Ubuntu), there is a tutorial. Then you can change your root password by using passwd and reboot system to access it as usual.
The good practice is to avoid root access via ssh and use sudo to gain superuser privileges. Also you can disable password authentication for OpenSSH and switch to Public key authentication.
UPD: I don't have enough reputation to answer to your comment, so updating the answer: you can boot to single user mode by changing kernel boot parameters in bootloader. It doesn't require password unless you had set up the one for Grub. Please check out the tutorial I've mentioned above to perform single user boot.
Comment: @UPD: the single-user-mode is a no go: I need to supply the root password to go into 'maintenance'. This is with typing 'linux single' at the LILO prompt. My system admin reminded me that he had added me to the sudoers file and had elevated my privileges. I was able to change the root passwd using sudo - otherwise I would have been completely locked out of root access to my server... Thx for thinking with me (+1), but your reply did not solve my problem.
Comment: Thank you for your comment - I had completely forgotten to reboot in single-user mode. Unfortunately, one has to enter the root passwd before entering the single-user-mode (Press CTRL+D for maintenance or...).


Using eval in defing Python class data attributs

Question: I wonder if it possible to use eval to creates class data attributes. Something like following code:
class Test:
    def __init(self):
        matrix_names = ['F', 'B', 'H', 'Q', 'R', 'x', 'P']
        for matrix in matrix_names:
            print matrix
            operation = "self.%s = self.__matrix_read(%s)" %\
             (matrix, matrix)
            eval(operation)

    def __matrix_read(self, filename):
        return (read(".matrix/%s.csv"%filename))

In iPython I get:
File "<string>", line 1
   self.F = self.__matrix_read(F)
       ^
SyntaxError: invalid syntax

Comment: Why do you want to do this?!
Comment: use `exec` instead of `eval`. `eval` is to evaluate - just expressions, no statements.
Answer: You can use setattr build in function:
class Test:
    def __init(self):
        matrix_names = ['F', 'B', 'H', 'Q', 'R', 'x', 'P']
        for matrix in matrix_names:
            print matrix
            setattr(self, matrix, self.__matrix_read(matrix))

Answer: Do not use eval for this. Other, better ways already exist if you wish to define attributes at runtime.
If you want the attributes defined and built at instantiation, use setattr() as is recommended in @PasteBT's answer.
If you want the answers to be dynamically expandable, use __getattr__() (good answer clarifying its behavior here).
For example:
class Test:
    def __init__(self):
        self.matrix_names = ['F', 'B', 'H', 'Q', 'R', 'x', 'P']

    def __matrix_read(self, name):
        return (read(".matrix/%s.csv"%filename))

    def __getattr__(self, name):
        if name in self.matrix_names:
            return self.__matrix_read(name)

Or, another way (IMHO cleaner, but YMMV):
class Test:
    # note that this is only called if the attr does not exist
    def __getattr__(self, name):
        try:
            with open(".matrix/{0}.csv".format(name)) as f:
                return f.read()
        except IOError:
            raise AttributeError("{0} does not exist".format(name))

(in python 3 replace IOError with FileNotFoundError). This way, you are not bound to a pre-built list of files, which may or may not be desirable depending on your application.


Why do we want (Restricted) Boltzmann Machines to be stochastic?

Question: Boltzmann machines are stochastic recurrent neural networks with a specific architecture, and they are interesting in several contexts.
They are stochastic in the sense that the sampling procedure involves repeatedly computing the activation functions for the next layer (hidden from visible or visible from hidden), sampling from the result, and using the obtained sample (as opposite to directly using the activation functions) for the next iteration.
I do wonder though, why is the stochasticity useful here?
If we want to compute the feature vector corresponding to a given input, do we use a sample from the hidden neurons' activations, or do we use directly the activations?
Using the same architecture as the RBM, but with deterministic neurons, would seem to also fit more naturally with the probabilistic energy-based interpretation: the activations on the visible layer after a pass through the hidden layer would directly correspond to a "proper" conditional probability of getting that output given the input, as opposite to just being the conditional probability of that output given a sample obtained from the conditional probability over the hidden layer given the used input.
The stochasticity seems to also make the training kind of weird. If the neurons are taken to be deterministic wouldn't the whole architecture effectively correspond to a regular feedforward NN with a given number of hidden layers (and some relations between the weights and biases of the layers), which could be trained using standard backpropagation?
Comment: You're asking how RBM is different from logistic (sigmoid) activated neural net?
Comment: @Aksakal I guess that is part of the question yes. How is it different form a sigmoid activated neural net with same kind of topology, and more generally where/why does the stochasticity help.
Comment: So, you're not asking how stochasticity is used to find optimal weights? I mean annealing type of optimization is not what you're asking about
Comment: @Aksakal I don't know, I'm not sure what you mean by that. If that is the reason why RBMs are chosen to be *stochastic* nets, then yes that would be a possible answer I think. It may be a very basic question, as I don't think I grasp the concept behind RBMs very well atm
Answer: Stochastic component in RBM (such as sampling from Boltzmann distribution) is used to find the optimal parameters of the RBM.
RBM itself is used to extract higher level features. You pre-train an RBM layer, then plug into the deep network. You train RBM in an unsupervised manner, somewhat similar to PCA or autoencoders.
For instance, AI people are used to think of PCA as a dimensionality reduction tool, which it is. However, it can be thought of a feature extractor too. Consider, interest rates on the market. You can borrow for 1 year or 10 years. If you go the market there would be quotes for borrowing to anything from overnight to 100 years, and each will have its own interest rate. It turns out that if you run these rates through PCA and look at first three components then something like this comes out:

So, the unsupervised (dumb) PCA was able to extract three features that are interpreted as level, slope and the curvature of the interest rate yield curve. These features are widely used in finance.
So, RBM serves a similar purpose in the neural net. It's pre-trained separately to extract some features from the input, then these features are passed along to the next layer in the network.
Comment: So am I understanding correctly that the stochasticity is only used at training time? But my question remains: why use a stochastic activation at all, instead of a more regular sigmoid activation, to extract said features?
Comment: It's the technical difficulty of calculating the gradient of energy for optimization routine. It turns out that the practical way is through some kind of Monte Carlo. See the last equation in the first section [here](http://www.iro.umontreal.ca/~lisa/twiki/bin/view.cgi/Public/DBNEquations). That gradient is impossible to deal with analytically


How to prove that ideal is not principal

Question:
Let $F$ be a field and $R$ be the subring of polynomials $F[x]$ such that coefficient of $x$ is zero. Let $I$ be the ideal of $R$ such that constant term is zero.
I have to prove that $I$ is not a principal ideal of $R$.

To show that I will have to prove that every element of $I$ is not generated by a single element of $R$. But to me it seems that every element of $I$, say, $f(x)= a_2x^2+a_3x^3+\dots+a_nx^n$ can be generated by an element of $R$, say, $g(x)=b_0+b_2x^2+\dots +b_mx^m$ by taking $b_2=b_3=\dots=b_n=0$, i.e.
$f(x)=b_0(\alpha_2x^2+\alpha_3x^3+\dots+\alpha_nx^n)$
where $b_0=g(x)$ and $\alpha_2x^2+\alpha_3x^3+\dots+\alpha_nx^n$ belongs to $R$. Thus it seems to me a principal ideal generated by $g(x)$. So what am I missing here? Please help.
Comment: That's what I was referring to! You've to be careful when choosing generators to not accidentally get too much. For example, the unit element $1$ "generates" every ideal in any ring by your argument. But it will never really generate any proper ideal. (I re-added my comment below)
Comment: You are correct in so far that the ideal generated by $g(x)$ (or any constant for that matter) *contains* $I$. But as the constants are units in $R[x]$ the principal ideal generated by $g(x)$ will be the whole ring instead of only $I$ which is a proper subset of $R[x]$.
Comment: @mrtaurho Ideal generated by generator $g(x)$ thus will contain polynomials containing constant terms also? And since $I$ does not contain any polynomials having constant terms, does that make I non-principal ideal?
Answer: Hint: look at $x^2$ and $x^3$. Can you find a non-unit $f\in R$ with $g,h\in R$ so that $fg=x^2$ and $fh=x^3$? There's a solution under the spoiler, but give yourself a chance before looking at it, please.

 No - by examining the factorization $fg=x^2$ in $F[x]$, we find $f=cx^2$, but then writing $h=h_0+h_2x^2+\cdots$, we have that $fh=ch_0x^2+ch_2x^4+\cdots$.


What is the difference between Gregorian chant and Gothic chant?

Question: I understand both belong to the plainchant class of music from the pre-Renaissance period. However, I am not sure if they differ in any identifiable way. I have also heard the term Roman chant being used but I suppose that's just synonymous with Gregorian chant.
Here are two different pieces I listened to (off YouTube) for reference:

Kyrie
Dies Irae

The guys who have posted the videos on YouTube have described the Kyrie as Gothic chant and the Dies Irae as Gregorian. To my ears though, they hardly seem different in character. How do I tell them apart?
Answer: I don't know a huge amount about plainsong however I can think of a couple of possibilities.  The first thing to note is that there are definitely some differences between the two videos you post: the Kyrie has elements of polyphony whilst the Dies Irae seems to be mostly in unison.
Gothic could refer to the specific period between the 9th and 14th centuries http://www.mfiles.co.uk/classical-periods.htm#Medieval
Looking at the comment on the Kyrie video, 'Organum Era Notre Dame School' it seems we are dealing with a specific type of plainsong, Organum.  Organum means plainsong with additional voices to add to the harmony.  The dates for when Organum music was developed roughly coincide with the Gothic period.
The wiki page for the Notre Dame School and this page are both informative too.
Note also that there is such a thing as 'Visigothic' or Mozarabic Chant, but this is a different style that developed on the Iberian Peninsula.  Compare this clip to the ones you posted:
Answer: Indeed they are similar! That particular Kyrie is called Cunctípotens Génitor Deus, one of many Kyries in Gregorian chant.
What they did, back in the Middle Ages, was borrow it from Gregorian chant, slow it way down, and resurface it with a second voice in a medieval improvization technique called organum, a well-known feature of Notre Dame polyphony, as Christophe mentioned. If you reverse the process by speeding up the Kyrie recording fast enough, the lower voice will sound nearly identical to this chant.
Organum is considered accompaniment, so it does not technically classify as plainsong, though it is based upon the same. While there are simpler organal accompaniments in 9th and 10th century Gregorian chant, the more florid "Gothic" Kyrie leans far closer to the polyphonic side of the spectrum. Keep in mind, at the time it was composed, plain vs. polyphonic was not a hard and fast division between genres, but rather just a simple matter of whether the cantors felt like spontaneously improving the music that day in church.
The term "Gothic chant" appears to be novel. I could trace it only back to Callixtinus' YouTube channel. I wouldn't be surprised if the term originated there. A web search reveals it hasn't been used in any context that wasn't influenced by Ensemble Organum's popularity on the web.
By the way, yes, Roman chant is synonymous with Gregorian chant ... most of the time.


Compression in Drupal 7

Question: I am running Drupal (latest version 7.22 ) on Apache 2.2 and I have also installed Varnish (module and proxy). In Apache, I have disabled the mod_deflate module.
Reading around the web, it seems that the options on the performance page in Drupal (aggregate css,js) shouldn't compress the css and js files. However, browsing my site and checking the http headers, I see that I am receiving "Content-Encoding: gzip". Looking at the (default) .htaccess, I see that there are some rewrite rules in order to server gziped files to those clients that can read them. So, I guess this is where the "Content-Encoding: gzip" headers come from. Also, when I enable compression of cached pages on the performance settings page in drupal, I find that even the html of the page I am requesting (as anonymous user only) is returned compressed. My questions on the above are:
1) Do the options "Aggregate and compress CSS files." and "Aggregate JavaScript files." actually compress the aggregated files or is it just that .htaccess makes them seem like gziped? Using chrome developer tools, the files seem compressed. Checking them with the developer toolbar addon in firefox, however, (Information -> View document size) they are not reported as compressed (while the html file is always being reported as such, even when I access it as authenticated user!)
2) If they are indeed gziped, where does the compression take place? Can I control the level of compression, etc somehow?
3) I am always receiving X-Drupal-Cache "MISS". I don't care much since I have Varnish installed. Yet, since I am not hitting the cache, how come I am returned a compressed html file (that is not in the cache)?
4) Is there any chance that the Varnish module messes anything up? I am accessing the website with https so as to be sure that Varnish is bypassed, in any case.
5) If I enable mod_deflate, should I leave that part of .htaccess intact? I understand that mod_deflate doesn't allow for precompression, but what if the compression is better?
6) Also, if drupal compresses on its own the css, js and html files, what is the point of enabling mod_deflate for these files?
Here is the relevant part of my .htaccess file for reference:
<code>  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</code>
Answer: A start:
1) Yes.
Note: If I really want to know what is going over the line, I use fiddler (Windows).
2) See function drupal_build_css_cache() in common.inc (line 3603). You cannot influence the level but you can influence whether it compresses or not with variable 'css_gzip_compression', see default.settings.php line 432.
BTW: You do not want to influence the compression level: for compress once, use many cases, maximum compression is always the best. Transfer time and decompressing time at the client is linear with compressed document size. So a 1-time slightly increased performance hit will save a lot of network activity and client side processing in the future.
3) -
4) -
5) Compression will be better as it will be done only once and it will be done better versus mod_deflate that will compress on each request and therefore will use a lower compression level. I don't know much about mod_deflate, but I guess that if there is already a  Content-Encoding header that tells the content is compressed, mod_deflate should not touch it. But I have had cases where I got a backup file that was compressed twice, so mod_deflate might not be that smart and should  explicitly be told to do so.
6) There is no point, but there might be for other requests, especially dynamic ones, i.e. non cacheable pages. Note that only aggregated css and js and cached pages (variable 'page_compression') are compressed by Drupal. Non cacheable pages are not compressed by Drupal.
Answer: To sum up what I have found so far and fietserwin's answer.
1) Those options do compress. No matter what you have read elsewhere. I went through some bugs in the drupal bug tracker and there are a couple bugs (eg this discussion for d8) that discuss actually separating this behavior with different options in the Performance settings in drupal. Also, you can check it with Chromium devtools or Firefox Network panel (not through the size column, but by checking the response headers for Content-Encoding: gzip) and toggling the available options for css/js aggregation in drupal. The developer toolbar seems broken or I cannot understand what it does.
You can have aggregation but no compression by setting the css_gzip_compression and js_gzip_compression variables to FALSE (see fietserwin).
2) The compression happens in php code. For more detail, look fietswin's answer. Judging by his answer on the compression level, I guess that php (at least for drupal) compresses at the maximum level of compression. Note that compressing in php and not relying on the web server is common for many other php applications, eg owncloud, flyspray, etc.
3) This is a bit weird and still haven't figured out why it happens. I think it has to do with the varnish module. I am not saying varnish itself, since I am running varnish 2 with no compression support). It only happens when I access the site through varnish (ie, when I access it with https, which bypasses varnish, the page is not cached and not gzipped). And if I have the "Compress cached pages" option enabled. So, my guess is that the varnish module completely takes over the caching mechanism of drupal but still uses these options to set the behavior (compression,lifetime,etc) of the varnish cache.
Since I couldn't find any more info on this and I have mod_deflate set to gzip all html files, I disabled this option to prevent the cached pages from being double compressed. Maybe there is a check or sth, as with css/js, to prevent this but I haven't found one.
4) obsolete question
5) Compression should happen in drupal, not in apache. There, it only happens once (in a while). So the .htaccess  excerpt above should be left intact. What it does is:
<code>RewriteCond %{HTTP:Accept-encoding} gzip #if the client can handle compression
RewriteCond %{REQUEST_FILENAME}\.gz -s #and if the (aggregated css file already exists
RewriteRule ^(.*)\.css $1\.css\.gz [QSA] #serve the compressed file instead

# The same for js files
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

# Do no actual rewriting but set the no-gzip apache variable to inform apache not to compress the already compressed files.
RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
</code>
So this part should be left intact to safely take advantage of the whole mechanism. The compression, as said above, probably is the best possible.
6) To add to fietserwin's answer, there might be other apps running on the server as well. All in all, just enable compression for css and js in apache as well, and drupal's htaccess will prevent double compression.

Compression in Drupal 7


Get data from MySQL after draggable swap

Question: I'm having problem to get data from mysql when two draggable elements are swapped. Because swap action is performed inside $.post function.
$(function () {
    var parent_div_data;
    var field_array = ["tire_number", "bar", "mm_1", "mm_2", "mm_3"];
    $(".tire").draggable({
        containment: ".table_edit_data",
        scroll: false,
        appendTo: "body",
        cursor: "move",
        helper: 'clone',
        revert: "invalid",
        start: function (event, ui) {
            parent_div_data = $(this).parent().attr("id");
        },
        stop: function (event, ui) {
            setTimeout(function () {
                if ($('#' + parent_div_data).children().length == 0) {
                    $.each(field_array, function (index, value) {
                        $('#' + parent_div_data).parent().find('.' + value).val('');
                    });
                }
            }, 50);

        }
    });

    $("#tire_div").droppable({
        tolerance: "intersect",
        accept: ".tire",
        drop: function (event, ui) {
            $("#tire_div").append($(ui.draggable));
        }
    });

    $(".droppable_1, .droppable_2, .droppable_3, .droppable_4, .droppable_5, .droppable_6").droppable({
        tolerance: "intersect",
        accept: ".tire",
        activeClass: "div-droppable-default",
        hoverClass: "div-droppable-hover",
        drop: function (event, ui) {
            var url = 'class=<?= $this->reg['
            class '] ?>&"&action=get_tire_data';
            var this_data = $(this);

            $.post('index.php?' + url, {
                tire_id: $(ui.draggable).attr('data')
            }, function (data) { //data attribute contains `id`. And data is returned.
                if (this_data.find(".tire").length == 1) {
                    var first = this_data.find(':first-child'); //where elements swap is performed
                    $('#' + parent_div_data).append(first);
                    // $.each(field_array, function(index, value) {
                    // $('#' + parent_div_data).parent().find('.' + value).val(first.attr(value));
                    // });
                }
                this_data.append($(ui.draggable));
                this_data.parent().find('.tire_number').val(data.tire_number);
                this_data.parent().find('.bar').val(data.bar);
                this_data.parent().find('.mm_1').val(data.mm_1);
                this_data.parent().find('.mm_2').val(data.mm_2);
                this_data.parent().find('.mm_3').val(data.mm_3);
            }, "json");
        }
    });
});

Where swap action is performed (see comment in the code), do I need to add another post, to get values again, or can you advice another method. Thanks.
Comment: What exactly you want to do after a swap? Can you be more specific.
Comment: @HarryBomrah Each droppable `div` has input fields, which are filled when I drop element. (There are 6 `div` elements total, and each `div` can hold only one draggable element, if you drag another they are swapped). My problem if elements are swapped only one `div` input fields are filled. Because element swap action is inside `$.post` and this element cant get data from `mysql`
Answer: so you can add call a function which makes one more request to server  whenever there is a swap
$.post('index.php?' + url, {
            tire_id: $(ui.draggable).attr('data')
        }, function (data) { //data attribute contains `id`. And data is returned.
            if (this_data.find(".tire").length == 1) {
                var first = this_data.find(':first-child'); //where elements swap is performed
                $('#' + parent_div_data).append(first);
                //call your function here
               // for ex getData(first);
            }
            this_data.append($(ui.draggable));
            this_data.parent().find('.tire_number').val(data.tire_number);
            this_data.parent().find('.bar').val(data.bar);
            this_data.parent().find('.mm_1').val(data.mm_1);
            this_data.parent().find('.mm_2').val(data.mm_2);
            this_data.parent().find('.mm_3').val(data.mm_3);
        }, "json");


Excel: Freezing simultaneously a column and a row

Question: In Excel 2016 I know how to freeze the first column or the first row through the menu View -> Freeze Panes.
But how can I simultaneously freeze both the first column and the first row?
When I apply one of them it removes the other one.
How can I freeze any column or row not the first ones?
@gravity, this is your suggestion:

I don't have that option.
Answer: If you select cell B2, and under "View," choose "Freeze Panes," the first column AND row will be frozen simultaneously.
Expanding upon this, if you choose the upper-left most, singular cell, that you do not want to be frozen, and choose freeze panes, all panes above and to the left of that single cell are frozen.
Comment: OK, I don't know what I was doing wrong. Now it works, thanks.
Comment: I've pasted a screenshot in the main question.  I don't have that option, only unfreeze panes, freeze top row and freeze first column.
Comment: Unfreeze your panes first (since you've already incorrectly frozen a row or column by itself), *make sure you have the top-most left-most CELL (not row or column) you DON'T want frozen selected (probably B2)*, then simply choose "Freeze Panes" again.  You need to simply start over.
Comment: I'm sorry I was trying. By selecting A1 I got to freeze columns and rows, but not the first column and first row. Strangely it freezes rows 1 to 19, and columns A to G
Comment: You should not be selecting A1 at all.  Click 'Unfreeze Panes,' first.  Then, click **only in cell B2**.  Then, click 'Freeze Panes' again, and both Column A, and Row 1 will automatically be frozen.


What is the variance of a constant raised to a random variable?

Question: What is the variance of a constant $k$ raised to a random exponent $x$?
$$Var(k^x)=?$$
Answer: If $k >0$ this quantity is related to the moment-generating function of $X$.  Letting $t \equiv \ln k$ you have:
$$\begin{equation} \begin{aligned}
\mathbb{V}(k^X) = \mathbb{V}( \exp (t X))
&= \mathbb{E}( \exp (2t X)) - \mathbb{E}( \exp (t X))^2 \\[6pt]
&= m_X(2t) - m_X(t)^2. \\[6pt]
\end{aligned} \end{equation}$$
The specific functional form varies according to the distribution of $X$, and can easily be obtained by substitution of the form of the moment-generating function.  In the case where $k <0$ then $\ln k$ is complex, and the quantity is related to the characteristic function, but it is a bit more complicated.
Comment: Thanks! So if $X \sim N(\mu, \sigma^2)$ then $V(k^X) = e^{\mu \ln(k) + 2 \sigma^2 \ln(k)^2} - e^{2 \mu \ln(k) + \sigma^2 \ln(k)^2}$?
Comment: In first exponential, variance term should be divided by two, not multiplied by two.  Other than that, assuming $k>0$, that looks fine.


How to grab the ID of an artist so i can insert the album into the database with the artist's ID?

Question: Here is my schema:
CREATE TABLE artists
(
    id serial PRIMARY KEY,
    name varchar(40) NOT NULL UNIQUE
);

CREATE TABLE albums
(
    id serial PRIMARY KEY,
    name varchar(40) NOT NULL,
    artist integer NOT NULL,
    FOREIGN KEY(artist) REFERENCES artists(id)
);

CREATE TABLE songs
(
    id serial PRIMARY KEY,
    name varchar(40) NOT NULL,
    album integer NOT NULL,
    FOREIGN KEY(album) REFERENCES albums(id)
);

This is what I'm doing:
INSERT INTO artists (name)
VALUES ('Dio') ON CONFLICT DO NOTHING;
INSERT INTO artists (name)
VALUES ('Amorphis') ON CONFLICT DO NOTHING;

SELECT id FROM artists WHERE name = 'Dio';
SELECT id FROM artists WHERE name = 'Amorphis';

INSERT INTO albums (name, artist) VALUES ('Holy Diver', 1) ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist) VALUES ('Dream Evil', 1) ON CONFLICT DO NOTHING;
INSERT INTO albums (name, artist) VALUES ('Halo', 2) ON CONFLICT DO NOTHING;

Right now I'm inserting into albums by looking at the table for the artist ID and typing manually. How can I do this automatically?
My application will receive the song title, artist name and album name. So it will need to look for the artist ID if the artist exists and if not, create the artist, then grab the ID of said artist and put into the INSERT INTO albums statement.
Comment: Your appliction  built on which ORM hibernate or smth else?? I
Answer: One way:
INSERT INTO albums (name, artist)
SELECT 'Holy Diver' AS album_name, id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;

Another way to do multiple albums from the same artist at once. You can just list them in the VALUES definition.
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
     (
      VALUES ('Holy Diver'),
             ('Dream Evil')
     ) t(album_name)
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;

And another way for good measure:
INSERT INTO albums (name, artist)
SELECT album_name, id AS artist
FROM artists,
     (SELECT 'Holy Diver' AS album_name
      UNION
      SELECT 'Dream Evil') t
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;

And another way:
INSERT INTO albums (name, artist)
SELECT UNNEST(ARRAY['Holy Diver','Dream Evil']) AS album_name,
       id AS artist
FROM artists
WHERE name = 'Dio'
ON CONFLICT DO NOTHING;

Ok, I'll stop.
Comment: Thank you very much! The application will receive only one input of 'artist, song, album' at a time. It is a personal database for my music player, so no need for multiple albums at once.

I just managed to do it this way too:
 `INSERT INTO albums (name, artist) VALUES ('Holy Diver', (SELECT id FROM artists WHERE name = 'Dio')) ON CONFLICT DO NOTHING;`


ionic chamar function dentro do callback

Question: Estou tentando chamar uma função dentro da outra função porem ele fica dando:

ERROR ReferenceError: "closeGPS is not defined"
      enableGPS tab1.page.ts:35

meu codigo atualmente:
enableGPS() {
    console.log("enable gps");
    this.gps = true;
    navigator.geolocation.getCurrentPosition(function (local) {
        sessionStorage.setItem('lat', local.coords.latitude);
        sessionStorage.setItem('lon', local.coords.longitude);
        closeGPS();
    });
}

closeGPS() {
    this.close = true;
}

Answer: Troque o callback para uma arrow function (() => {}), dessa forma, o this irá referenciar o local em que closeGPS() está e, então, chame ela com o this
navigator.geolocation.getCurrentPosition((local) => {
    sessionStorage.setItem('lat', local.coords.latitude);
    sessionStorage.setItem('lon', local.coords.longitude);
    this.closeGPS();
});


django recreate dropped table

Question: I dropped a table manually cause while changing the model I made a very bad mistake. So anyway ... how can I recreate it ? I have tried :
- Delete the migrate folder of that app
- delete from django_migrations where app='main'
- makemigrations main
- migrate main

But it stops at the first table. Which is there :-( and my Table message in that case is not recreated. In 0001_initial.py I have the correct entry for my table
migrations.CreateModel(
        name='Message',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('created_at', models.DateTimeField(auto_now_add=True)),
            ('updated_at', models.DateTimeField(auto_now=True)),
            ('unread', models.BooleanField(default=True)),
            ('subject', models.CharField(max_length=120)),
            ('freetext', models.TextField(null=True)),
            ('from_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user', to=settings.AUTH_USER_MODEL)),
            ('to_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_user', to=settings.AUTH_USER_MODEL)),
        ],
    ),

Is there way to start this manually ?
Answer: Next time when you rollback:

Go into the migrations folder in your app.
Look for the migration file where you would like to go back to. (for example 0012_post_category.py)
go in the terminal write: ./manage.py migrate yourAppName 0012 (this is just an example number) and hit enter
if everything goes well. Delete the other migrations which came after this number in your migrations folder.

Do not just delete migrations! Hope that helps.
Comment: yes this helps. Next time I will do that :-) for my specific problem I have created a file `0002_message.py` containg just the create for table `message`. I have now `0001_initial.py` and `0002_message.py`. I wiped out all entries in `django_migrations` except `0001_initial` and ran `migrate main` and hurray table recreated. At least I do now understand better how this migrate stuff works
Comment: Of course I removed the entries for `message` in `0001_initial.py`
Comment: Ok very good. This is like my standard way if there are problems with the db. In 90% of the cases you can fix the problem like this
Answer: I think best way is to write your own migration file.
Under the migration folder create new migration file with DeleteModel method. for instance if your previous migration file name is '0065_auto_20210318_0000' so your file migth be:
class Migration(migrations.Migration):

    dependencies = [
        ('my_app', '0065_auto_20210318_0000'),
    ]

    operations = [
        migrations.DeleteModel(
            name='MyModel',
        ),
    ]

django recreate dropped table


Stumped in the middle of a PHP loop

Question: Here's what I've got so far-
$awards_sql_1 = mysql_query('SELECT * FROM categories WHERE section_id = 1') or die(mysql_error());
$awards_sql_2 = mysql_query('SELECT * FROM categories WHERE section_id = 2') or die(mysql_error());
$awards_sql_3 = mysql_query('SELECT * FROM categories WHERE section_id = 3') or die(mysql_error());
$awards_sql_4 = mysql_query('SELECT * FROM categories WHERE section_id = 4') or die(mysql_error());

$loop = 1;

while($row_sections = mysql_fetch_array($sections_query)) {
    $category = 1;
    echo "
" . $row_sections['section_name'] . " (Loop# $loop)
";

    while($categories = mysql_fetch_array(${"awards_sql_{$loop}"})) {
        ${"winners_sql_{$loop}"} = mysql_query("SELECT * FROM 2009_RKR_bestof WHERE section = $loop && category = $category ORDER BY result_level ASC") or die(mysql_error());
        echo "
{$categories['category_name']}
";
        echo "
";
>>          while($winners = mysql_fetch_array(${"winners_sql_{$loop}"})) {
                switch ($winners['result_level']) {
                    case 1: $result_level = "Platinum"; break;
                    case 2: $result_level = "Gold"; break;
                    case 3: $result_level = "Silver"; break;
                }
                if (isset($winners['url'])) { $anchor = ""; $close = ""; }
                echo "
$anchor{$winners['winner']}$close ($result_level)
";

                unset($anchor);
                unset($close);
            }
        echo "
";
        $category++;
    }
    $loop++;
}

Where I'm getting stumped, is I'm getting this thing to loop through correctly, my loop counter ($loop) is working, but when it gets time to spit out the actual reward recipients after the first loop through winners, it's only producing the category titles, the list-items are not getting looped out.
I added a little pointer to where I think the problem begins or centers around (>>).
My guess is I need to maybe unset a var somewhere, but I don't know, I can't see it.
Comment: I really don't understand your need to have 4 different queries, surely they could be combined into a single one?? and you could remove one of the loops??
Comment: Another reason to not use Arrow Code (Tons of nested If Statements), if you post it on Stack Overflow, it is really hard to read.
Comment: Also, I would look into how to use arrays: http://us3.php.net/manual/en/language.types.array.php
Comment: I'm not an experienced programmer so I'm learning as I go (re: multiple queries & arrays).
Answer: I'm with KM - you're displaying a single page and with your loops, you've got a LOT of queries happening at once - what if 1,000 people hit that page at the same time? ouch...
Maybe consider a larger query (with some repeated data) and loop through it once?
For example:
SELECT
  section_name,
  category_name,
  result_level,
  url,
  winner
FROM 2009_RKR_bestof
INNER JOIN categories ON 2009_RKR_bestof.category = categories.id
INNER JOIN sections ON 2009_RKR_bestof.section = sections.id
ORDER BY section_name,category_name ASC

In your loop, you can do checks to determine if you're in a new section (category/whatever):
//pseudo-code
$current_section = "";
while($stuff = mysql_fetch_array($sql))
{
  if ($current_section == "")
  {
    $current_section = $stuff["section_name"];
  }
  if ($current_section == $stuff["section_name"])
  {
    //keep going in your loop
  }
  else
  {
    //we've gotten to a new section - so close your html and start a new section
  }
}

You get the idea..
Comment: Kind of I guess.  I'm not that experienced, but I just ran that query of yours in SQLyog so I see what it's doing.  I'll just have to rework my loops I guess...I think I understand.
Comment: Definitely the best way to do this.  @Marty - if you have any other questions, you know where to ask them!
Comment: I'm pretty much lost now when it comes to the comment "keep going in your loop"
Comment: would that be a place to do something like:

while (in_array()) {

?
Comment: "keep going in your loop" was a way to indicate that you'd do your display logic, echo statements, etc - probably a bad choice of words.

My overall intent was to show that you can get everything done in a single query rather than a whole bunch of queries to get the same effect.
Answer: My guess would be that it is a data problem.  It isn't having trouble reading the titles, only the winners.  If it iterated once, I would check the data, and ensure that winners_sql_2 - winnders_sql_4 are getting actual data.  Perhaps add an echo winners_sql_2 line, to output the contents of the query, and ensure the query is framed correctly.

Stumped in the middle of a PHP loop


How to view javascript errors in ios simulator launced by phonegap?

Question: I can't seem to find an answer to this seemingly simple question.  I have an app that i've built using the command line phonegap tools and when i start this app it opens up.  i am using something called ios_sim (https://github.com/phonegap/ios-sim) which launches the app in the simulator and does not launch xCode (i don't quite understand why this is a feature, it seems like xCode has some useful tools)
Anyhow, my app is not functioning the same way that it does in the browser and i need to debug it.  I have also already installed Charles to inspect the requests and i can verify that the correct data is coming from my API so my assumption is that there is some sort of javascript error in rendering the page (the page is partially rendered btw).
All i want to do is view the javascript errors.  the same way that you would in the console if you were looking at a web page.
how do you do that?
Comment: Enable 'Develop' option from Safari. Then select from the 'Develop' menu 'Simulator', you will see app listed there, select it and in the new window will be able to access Debugger/Console
Answer: You have to use Safari Remote Debugging with Web Inspector. See in the relating cordova docs how to do that!
Comment: Thanks, I had looked at this before but my problem was that i was launching the app on my phone by launching the phonegap app and pointing it at the IP address shown on the PhoneGap Developer App.  Because i did it this way (rather than launching from xcode or the phonegap cli into a simulator) i was unable to do the safari remote debugging.    got it working with the simulator now, thanks.


"return" in my method doesn't return the value when the method is called

Question: Just finished up an assignment for my Java class; it was to create a class with a method that, when given two strings, searches for the second string in the first and counts the number of times it is found.
Here's the important bit:
for (int count = 0; count < l1; count++) {
    if (one.charAt(count) == two.charAt(0)) {
        for (int count2 = 0; count2 < l2; count2++) {
            if (one.charAt(count) != two.charAt(count2)) {
                break;
            }
            count++;
            if (count2 == l2 - 1) {
                twoCount++;
            }
        }
    }
}
System.out.println("There are " + twoCount + " \"" + two + "\"");
return twoCount;

I included the System.out at the end because when I call the method in another program, return doesn't actually return anything, as such:
test.stringFind(one, two);

output being:
----jGRASP exec: java StringSearchRun

There are 2 "love"
----jGRASP: operation complete.

Notice how there's just that one line from my System.out? My method in the class is defined as an int, as well as the twoCount variable. So what stupid mistake did I make?
Comment: You actually need to *use* the return value: `System.out.println(test.stringFind(one,two));`.
Answer: If you're method return type is int, then you have to do something with the returned value. By just calling the method and doing nothing else, nothing happens because there's either
A) No way to retrieve the returned value or
B) Nothing being done to the returned value
Why is this so? Think about it, where is the value being returned to after executing test.stringFind(one,two);? The method when called by itself returns a value that is garbage collected right away since the value's scope is only within the method call. Therefore, once the call is done, the value is discarded because it doesn't leave the scope of the method. So to fix this, either store it in another variable or use it in an expression. Here are some examples of what you can do with it in your main method,
int result = test.stringFind(one,two);

or
System.out.println(test.stringFind(one,two));

Comment: No problem, if you found the answer helpful then don't forget to mark it as accepted. Happy coding!


What is wrong in my answer relating Todd-Coxeter Algorithm

Question: The question is:
A triangle group $G^{pqr}$ is a group $<x,y,z|x^p,y^q,z^r,xyz>$, where $p \leq q \leq r$ are positive integers. In each case, prove that the triangle group is isomorphic to the group listed.
a) The dihedral group $D_n$, where p, q, r = 2, 2, n,
b) The octahedral group, when p, q, r = 2, 3, 4,
c) The icosahedral group, when p, q, r = 2, 3, 5.
I am working with question b), that is $<x,y,z|x^2,y^3,z^4,xyz>$
have $xyz = 1$ and $x^2 = 1$
I get $yz = x^{-1} = x$ and $yzyz=1$
Then $<y,z|y^3,z^4,yzyz>$ is homomorphic to $<x,y,z|x^2,y^3,z^4,xyz>$
I chose $H=<y>$ and found the $y=(243)$ $z=(1234)$ is the solution of $<y,z|y^3,z^4,yzyz>$, the detailed process is in the followed image:

I found when I set a = 3, I will get b = 2 and c = 4, also all tables are passed.
Then the order is $|G|=|H|[G:H]=3\times4=12$
But the order of octahedral group is 24, what in my answer is wrong?
Comment: How can we possibly tell what you have done wrong when you haven't shown the details of your calculation? You should get $8$ cosets of $H$, and something like $y=(2,3,5)(4,6,7)$, $z=(1,2,4,3)(5,7,8,6)$.
Comment: Thank you @DerekHolt, I added some details. I think your results are right, as your [G:H] is 8.
Comment: But you are not allowed to just guess entries in the tables, even if your guesses seem to work. All of your table entries have to be either definitions, or they have to be deduced from the tables. If you guess entries then the result might be a proper quotient of the group defined by the presentation. In this example, your permutations do generate $S_4$, but you have made the stabilizer larger than $H$, because $zyz$ fixes $1$. If you do the algorithm correctly, then the stabilizer of $1$ should be exactly $H$.
Comment: Thank you @DerekHolt. So, I should add rows to complete the table as I get uncertain entries.
Comment: Hi, @DerekHolt, I expand my table from 1-4 to 1-8, still I get lots of uncertain entries, can you show me how you get your results? thanks a lot.
Answer: Here is a summary of coset enumeration of the cosets of $H$. We know that $1y=1$.
Define $1z=2$, $2z=3$, $3z=4$, deduce $4z=1$.
Deduce $2y=4$ from $1yzyz=1$.
Define $4y=5$, deduce $5y=2$.
Define $5z=6$, $6z=7$, $7y=8$, deduce $8z=5$.
Deduce $6y=3$ from $4yzyz=4$.
Deduce $3y=8$ from $5yzyz=5$, and hence $8y=6$.
Finally, deduce $7y=7$ from $8yzyz=8$.


How to compute Cohen's d from means difference in T-Score (or Z-Scores) and its CI

Question: I am performing a meta analysis on longitudinal cohort studies reporting outcomes in cognitive performance as a function of adherence to a nutritional variable. Most of them provide "standardized means differences" or "standardized beta regression coefficients" which I can easily convert to a correlation coefficient.
However, there are some studies that only report the results of their regression analysis as raw means differences (95% CI, p value) derived by using the highest tertile (vs. lowest and middle) as reference for comparison. These means differences are expressed in transformed scores, either T or Z scores.
How can I compute a Cohen's d coefficient with this information?
My first thought was to calculate SE/SD from the CI but given the fact that they are asymmetrical I don't think that makes any sense. Should I just divide the value by the SD of T-Scores (SD = 10) or Z-Scores (SD = 1)?
Answer: Divide the mean difference by 10 for the T-scores and 1 for the Z-scores. The only issue here is that you are effectively dividing by the overall standard deviation rather than the within groups pooled standard deviation. For small values of $d$ this won't make much difference. For larger values it will. You can compute the pooled standard deviation for the T-Score values as
$$
  s_{pooled} = \sqrt{
    \frac{10^2(N-1) -
       \frac{\left(\overline{X}_1^2 + \overline{X}_2^2 -
       2 \overline{X}_1 \overline{X}_2 \right)}
      {N}}{N}} .
$$
For the z-score, drop the $10^2$ from the equation.


Why does this problem have one less root for x?

Question: Problem statement (Problem $6$):

This is my work below:

The answer of $x$ is $2$ and $8$. but my answer is $1$/ $\sqrt{3}$ and it is a credible answer if you solve it. Why is this happening?
Comment: The $x=2$ corresponds to $x-1=1$ and $1^a=1^b$ for every $a, b$
Comment: https://ibb.co/doDLcc
Comment: Your work yielded the answer $x = 81$. Are you mixing up the problems?
Comment: Nope there are two answers -81 and 2
Comment: Dude you did it so easily and I was like what the hell's wrong with me since 2-3 days. Thanks though you could've written it as an answer you know...to get the upvote
Comment: It's a hassle to write answers from the phone and imo 10k is enough for me, anyway it's mostly experience, the more problems you do the easier it will be for you to spot things like this.
Answer: There are two answers, $81$ and $2$.

If $a$ is positive, and $s,t$ are real, the equation
$$a^s = a^t$$
holds if and only if $a=1$ or $s=t$.

You analyzed the case $s=t$, which yields $x=81$.

You missed the case $a=1$, which yields $x=2$.
Answer: When $x=1/\sqrt3$, $x-1<0$ and so $(x-1)^7<0$.
But $|x-1|>0$ and so $|x-1|^{\textrm{nasty expression}}>0$.
Thus $1/\sqrt3$ cannot be a solution.
Comment: Yeah that's resolved even if I put it in the nasty expression but how does x=2 come? I mean this question has repeated twice in the book and has 2 as an answer both times...
Answer: Remember that you are looking for a solution under the condition $(x-1)>0$.
Note that since $t=\log_3 x$ the solutions are $x=81$ and $x=\frac1{\sqrt3}$.
As pointed out by quasi, the other solution come from the trivial case $x-1=1$.
Comment: Yeah but how does value of x come to be 2? I get the x-1>0
Comment: That could be... the study material's the nastiest then. This question was repeated further,in a multiple choice question. The three values we have -2,81,1/3^-1/2 were in the options and bam,2 was the answer again. Legend of Typos
Comment: A comment just answered that...
Comment: @DilinFinn Yes of course, we have also the case $x-1=1$ which leads to x=2.


Assign strictly one special bolt on each machine in storm cluster

Question: I would like to start special bolt on every machine in my cluster.
Storm has pluggable scheduler, but documentation is very scanty. There is only one understandable example from xumingming. How could be implemented this pattern using IScheduler ?
Example
We have TCPBolt, which listens port 8765. TCPBolt parallelism == cluster size. We need to start one instance of this bolt on each machine.
Answer: The example and source code gives enough demo code to do this.
First you need to set the task number of TCPBolt to be the host number of your cluser.
Then in your IScheduler impl, using data in private Map<String, SchedulerAssignmentImpl> assignments; to check if the TCPBolt is assign to a host ( in SchedulerAssignmentImpl, using data Map<ExecutorDetails, WorkerSlot> executorToSlot;)
Finally, if not assigned, using the following code to assign
// re-get the aviableSlots
availableSlots = cluster.getAvailableSlots(specialSupervisor);

// since it is just a demo, to keep things simple, we assign all the
// executors into one slot.
cluster.assign(availableSlots.get(0), topology.getId(), executors);

This is just a rough idea. Hope it helps.


How to map a component collection with compass?

Question: I need to map a collection of components with compass (using XML mapping)... Is there any way to achieve this?
Thanks in advance for any suggestions.
Example classes:
class ClassA {
    private Set<ClassB> bs;
    // ... getBs/setBs ...
}
class ClassB {}

Example mapping:
<class name="com.package.ClassA" alias="classA">

</class>
<class name="com.package.ClassB" alias="classB">
</class>

Answer: Yeah, just found out how to do this, the mapping is simple - you just apply the alias to the collection component/reference. Obviously all the rest is done implicitely.
<class name="com.package.ClassA" alias="classA">
     <component name="bs" ref-alias="classB" />
</class>
<class name="com.package.ClassB" alias="classB">
</class>


The difference between 'AND' and '&&' in SQL

Question: Is there a difference in the way SQL interprets the logical operators AND and &&?
Comment: You can use && and `and` in conjunction with each other. `WHERE title='cabbage' && type='vegetable' OR title='cherry' && type='fruit'`
Answer: AND is Standard SQL
&& is proprietary syntax
Answer: For mySQL: The manual is not saying it explicitly, but they are listed as identical:

AND, &&
Logical AND. Evaluates to 1 if all operands are nonzero and not NULL, to 0 if one or more operands are 0, otherwise NULL is returned.

The operator precedence page also makes no distiction.
Answer: If you're working with PostgreSQL, '&&' means overlap (have elements in common):
example: ARRAY[1,4,3] && ARRAY[2,1]
https://www.postgresql.org/docs/9.1/static/functions-array.html
Comment: I just noted the 'mysql' tag, so my answer does not relate specifically to the OP, but I think this might be still useful for people landing on this page.
Answer: According to this page http://msdn.microsoft.com/en-us/library/bb387129.aspx they have the same functionality in SQL Server.
MySql has this to say on the subject http://dev.mysql.com/doc/refman/5.0/en/logical-operators.html
Comment: That's not SQL Server syntax, that's Entity SQL syntax (from the Entity Framework). SQL Server only supports the standard SQL operator `AND`, not `&&`.


How to use sudo with rcp command to copy files from linux host to HP-UX host?

Question: I'm having this issue where when I try to use sudo to rcp some files from a Linux host to an HP-UX host (note that the destination directory requires root access to write to), I get the following error from HP-UX's side:
remshd: Login incorrect.

I should note that the passwords for the Linux host and the HP-UX host are different. The command doesn't seem to give me a chance to enter the proper HP-UX password and automatically defaults to this error.
Comment: Is root login disabled?  Can you login as root locally (i.e., as a login shell), or ssh from root to root?
Comment: [Please do not cross post](http://superuser.com/questions/442392/how-to-use-sudo-with-rcp-command-to-copy-files-from-linux-host-to-hp-ux-host). Server Fault is the correct place for this question.
Answer: The rcp man page says

Rcp does not prompt for passwords; it uses Kerberos authentication ...

You'll probably find it easier to use scp to do this. If you allow root logins via ssh on ypor HPUX system then
scp -r /local/path firstname.lastname@example.com:/remote/path

should do the trick. If you don't allow root logins then login to the HPUX host and obtain a root shell then
scp -r firstname.lastname@example.com:/remote/path /local/path


user/logout access denied v7.34

Question: Admin or normal user can not logout using www.myswebsite.com/user/logout
An access denied page is displayed and the user is still logged.
using ?q=user/logout works.
It is not a rewrite problem, all other url are ok.
I have cleared the cache and deleted the cookies, tried on FF, IE & Chrome.
Any idea to investigate ?
Comment: Are you using fb functionality to your site ?
Comment: Nope, modules used are:
nagios, CKEditor, IMCE
Comment: Actually this issue occurred due to SESSION.
Comment: If you are using any custom module & hold the SESSION or any SESSION created in any module then first check & try to close that SESSION. Your issue will solved.
Comment: I have trash the session table, issue is still present.
Comment: Refer to this link : https://www.drupal.org/node/1022932#comment-4003886
Comment: I don't get why ?q=user/logout works and not /user/logout

I have no trace of the 403 for /user/logout into apache log??

http://pastebin.com/PuC65g7C
Answer: Try different way

This works for me if I substitute the logged-in username for 'user', like this:

http://my_site/my_user/logout
ie:
http://example.com/jdoe/logout

this might be problem with not enabling clean url in your site go to

http://example.com/admin/config/search/clean-urls
enable clean url and check if its working

as you mentioned use http://example.com/user/logout will logout the current user section

Further readings:
logout problem - https://www.drupal.org/node/1572984
enabling clean url - https://www.drupal.org/node/1572984
access denied + logout - https://www.drupal.org/node/2192401
Comment: so you have clean url enabled and when user go to user/logout he is still logged in.
Comment: clean url is working without problem. Your two links are the same.
Comment: yes, as far I remember it was working. I have only change the css of my theme and the page content, nothing special.
Answer: I have found the root cause. The Geocaching. I am in Australia and the server is in France. The missing of /user/logout into the apache log warns me. I have tested with a french proxy and everything is ok.
My provider offers Geocaching, the page looks to be cached.
I have purge the geocache and /user/logout works!!
The first hit of a 403 for /user/logout triggers the same problem.
This is easy to understand, when user/logout is success, the answer is a 302, nothing is added into the cache whereas a 403 is permanent so it is stored.
This explains why ?q=user/logout works, it is a query no caching is done.
To summarize deactivate the geocaching.

user/logout access denied v7.34