What are efficient algorithms to compute singular value decomposition (SVD)?

Question: The Wikipedia article on principal component analysis states that

Efficient algorithms exist to calculate the SVD of $X$ without having to form the matrix $X^TX$, so computing the SVD is now the standard way to calculate a principal components analysis from a data matrix, unless only a handful of components are required.

Could someone tell me what are the efficient algorithms the article is talking about? There is no reference given (URL or citation to an article proposing this way of computation would be nice).
Comment: A Google search on [singular value decomposition algorithm](https://www.google.com/search?q=singular+value+decomposition+algorithm) does a fine job of highlighting relevant information.
Comment: Don't forget to remove the mean before SVD for PCA!
Comment: Try Lanczos SVD!
Answer: The main work-horse behind the computation of SVD is the QR algorithm. Having said that there are many different algorithms to calculate the singular value decomposition of a generic $M$-by-$N$ matrix $A$. A great schematic on the issue available here (from the documentation of Intel's MKL) is the following:
As you see depending on your use case there are different approaches (the routine naming conventions can be found here). That is because, for example there are matrix forms where a Householder reduction can be more expensive than a Givens rotation (to name two "obvious" way of getting QR). A standard reference on the matter is Golub's and Van Loan's Matrix Computations (I would suggest using at least the 3rd edition). I have also found Å. Björck's Numerical Methods for Least Squares Problems very good resource on that matter; while SVD is not the primary focus of the book it helps contextualizing the use it.
If I have to give you one general advice on the matter is do not try to write your own SVD algorithms unless you have successfully taken a couple of classes on Numerical Linear Algebra already and you know what you are doing. I know it sounds counter-intuitive but really, there as a tonne of stuff that can go wrong and you ending up with (at best) sub-optimal implementations (if not wrong). There some very good free suites on the matter (eg. Eigen, Armadillo and Trilinos to name a few.)
Comment: Fixed. QR-based approaches (and LQ) are used in all cases; QR is not restricted to square matrices. The algorithms linked are for a general $M$-by-$N$ matrix $A$. The OP is inquiring within the context of PCA where the matrix $X^TX$ is relevant.
Comment: Yep, I was wrong: QR is not restricted to square matrices. +1, by the way. This question was one of the highest voted unanswered questions with the [tag:pca] tag, so it is nice to see it finally answered.
Comment: The question was about computing SVD of the data matrix, not of its covariance matrix (using your notation, $X$, not $A$). Isn't QR algorithm applicable only to square matrices? If so, then how can it help computing SVD of the (non-square) data matrix?
Comment: Your answer does not mention a whole variety of iterative algorithms. Was it on purpose? Somebody asked a question about iterative SVD algorithms, see [What fast algorithms exist for computing truncated SVD?](http://stats.stackexchange.com/questions/159325), and I posted an answer there trying to provide some overview. Perhaps we should at least cross-link our answers. And it would certainly be great if you can expand yours by some discussion of QR algorithms vs. iterative algorithms.
Comment: No, it was accidental. You answered your own question in your post though; truncated SVD are essentially truncated eigendecompositions (see for example [ARPACK](http://www.caam.rice.edu/software/ARPACK/)). There are some fine differences but they are *fine*; some software (eg. MATLAB's `svds`) go as far as simply using their truncated SVD function as a wrapper for their truncated eigendecomposition (`eigs`) routines.
Comment: I will look into writing a few sentences on the mater in next couple of weeks. (I have been extremely busy this month - you can see I haven't answer anything in weeks.)
Comment: Did you mean to link to https://en.wikipedia.org/wiki/QR_algorithm instead of to the QR decomposition? Thanks
Comment: I don't remember my Sept 2014 intentions, sorry. :) But I prefer the link to the QR decomposition; it emphasises the generality of QR decomposition how much of a central concept it is as well as clearly links to the QR algorithm for a particular implementation.


How to search multiple keywords in a directory in perl

Question: I am facing big problem in performance . I have to search for the keyword inside the files present in a huge directory (30 gb) having around 600 sub-directories(which will again have many sub directories inside).
Currently i am spliting the sub-directory in to 50 text files, so each file will get 12 sub directory names and running all the 50 process paralley .
my $pm = Parallel::ForkManager->new($lines);

# Forks and returns the pid for the child:
my $pid = $pm->start and next;

# we are now in the child process
ucm5 ("-iinput.txt","-f$data"); - here $data will be text file names(text1,text2...text50)
--input.txt will have the multiple search keywords(hi , hello)

$pm->finish; # Terminates the child process

#!/usr/bin/perl
sub ucm5 {
local @ARGV = @_;
use strict;
use warnings;
use File::Find;
use Getopt::Std;
#getting the input parameters
getopts('i:f:');

our($opt_i, $opt_f);
my $searchKeyword = $opt_i;                               #Search keyword file.
my $intfSplit = $opt_f;                               #split file
my $path = "C:/";                           #source directory
my $searchString;                                   #search keyword

open FH, ">>log.txt";                                          #open the log file to write

print FH "$intfSplit ". "started at ".(localtime)."\n";       #write the log file

open (FILE,$intfSplit);                                       #open the split file to read

while(<FILE>){

   my $intf= $_;                                              #setting the interface to intf
   chomp($intf);
   my $dir = $path.$intf;
   chomp($dir);
   print "$dir \n";
   open(INP,$searchKeyword);                                  #open the search keyword file to read

   while (<INP>){

   $searchString =$_;                                         #setting the search keyword to string
   chomp($searchString);
   print "$searchString \n";
   #open my $out, ">", "vob$intfSplit.txt" or die $!;          #open the vobintfSplit_* file to write
   open my $out, ">", "vob$intfSplit.txt" or die $!;
#calling subroutine printFile to find and print the path of element

#the subroutine will search for the keyword and print the path if keyword is exist in file.
my $printFile = sub {
   my $element = $_;

   if(-f $element && $element =~ /\.*$/){

      open my $in, "<", $element or die $!;
      while(<$in>) {
         if (/\Q$searchString\E/) {
            my $last_update_time = (stat($element))[9];
            my $timestamp  = localtime($last_update_time);
            print $out "$File::Find::name". "     $element"."     $timestamp". "     $searchString\n";
            last;
          }
        }
      }
    };
find(\&$printFile,$dir);
  }
}
print FH "$intfSplit ". "ended at ".(localtime)."\n";         #write the log file
}
1;

Code may be little bit confuse i will explain what it is doing - in first while loop it opensthe text file which contain the sub-directories and inside that another while loop opens the textfile which contains the search words(hi,hello). inside that file::find will be called to search the keywords in the sub dorectories.
Now what happening is it is going into first sub directorie and searching for first keyword (HI) and once done it is again going for the same directory and searching for next keyword(Hello) which means reading the same directory twice .
but i want to search for both the keywords in the first reading time itself which will save lot of time . my output should have the path, filename , searchword .
example
C:/aims/if/sp/abcd.sql   abcd.sql   HI
C:/aims/if/sp/abcd.sql   abcd.sql   Hello
please help me in this issue . is there any other better way to search all the 600 sub directories with multiple keywords apart from parallel processing and thread.
Comment: I am guessing your bottle neck is going to be reading from harddisk.. If so, unless you have a RAID setup, parallelisation might actually slow things down.
Comment: Try taking a look at the responses to [this question](http://stackoverflow.com/questions/14643785/how-to-improve-perl-script-performance) which looks **very** similar yours
Comment: Take a look at this:http://theunixshell.blogspot.com/2014/03/searching-multiple-strings-in-multiple.html
Answer: You probably want to just match all the keywords in one go so you just scan the files once.
The code below will look for "hello" or "test" and print any matching lines in input. Probably worth considering if you want to use quotemeta() on your keywords to prevent regex patterns being embedded in your words
while (<>) {
    if (/\b(hello|test)\b/i) { print "$1: $_" }
}

The \b matches a word-boundary (so it won't match "testing") and /i makes the whole test case insensitive. The matched word end ups in $1.

EDIT: fuller example showing how to process multiple matches.
Let's say we have a sample file /tmp/test.txt and a perl script match.pl (which only handles a single file in my example).
The test data:
This is a test
Line two
And this is line three

The script:
#!perl
use v5.10;
use warnings;
use File::Slurp;
my $contents = read_file('/tmp/test.txt');

my @raw_matches = $contents =~ /(test|line)/gi;

my %match_counts;
foreach (@raw_matches) {
    $match_counts{ lc($_) }++;
}

my @unique_matches = sort keys %match_counts;
foreach (@unique_matches) {
    say "$_ : count = $match_counts{$_}";
}

Sample output:
line : count = 2
test : count = 1

Now, this does rely on being able to read the whole file into memory in your script, but you didn't mention any huge files, just a lot of them to process. There may be slightly shorter ways to word the above example, but hopefully it's clear what each part is doing.
It should be simple enough to make the above into a function you can call once per file.
Comment: I tried your approach but the problem is if the same file consits of both the key words it is displaying only once it is not searching for the next keyword in the file . if we remove last(it will break the loop if the keyword is matched in the file) from the code then it is showing all the occurence of the keyword in the file including the result for the next keyword.


É possivel executar este código de 10 em 10 segundos?

Question: Eu tenho este bloco de código que diz se os meus ip's estão OK ou NOK eu pretendo executar o código de 10 em 10 segundos de forma a não estar sempre a executar na linha de comandos, existe alguma maneira de fazer isso? Já vi alguns métodos chamados setInterval e setTimeout mas não sei se é isso.
const dotenev = require('dotenv');
dotenev.config();
const ping = require('ping');

const hosts = JSON.parse(process.env.SERVERS_TO_MONITORIZE);

hosts.forEach(function (host) {
    ping.sys.probe(host.ip, function (isAlive) {
        if (isAlive) {
            host.status = 'OK';
            console.log(host.name + ' ' + host.ip + ' ' + host.status);
        } else {
            host.status = 'NOK';
            console.log(host.name + ' ' + host.ip + ' ' + host.status);
        }
       return host.status;
    });
});

module.exports = hosts;

Comment: Por que tem que fazer a verificação de disponibilidade a cada 10s? Não seria mais simples através de um [getter](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/get) fazer essa verificação apenas quando alguma parte do programa consultasse a propriedade `status` de um determinado host?
Answer: Uma maneira de resolver o problema é utilizando a lib node-cron.
Para isso primeiramente faça a instalação da lib node-cron utilizando o comando:
npm install node-cron

Depois basta importar esta lib, e criar uma expressão no padrão de um cronjob

Cronjob: O utilitário de linha de comando cron, também conhecido como cron job, é um agendador de tarefas em sistemas operacionais do tipo Unix. Os usuários que configuram e mantêm ambientes de software usam o cron para agendar trabalhos para serem executados periodicamente em horários, datas ou intervalos fixos.

Segue um exemplo de utilização:
const cron = require("node-cron");

cron.schedule("*/6 * * * * *", () => console.log("Executando a tarefa a cada 10 segundos"));

Após montar o script, supondo que o nome dado ao arquivo seja tarefa.js e que contenha o conteúdo acima, para executar a cada 10s basta executar utilizando o tempo de execução do nodejs com o comando:
node tarefa.js

Ao fazer isso verá que a mensagem Executando a tarefa a cada 10 segundos será exibida em tela a cada 10s.

Para realizar tarefas agendadas baseadas em tempo. Você vai precisar de utilizar uma expressão no padrão de cronjob. (Um padrão do Unix).
Além da utilização do node-cron, uma solução baseada na instalação de bibliotecas externas, se tiver utilizando um sistema operacional baseado em Unix, pode fazer utilização do serviço cronjob do Unix.
Sintaxe do cron
Esta é uma referência rápida à sintaxe do cron e também mostra as opções suportadas pelo node-cron.
  ┌────────────── segundos (opcional)
  │ ┌──────────── minuto
  │ │ ┌────────── hora
  │ │ │ ┌──────── dia do mês
  │ │ │ │ ┌────── mês
  │ │ │ │ │ ┌──── dia da semana
  │ │ │ │ │ │
  │ │ │ │ │ │
  * * * * * *

Ou pode utilizar alguma ferramenta para ajudar a montar a expressão do cronjob.
Comment: De facto era isso que queria, mas se eu alterar algum ip continua a dar OK, ou seja, o código que é repetido é sempre o mesmo, não atualiza de acordo com os dados fornecidos durante a execução
Comment: sim exatamente isso, é possivel?
Comment: Ok muito obrigado pela ajuda!!
Comment: @FranciscoMarques caso a resposta tenha lhe atendido, não esqueça de marcar o V ao lado da mesma para que outras pessoas identifiquem o que resolveu o seu problema
Comment: Deixa eu vê se entendi. Você quer modificar os valores que estão no arquivo `.env` e quer que estas mudanças sejam refletidas no código. É isso? @FranciscoMarques
Comment: Se quer este comportamento, deve colocar a chamada `dotenev.config();` dentro do método a ser chamado no intervalo de tempo.


Fastest way to compute minimal polynomial (for solving $x' = A x$, $A$ matrix)

Question: In general, given a $3\times 3$ or $4\times 4$ matrix $A$ which doesn't have a lot of $0$ entries, what is the  fastest or less error prone way to compute its minimal polynomial?
More generally, I have a differential equations final coming, and this is required for solving $x' = A x$ problems (where $A$ is a matrix). I usually fail to solve those because there is a lot of computing involved and I make silly errors which later turns into horrors (integrals, systems...).
I am worried about making these silly errors and fail the exam even when I know the theory and the methods.
Do you have any tricks to solve these kind of standard problems, where $A$ is usually a $3\times 3$ matrix with integer entries?
Answer: I believe in solving lots of problems to get good, here: at solving first order matrix differential equations. I used the Schaum's Outline on Differential Equations to train, maybe your library has a copy. Mine is from 1988.
To calculate the characteristic polynomial, you need to be able to calculate determinants,
$$
\chi(\lambda) = \det \left( A - \lambda I \right)
$$
I used the Schaum's Outline on Linear Algebra for that. :-)
Addendum: I removed the excerpt pages on $e^{At}$ calculation, as you say you know that part.


Javascript Push to Array if Condition is Met

Question: I have the following Foods Object:
var Foods = {
  "Fruits": [{
   "id": "1",
   "Name": "Granny Smith",
   "Category": "1"
  }, {
   "id": "2",
   "Name": "Raspberries",
   "Category": "1"
   }
],
 "Potatoes": [{
   "id": "3",
   "Name": "Maris Piper",
   "Category": "2"
  }, {
   "id": "4",
   "Name": "Charlotte",
   "Category": "2"
 }]
 }

What I would like to do is only push the produce that matches an id passed by a link.
Get Foods

This is what I have tried so far:
function getCat (id){
 result = [];
 for(let item in Foods) {
    if(Foods[item].id == id) {
        data[item].foreach(v=>result.push("

" +
        data[key].Name + "

"));
    }
  }
}

display();

function display() {
  alert(result);
}

So if a user hits the link (which has an id of 2), the result array should contain "Charlotte" and "Maris Piper" but I am just drawing a blank.
Any help appreciated.
Cheers
Comment: what is your variable `result = [];` scope? is it a global scope?
Comment: Whats data ???? And js is typesafe, so its *onclick* and *forEach*
Comment: Sorry should be a Foods object.
Comment: I think you might be looking for *array.filter*, but it is completely unclear what your data looks like and what you want to get out of it.
Answer: Youre quite close, however theres a slight problem:
for(let item in Foods) {
  console.log(Foods[item]);
  /*
  [{
  "id": "1",
  "Name": "Granny Smith",
 "Category": "1"
   }, {
   "id": "2",
   "Name": "Raspberries",
   "Category": "1"
   }
]
*/

So youre iterating over the categories, which are arrays.
Foods[item].id

is undefined as its an array and not a product. So we need to iterate the array to, e.g.
var result=[];
Object.values(Foods).forEach(function(category){
 category.forEach(function(product){
   if(product.id===id){
     result.push(product);
   }
 });
});

Run
But if youre doing this quite often, it might be easier to create one product array once:
var products = Object.values(Foods).reduce((arr,cat)=>arr.concat(cat),[]);

So you can simply filter this whenever someone clicks a button:
var result = products.filter(product=>product.id === id);

Run
Comment: Did you mean to write `var category in Foods` instead of `of Foods` since of doesn't work on Objects.
Comment: You are certainly right it is but, the for..of loop only supports iterable objects like arrays, not objects.
Comment: @antonio smoljan *of doesnt work on objects* lol. everything in js is an object.
Comment: @antonio smoljan lol, always have used it like this, never noticed that it doesnt work :/ . thanks ;)
Comment: No problem great answer im upvoting it, just wanted to see if i was mistaken :)
Comment: Using your first code snippet, Jonas this actually works but the alert function spits out the contents of result twice?
Comment: @hexana where did you put the alert?
Comment: var result=[];
Object.values(Foods).forEach(function(category){
 category.forEach(function(product){
   if(product.id===id){
     result.push(product);
   }
 });
});  alert(result);
Comment: An amazing help.  Thanks so much.  It has been really annoying me and you have really explained it. thanks again Jonas.  Big green tick from me :)
Comment: @hexana by the way, you may change *id* to *category* based on your example... ;)
Answer: You're somewhat on the right track, but what's data? Why are you not doing anything with result? And you should be looking at the Category property rather than ID.
This'll work:
function getCat(id) {
    let result = [];

    for (let item in Foods) {
        if (Foods.hasOwnProperty(item)) {
            Foods[item].forEach((food) => {
                if (food.Category == id) {
                    result.push(food);
                }
            });
        }
    }

    console.log(result);
}

Comment: Thanks for your help. Tried your solution and if I do document.write(result) it returns [object Object],[object Object]
Comment: @hexana yes its an object. 1) dont use document.write 2) simply build up a string like you already did in your code instead
Comment: Jonas do you have an example as I can't seem to get it to work?
Answer: First of all result array should be at global scope so that you can access it in another function, And in object you are having categories then each category has some data in array so after iterating over object, you need to iterate the items from array as well to get the value. Check the below code.
var result = [];
    function getCat(id){
     for(let item in Foods) {
        var foodItem = Foods[item];
        for(let i=0; i<foodItem.length; i++){
           if(foodItem[i].id == id) {
              result.push("

" + foodItem[i].Name + "

"));
           }
        }

      }
    }

function display() {
  alert(result);
}

display();

Answer: Iterator is wrong. You should do it like this:
function getCat(id){
    result = [];
    for(let item in Foods) {
        Foods[item].forEach(function(each){
            if(each.id == id) { // you cmpare to the wrong target
                // do something
            }
        });
    }
}


What's the significance of the distinction that there are non-surjective epimorphisms?

Question: Isn't surjectiveness only relevant when discussing sets and set-like objects? Or is it that there are so many things that can be treated like sets that knowing if something is surjective or not is useful?
For instance this answer mentions a surjective epimorphism with no right inverse. It seems there are any number of categories that have an epimorphism $e$, but when looking at $e$  outside category theory it lacks some property — perhaps, say, being surjective.
I guess my question is just: when "epimorphism" is first defined†, the caveat is given that there are non-surjective epimorphisms, but why not mention there are surjective-but-no-right-inverse epimorphisms, or other similar cases?
† wikipedia, Algebra by Mac Lane
references: Category Theory for Programmers youtube series (Bartosz Milewski)
Comment: Perhaps there is greater risk of conflation of epimorphism with surjective (since they agree in so many familiar concrete categories) than there is of assuming surjective epimorphism implies existence of right inverse (not sure why anybody would assume that).
Comment: Well, Greek "epi" is literally "onto". So warning that an epi need not be onto seems adequate.
Answer: Yes, surjectiveness is a property of functions, and categories don't have to have anything to do with functions.  There's a notion of a concrete category that does a reasonable job of capturing the notion of category where the arrows can be thought of as functions.  Any category of algebraic objects (rings, groups, lattices, etc.) is a concrete category.
I would assume it's mentioned because the "dual-ish" statement that an injective homomorphism (in a category of algebraic objects) is precisely a monomorphism is true. (According to Wikipedia, sometimes "epimorphism" is defined to be "surjective homomorphism" by people outside of category theory, so it's important to show that the categorist's notion is not that.) Proof: In a category of algebraic objects, the forgetful functor $U$ is a right adjoint. $f : A \to B$ is a monomorphism if and only if the following diagram on the left is a pullback:$$
\require{AMScd}
\begin{CD}
A @= A  @. @.@. @. @. UA @= UA \\
@| @VVfV @. @. @. @. @| @VVUfV \\
A @>>f> B @. @. @. @. @. UA @>>Uf> UB
\end{CD}$$
But then the right hand diagram is a pullback and so $Uf$ is injective. That proves that every monomorphism is an injective homomorphism. To show that every injective homomorphism gives rise to a monomorphism, assume $Uf$ is injective (i.e. a monomorphism in $\mathbf{Set}$). We can form the pullback of $f$ along itself as algebraic categories are complete producing the left hand diagram:$$
\begin{CD}
A\times_B A @>p>> A  @. @.@. @. @. U(A\times_B A) @>Up>> UA \\
@VqVV @VVfV @. @. @. @. @VUqVV @VVUfV \\
A @>>f> B @. @. @. @. @. UA @>>Uf> UB
\end{CD}$$
The right hand diagram is again a pullback, but $(UA,id,id)$ is also a pullback of $Uf$ along itself so we have $Up : U(A\times_B A)\cong UA$ canonically, and similarly for $Uq$ so $Up = Uq$. Via faithfulness $p = q$ and $f$ is a mono follows. $\square$
All we really needed above was that $U$ is faithful and preserves kernel pairs and that the source category has them.  $U$ usually won't preserve cokernel pairs. For example, the injections of a coproduct of an object with itself are a cokernel pair, but the underlying set of the coproduct of algebraic objects is usually not the disjoint union of the underlying sets of the objects. So dualizing the above proof does not work, even for only one direction, though this does not mean another proof couldn't be used.
As for right inverses, every epimorphism having a right inverse is equivalent to the axiom of choice in $\mathbf{Set}$.  So even in $\mathbf{Set}$ having a right inverse is already a property one may find overly strong as a definition of epimorphism. If we consider the dual statement, "all monomorphisms split in $\mathbf{Set}$," it is almost but not quite true. The counterexample is any function from the initial object (i.e. the empty set) into any non-empty set.  The point being there is less of a chance that "has a right inverse" will be a property one expects an epimorphism to have, but there's a good possibility one might expect "epimorphism" implies surjective homomorphism (in concrete categories) because that literally is the definition of "epimorphism" sometimes, and it often is true.


Calculate variance of $X^2$ when $X$ is a random variable with mean $0$ and variance $\sigma_x^2$

Question: Suppose $X$ is a random variable with mean $0$ and variance $\sigma_x^2$.
How can I calculate mean and variance of $X^2$?
I calculated the mean like this
\begin{equation*}
  \operatorname{Var}(X) = \operatorname{E}(X^{2}) - \operatorname{E}^{2}(X) \rightarrow \operatorname{E}(X^{2}) = \sigma_{x}^2
\end{equation*}
but am stuck at the variance.
Comment: It depends on the distribution of $X$.
Answer: If you have only the mean and variance of $X$ as 0 and $\sigma_x^2$, then there is insufficient information to calculate the variance of $X^2$, which is
$$
E[X^4] - E[X^2]^2 = E[X^4] - \sigma_x^4.
$$

For a normal R.V. $\sim N(0, \sigma_x^2)$, $E[X] = 0, E[X^2] = \sigma_x^2, E[X^4] = 3 \sigma_x^4$.
For a uniform R.V. $\sim U(-1.5 \sigma_x, 1.5 \sigma_x)$, $E[X] = 0, E[X^2] = \sigma_x^2, E[X^4] = 9 / 5 \sigma_x^4$.
It's easy to build distributions for which this is infinite.
Comment: What exactly we should know about the distribution of $X$, to calculate the variance of the $X^2$?


What is a "worker" in Odoo?

Question: What is the purpose of workers? Are these workers for multi-threading or something else? When the Odoo instance start I see at least 6 workers on command line that informed:
2016-03-10 13:55:09,602 15504 INFO ? openerp.service.server: Worker WorkerHTTP (15504) alive
2016-03-10 13:55:09,606 15503 INFO ? openerp.service.server: Worker WorkerHTTP (15503) alive
2016-03-10 13:55:09,625 15507 INFO ? openerp.service.server: Worker WorkerCron (15507) alive
2016-03-10 13:55:09,628 15506 INFO ? openerp.service.server: Worker WorkerCron (15506) alive
2016-03-10 13:55:09,629 15508 INFO ? openerp.service.server: Worker WorkerCron (15508) alive
2016-03-10 13:55:09,629 15509 INFO ? openerp.service.server: Worker WorkerCron (15509) alive

And what is the difference between WorkerHTTP and WorkerCron? Honestly I don't know what they do.
Comment: visit this link s://github.com/DocCyblade/tkl-odoo/blob/master/overlay/etc/odoo/openerp-server.conf#L395
Comment: @prakash link is dead.
Answer: Definition
It is explained in the Odoo documentation here

Odoo includes built-in HTTP servers, using either multithreading or
  multiprocessing.
For production use, it is recommended to use the multiprocessing
  server as it increases stability, makes somewhat better use of
  computing resources and can be better monitored and
  resource-restricted.
Multiprocessing is enabled by configuring :option:a non-zero number
  of worker processes <odoo.py --workers>, the number of workers should
  be based on the number of cores in the machine (possibly with some
  room for cron workers depending on how much cron work is predicted)
  Worker limits can be configured based on the hardware configuration to
  avoid resources exhaustion Warning
Note: Multiprocessing mode currently isn't available on Windows

Configuration
You should use 2 worker threads + 1 cron thread per available CPU, and 1 CPU per 10 concurent users. Make sure you tune the memory limits and cpu limits in your configuration file.
workers = --workers <count>

If count is not 0 (the default), enables multiprocessing and sets up the specified number of HTTP workers (sub-processes processing HTTP and RPC requests).
A number of options allow limiting and recyling workers:
--limit-request <limit>

Number of requests a worker will process before being recycled and restarted. Defaults to 8196.
--limit-memory-soft <limit>

Maximum allowed virtual memory per worker. If the limit is exceeded, the worker is killed and recycled at the end of the current request. Defaults to 640MB.
--limit-memory-hard <limit>

Hard limit on virtual memory, any worker exceeding the limit will be immediately killed without waiting for the end of the current request processing. Defaults to 768MB.
--limit-time-cpu <limit>

Prevents the worker from using more than  CPU seconds for each request. If the limit is exceeded, the worker is killed. Defaults to 60.
--limit-time-real <limit>

Prevents the worker from taking longer than  seconds to process a request. If the limit is exceeded, the worker is killed. Defaults to 120.
Differs from --limit-time-cpu in that this is a "wall time" limit including e.g. SQL queries.
--max-cron-threads <count>

number of workers dedicated to cron jobs. Defaults to 2. The workers are threads in multithreading mode and processes in multiprocessing mode.
For multiprocessing mode, this is in addition to the HTTP worker processes.
More info about Deployment Architecture, with some diagram.
More information about the configuration file
Practical Examples
I am Adding here the information on the @prakah link in the comment above:
Heading            | Description
------------------ | ---------------------------------------------------------
CPUs               | Number of CPU Cores not threads
Physical           | Physical memory, not virtual or swap
workers            | Number of workers specified in config file (workers = x)
cron               | Number of workers for cron jobs (max_cron_threads = xx)
Mem Per            | Memory in MB that is the max memory for request per worker
Max Mem            | Maximum amount that can be used by all workers
limit_memory_soft  | Number in bytes that you will use for this setting

Note: Max Memory if notice is less than total memory this is on purpose. As
       workers process requests they can grow beyond the Mem Per limit so a
       server under heavy load could go past this amount. This is why there
       is "head room" built in.
CPUs | Physical | workers | cron | Mem Per | Max Mem | limit_memory_soft
---- | -------- | ------- | ---- | ------- | ------- | -----------------------
ANY  | =< 256MB |    NR   |  NR  |      NR |     NR  | NR
 1   |   512MB  |    0    |  N/A |     N/A |     N/A | N/A
 1   |   512MB  |    1    |  1   |   177MB |   354MB | 185127901
 1   |    1GB   |    2    |  1   |   244MB |   732MB | 255652815
 1   |    2GB   |    2    |  1   |   506MB |  1518MB | 530242876
 2   |    1GB   |    3    |  1   |   183MB |   732MB | 191739611
 2   |    2GB   |    5    |  2   |   217MB |  1519MB | 227246947
 2   |    4GB   |    5    |  2   |   450MB |  3150MB | 471974428
 4   |    2GB   |    5    |  2   |   217MB |  1519MB | 227246947
 4   |    4GB   |    9    |  2   |   286MB |  3146MB | 300347363
 4   |    8GB   |    9    |  3   |   546MB |  6552MB | 572662306
 4   |    16GB  |    9    |  3   |  1187MB | 14244MB | 1244918057

Comment: @salahaddin `1MB = 1024kB`, `1kB = 1024B`. So `768 x 1024 x 1024 = 805306368 B`
Comment: I'm sorry but i'm still donnot understand why `768MB` is `805306368`. Can you explain me it please.
Answer: As you might know the GIL prevents Python from doing any real threading
to better understand workers, let's see what would happen without them:
with no workers enabled, your odoo instance only uses one core in the hosting machine, hence once the number of clients goes beyond one, the performance just goes downhill since a new client needs to wait its turn to use odoo resources.
normally a production server would have multiple cores, hence the need to scale odoo on the machine resources; simply put workers is somehow equal to launching multiple instance of odoo on the same machine.

What is a "worker" in Odoo?


How can I use a program that requires the local console, remotely?

Question: I have a customized program that I need to run remotely (in order to use the computing power of my server). I have run into a problem in which this program doesn't seem to work when it isn't using the local console in Windows Server 2008. I found this out after trying to use it under RemoteApp. The developer of the program isn't willing to try to figure out how to fix it at all (note: it is a technical issue, not a licensing issue).
So my question is, is there any way to handle this or trick the program into thinking it is being used locally? I am willing to sacrifice the "nice" features of RemoteApp and am even willing to go so far as to say I will only have one person logged in at a time. The only requirement is I need to be remote and I can't use VNC.
Thanks for your help.
Comment: Can you just use Windows RDC?
Comment: @bobert5064 When I use Windows RDC it logs me into a non-local session (not sure of the proper terminology) and causes the program to not work.
Comment: Oh, you're right, I hadn't thought of that not being considered a local session, sorry. Since the application is customized, do you have the source code? I don't have a lot of experience in this area, but have you tried to SSH into the machine and run it from there?
Comment: May I ask why VNC is not an option?
Comment: @Zoredache Blocked on the network and I don't have the authority to do anything about it. :(
Comment: I probably should have mentioned this in the question, the program works on Win XP RDP, but not on Server 2k8 RDP.
Comment: @Zoredache That actually looks like it worked! I had tried "-console", but I guess that didn't do what I thought it would. Thanks for the help.
Comment: Good, I have moved my comment to an answer.
Answer: Try using the /admin switch with connecting via RDP from a recent RDP client..  It connects actually lets you view the console on Windows 2003 machines.


sharepoint in infrastructure managemant services

Question: Is sharepoint being used in infrastructure management services(ITIS)
Answer: Yes, check out one of the case studies on this:
SharePoint 2010: AvePoint's infrastructure management tools are built on SharePoint
http://www.microsoft.com/showcase/en/us/details/abe1bff1-bfff-4ff9-b21d-9952f331a5a3
Answer: yes, sharepoint is being used in infrastructure management services(ITIS).


Problem with finger jump in piano

Question: I was practicing the Fur Elise piece on the piano,

Since I'm trying to improve my piano playing skills, I'm practicing to play it without looking at the keyboard. I've practiced the first two lines of the note. I can play the right hand very well except for one part,
It starts with E D# E D# E B D C A, which is not difficult. Now I have to move my right hand to play the lower C note with my thumb. I find it very hard to do this without looking at the keyboard because this key is far away from the other keys. I'm wondering how to practice these finger jumps?
Other right hand keys are easy to play without looking at the keyboard because their positions are close to each other.
Answer: You can avoid making a leap if you end with a different finger. Here's how I play that phrase personally:

The stretch of a sixth between two adjacent fingers may look like a lot, but your thumb is flexible, get used to using it to its fullest! Of course you'll need to learn to stretch exactly the right amount, but any hand-based muscle memory is going to be easier to execute reliably than an arm-based leap.
How did I figure out this fingering? Trial and error, same as you. There will be less error eventually as you learn to anticipate problems and how to solve them, but there's no magic to it, just ten fingers and a little creativity where it's called for. As far as fingering goes there's not really a "wrong" way as long as it works for you.
Finally, leaps will come up sometimes and the other answers here are pretty good in regards to those, so listen to them too. But there's also nothing wrong with taking the "easy way" if it leads to a better performance.
Comment: I agree with the general advice, but wanted to tell what I do. I still play the A with my thumb, but then I slip over and grab it with my ring finger (i.e. finger 4) and then my hand naturally fits the CEAB that comes up.
Answer: All you can do, is like most of us, and get familiarised with the stretch on piano between the previous A, which you play with your specific finger, and the lower C, which as you say will be with  your thumb. That stretch is specific to tis tune, and will need to be learned visually before it's playable without looking.
Comment: Thanks! I just noticed that if I play the prevoius A with index finger instead of the thumb it is easier to reach the lower C with thumb.
Answer: Make a silent change on A from thumb to finger 5, like other say.
But now the most important help that I miss in the given answers:
Blind piano players find their orientation by touching the black  keys:
So you have to search with  closed eyes the keys c# and d# with with finger 1 and 2. Left from C# is C.
Answer: For this specific jump, there is the option of playing the A with the thumb, but then swapping in another finger (say, 4 or 5) so that the C is within can be felt. The sixteenth rest after the A is a perfect time to make the swap.
In general, the most efective way I know to practice leaps from note (or chord) X to note (or chord) Y is:

Place the hand on X, at rest on the surface of the keys.
Make a staccato leap off of X.
Make a smooth arc to Y, watching your entire arm from shoulder to fingertips, and also keeping an eye on your destination.
Land at rest on the surface of the keys of Y.

The most important element is step 3, making a smooth arc. It needs to be smooth — no abrupt changes of direction, no corners, real height — and there can be no "adjustments" (e.g., no landing on the key surface and then adjusting the finger placement).
When the leap is made cleanly from start to finish, one has a much better chance of making the same leap without looking at the keyboard.
Answer: Do not think of making a leap. Make a stretch. The finger on the A will be the anchor that allows you to know where everything else is, and thus allow you to find the note in question.
Comment: Not if the finger on A is the thumb, which is one of the more intuitive fingers to use there.

Problem with finger jump in piano


What is the sum of this series: $1 + \frac{1}{5}x + \frac{1 \times 6}{5 \times 10}x^2 +\cdots$?

Question: Say I have a series like the following;

$$1 + \frac{1}{5}x + \frac{1 \times 6}{5 \times 10}x^2 + \frac{1 \times 6 \times 11}{5 \times 10 \times 15}x^3 + \cdots.$$

How do I find the sum of this?
I'm trying to find an expression for the nth term but struggling!
Comment: Well, it may help to know how the series is defined. Whence does the expression above come?
Answer: As @Jennifer answered, the general term seems to be
$$
\frac{\prod_{i=0}^{n-1} (5i+1) }{\prod_{i=0}^{n-1} 5(i+1)}=\frac{\Gamma\left(\frac15+n\right)}{\Gamma\left(\frac15\right)\Gamma\left(n+1\right)}=\frac{\left(\frac15\right)_n}{n!} \tag1
$$ where $(x)_n=x(x+1)\cdots (x+n-1)$, then one may recall the generalized binomial theorem,
$$
\left(1-x \right)^{-\alpha}=\sum_{n=0}^\infty\frac{\left(\alpha\right)_n}{n!}x^n.
\tag2$$ Hence, by putting $\alpha=\dfrac15$ in $(2)$, one gets, using $(1)$:

$$
1 + \frac{1}{5}x + \frac{1 \times 6}{5 \times 10}x^2 + \frac{1 \times 6 \times 11}{5 \times 10 \times 15}x^3 + \cdots =\color{red}{\frac1{(1-x)^{1/5}}}, \quad |x|<1. \tag3
$$
Answer: The term for $x^n$ seems to be :
$$\frac{\prod_{i=0}^{n-1} (5i+1) }{\prod_{i=0}^{n-1} 5(i+1)} $$


Using Git with a Drupal site

Question: May we use git with a Drupal Site ?
Because I'm trying to use Git with a Drupal site and it seems that not all the information that are pushed !!!
Thank you
Comment: Did someone set up the .gitignore file?  It might be ignoring some files, but that might be a good thing.  Most people don't want to shove Drupal core into the repo.
Comment: The .gitignore files are empty ... yeah it will be a very good thing -- I hope that it is possible!!
Comment: You're not trying to push website content with git, right? Just the code?
Comment: all the things, code and content ? is it possible ?
Answer: Git is a source code management (SCM) system.  There are many different source code management systems out there and Git fall into the category of a distributed version control system (DVCS).  It takes a "peer-to-peer" approach to version control as opposed to a "Client-Server" approach like version control systems like Subversion (SVN).
Yes we can use GIT with drupal.
To setup a GIT repository in drupal project please visit below link.
Git Setup
Answer: Yes. It is typical practice to manage Drupal with a VCS, with Git being the defacto option; Drupal core, as well as all projects on drupal.org, uses Git as its VCS.
Drupal includes some default git configurations. D7 has a default .gitignore config. D8 has an example.gitignore config which isn't applied by default. There is also a default .gitattributes for white space settings.
You'll have to troubleshoot what is/is not include in your codebase. Typically, the gitignore settings exclude content & settings data from the code repo.
Comment: It's in the site root. BTW, using a VCS to store content is considered bad practice; a VCS is for managing code, not data. Putting all your content into your VCS can blow up its size pretty quickly depending on how much content you have.
Comment: Oh !! where may I find the default drupal gitignore file ?? because this one is blocking the content to be updated  !
Comment: So for the content I use "export and import" the database ?
Comment: There are many solutions out there, it will depend on your needs. The Drupal [Backup and Migrate](https://www.drupal.org/project/backup_migrate) project is one solution to migrating over both DB & file system content.
Comment: @ShawnConn my naive way of handling it was creating a separate repo and doing mysqldump, after i clear cache of course.

Using Git with a Drupal site


Mixed Effects Logistic Regression w/ Repeated Measures for Observational Data

Question: I am working on a study of how different scholarship programs at a university may influence student retention (i.e., if students are still enrolled at the university one year later). Each student can receive a different combination of scholarships--they can also lose or gain scholarships over time. All students in the study started in the same cohort/semester.
My data has the following variables:

Student ID: identifier for each student
Term: semester that the student had the scholarship (categorical)
Award Type: whether scholarships are awarded based on merit, financial need, or special interest (categorical)
Award Prop: the proportion of student expenses that the scholarship covers - for example, an Award Prop of 0.50 means that the scholarship will cover half of a student's college expenses (continuous)
Outcome: whether or not the student persisted a year later (binary)

An example of the data is provided below:
ID     Term           Award Type   Award Prop   Outcome (Persisted?)
0025   Fall 2012      Merit        0.25         Y
0025   Fall 2012      Need         0.50         Y
0025   Spring 2013    Need         0.50         Y
1310   Fall 2012      Interest     0.30         N
1310   Spring 2013    Interest     0.30         N
1229   Spring 2013    Need         0.90         Y
1229   Spring 2013    Interest     0.10         Y
2843   Fall 2012      Merit        0.50         N

Due to the fact that I'm modeling a binary outcome for individuals sampled several times, I am thinking of approaching this with a mixed effects logistic regression with repeated measures using lme4 in R.
I think the way to structure this might be to nest ID within Term as a random effect:
glmer(Outcome ~ AwardType + AwardProp + 1|(Term/ID), family=binomial)

First, based on the parameters above, does this seem to be a sound way to approach this analysis?
Second, should I be concerned about potential issues with missing/unbalanced data (since each person has different scholarships, a person with a scholarship one semester may not have it in other semesters, etc.)? One article I read said that mixed effects modeling should take care of this.
Answer: Have you thought about using a survival model (cox regression) here?
I think such a model will take the temporal characteristic of your data better into account. Given that your treatment/exposure can vary over time, it also make sense to look at models for time varying exposures, e.g. here: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4351798/
Answer: Your analysis might be okay for a randomized trial with one observation period. What is problematic with observational data includes:

You do not model the "treatment" (scholarship) assignment process. If some scholarships are given to, say, underprivileged students who may be more likely to drop-out in the first place, while another scholarship is given to e.g. athletes or legacy admissions or highly performing students that are more likely to stay in the course in the first place, then you end up with confounding. You can't tell the difference between whether you are comparing the students as they were (i.e. the same would have happened even if they had not got the scholarship), the causal effect of the scholarship, or (most likely) a mixture of the two (but likely with a strong effect of the pre-existing student characteristics).

To account for this, you'd need to have model the assignment process, which likely requires quite an in-depth level of information (e.g. details on socio-economic background, financial situation, education of parents/other key family members, past academic track-record etc.). Without those things, it'll be futile to hope to account for the possible sources of confounding and you're likely just wasting your time.
If you have those things, you can try various causal inference methods (e.g. adjustment, doubly-robust methods, propensity score methods etc.). One good book on the topic would be this one, a pre-print is freely accessible at the link location on the author's webpage.

This only gets worse, if you treat time periods the way you do. E.g. if a student has a scholarship for a period, then looses their scholarship, then has a period without it and then drops-out, causally attributing this to not having a scholarship is really problematic. The reason is that perhaps the reason that explains them dropping-out is what made then loose the scholarship (e.g. dropping test performance) or it is a direct effect of the loss of the scholarship (or some mixture of these things).
I'm not sure whether you have students without any scholarships at any time in your data, but without those it's also a lot harder to say things about the causal effects of scholarships (you can at best but even that gets a lot harder compare types of scholarships). It may be cleaner to compare those having a scholarship at a fixed point of time (even if they may loose it in the future) going forwards with time-to-event methods.
Answer: It seems like you may be getting a lot of overlaps in the 1-year follow-up periods for different scholarships obtained by the same student (e.g., first and second observations in your example).  I don't know if it is true in your case, but I suppose it is also possible for a student to obtain a new scholarship during the 1-year follow-up period from a previous scholarship.  So rather than simply having correlated observations for the same individual, you'll have different observations for the same outcome.  My suggestion would be that rather than treating scholarships as separate observations, you could combine current observations, such that you have a clean 1-year follow-up period per observation (clean meaning no additional scholarships granted and no scholarships lost).  Then the predictor variables can be constructed to indicate what scholarships were obtained leading up to the start of that 1-year period.  The outcome variable would still measure if the student was still enrolled at the university one year later.
Comment: Sorry, I just wanted to follow up for clarification. Do you mean that I should convert my data from a long format to wide format (i.e., one observation record per student/ID)? I'm also a little unsure about your suggestion here: "Then the predictor variables can be constructed to indicate what scholarships were obtained leading up to the start of that 1-year period." Does this mean that I would have to have one column per each scholarship type?
Comment: I envision one observation per 1-year follow-up period, so sometimes I expect there to be multiple observations per student (if a student received multiple scholarships at least 1 year apart).  So you can still model repeated measures in that case, but the key point is that you only have one observation per outcome (did student stay enrolled for 1 year).  Creating separate variables for each scholarship type makes sense.  There can also be variables for how many total scholarships there were and how far apart they were granted.


What is star query optimization?

Question: I found in a features table for SQL Server 2005 a row named "Star query optimization" but it is not explained anywhere.
Could this be a feature that optimizes a query like :
<code>SELECT * FROM Table
</code>
Answer: It's a business intelligence feature, allowing the query planner to make better decisions when performing queries on star schema style databases, typically used in business intelligence / data warehouse implementations.
Some sparse background is available in this blogs.msdn.com post, but the article they link to for deeper information is gone.

What is star query optimization?


React MUI: theme color custom prop not applied

Question: I have 2 themes, dark mode and light mode:
import { styled, alpha, ThemeProvider, createTheme } from '@mui/material/styles';

//I use the dark theme only
const themeLight = createTheme({
...
})

const themeBlack = createTheme({
    palette: {
        background: {
            default: "#262626",
            paper: "#262626"
        },
        primary: {
            main: "#FEB139",
            light: "#FEB139",
            dark: "#FEB139",
        },
        secondary: {
            main: "#143F6B"
        },
        tertiary: {
            main: "#FFBC80"
        },
        base: {
            main: "#F55353"
        },
        info: {
            main: "#FEB139",
            light: "#FEB139",
            dark: "#FEB139"
        },
        text: {
            default: "#FF9F45"
        },
        shadow: "rgba(118, 118, 118, 0.23)",
        mode: "dark",
    },
    typography: {
        body1: {
            color: "#FF9F45"
        },
        h1: {
            color: "#FF9F45"
        },
        h2: {
            color: "#FF9F45"
        },
        h3: {
            color: "#FF9F45"
        },
        h4: {
            color: "#FF9F45"
        },
        h5: {
            color: "#129F65"
        },
        h6: {
            color: "#FF9F45"
        },
    },
    root: {
        color: "#F55353"
    },
    card: "#111111",
    top: "#1E1E1E",
    line: "#111111",
    title: {
        font: "'Lato', sans-serif",
        size: 22,
        weight: 600,
        color: "#FEB139",
    },
    gradient: "linear-gradient(274deg, rgba(255,255,255,0) 0%, rgba(0,0,0,1) 0%,#FEB139 0%, #F55353 100%)",
    maxPadding: 80,
    minPadding: 10,
    drawerWidth: 240,

});

export { themeLight, themeBlack };

On some pages, it works fine, but on some specific ones it doesn't. The problem aappears generally on all components, but I will focus right now on typography.
<Typography variant="h4">
    Login
</Typography>

As you might see, in the theme object, #FF9F45 is the specified color, but for some reason it is not applied. Checking the styles using the Chrome dev tools, the color seems to be overridden by the default one
Answer: The component/page had another theme nested inside:
const theme = createTheme();

<ThemeProvider theme={theme}>
...
</ThemeProvider>

The mui basic templates include separate themes for each component, so thats how it got there.


How to set title of rendered anchor tags for

Question: I have a bulleted list in ASP.NET whose DisplayMode is set to HyperLink. When the control is rendered, the links display perfectly fine but additionally I want to set title for each anchor tag. How do I do this?
aspx file:
<asp:BulletedList ID="BL1" runat="server" DisplayMode="HyperLink" DataTextField="AnchorText" DataValueField="URL" />

Code Behind File:
In the code behind file I am data binding the BL1 with a list.
List<UrlData> listOfUrls.
where UrlData class has three public properties
class UrlData
{
     public string URL {get; set;}
     public string AnchorText {get; set;}
     public string TitleText {get; set;}

    //public UrlData to initialise properties
}

Comment: Please share how you are populating `BulletedList `
Answer: You should use a repeater:
Bind the data source:
protected void Page_Load(object sender, EventArgs e)
{

      rprUrls.DataSource = listOfUrls;
      rprUrls.DataBind();

}

Your repeater will look like:
<asp:Repeater ID = "rprUrls"  runat="server">
        <HeaderTemplate>
</HeaderTemplate>
        <ItemTemplate>

<%# string.Format("{1}", Eval("URL").ToString(), Eval("AnchorText").ToString(), Eval("TitleText").ToString()) %>

        </ItemTemplate>
        <FooterTemplate>
</FooterTemplate>
    </asp:Repeater>

Answer: You have two options:-
Option 1:
Loop through the items inside your BulletedList and add the title attribute like this:-
protected void Page_PreRender(object sender, EventArgs e)
{
   foreach (ListItem item in BL1.Items)
   {
       item.Attributes["title"] = GetToolTip(item.Value);
   }
}

Obviously you will have to call the datasource again to get the respective tool-tip:-
private string GetToolTip(string url)
{
    return UrlDataList().First(x => x.URL == url).TitleText;
}

Assuming, UrlDataList() will return List<UrlData> which you are binding to BL1. Obviously this is not the best way since we are querying the data twice.
Option 2:
You can instead create the same behaviour using a repeater control (recommended way):-
<asp:Repeater ID="rptDemo" runat="server">
   <HeaderTemplate>

   </HeaderTemplate>
   <ItemTemplate>

        <%# String.Format("{2}",Eval("ID"),Eval("Salary"),Eval("Country")) %>

   </ItemTemplate>
   <FooterTemplate>

   </FooterTemplate>
</asp:Repeater>

Simply Bind it like this:-
protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      rptDemo.DataSource = UrlDataList();
      rptDemo.DataBind();
   }
}

Comment: @ihimv - Did you get a chance to look at my answer?


Modify/hook into admin page of rate module

Question: I'm creating a new widget type for the rate module with some custom settings. I plan to use multiple instances of the same widget each with different custom settings. Is it possible to hook into rate_widget_form to alter the admin page of the rate module ?
Example :
admin/structure/rate/add?template=widgetname
admin/structure/rate/%/edit

Sample Image :
Answer: I found the solution for my problem. I used hook_form_FORM_ID_alter
function hook_form_rate_widget_form_alter(&$form, &$form_state, $form_id){
enter code here...
}


How to send AMP Emails with PHP?

Question: I am trying to create a PHP script to send AMP Emails with PHPMailer. When reading online tutorial I found that you can specify Mime types in PHPMailer as follows:
$mail->AltBody = "Hello, my friend! This message uses plain text !";

This should create alternative body in TEXT format and the message will automatically use the MIME type multipart/alternative. However, according to the AMP for Email official documentation, I need to set a completely new MIME type for AMP Emails: text/x-amp-html. I can't seem to find a way to do that with PHPMailer. I am building this script so I later can re-create the code on Magento 2. For now I only found this plugin that should do exactly what I need. However, I believe this PHP script that I am trying to build, should be useful for the whole Stackoverflow community.
My last idea was to send AMP Email using native PHP mail() function, but I don't know how. I think, I must pass AMP Email HTML in $message variable and set AMP headers in $headers. Please see below:
mail($to, $subject, $message, $headers);

Any help appreciated!
Comment: This doesn't seem to be a plugin or tool request @Funk. He found a plugin, but he's trying to build one in `mail()`. It's perhaps a bit too broad, but I still think it's within the scope of SO.
Answer: The following script should add one additional mime type to your email. I have followed both of your links to understand what you need and built this snippet according to the documentation provided. But I didn't have time to test it. Hope it helps.
//specify the email address you are sending to, and the email subject
$email = 'email@example.com';
$subject = 'Email Subject';

//create a boundary for the email. This
$boundary = uniqid('np');

//headers - specify your from email address and name here
//and specify the boundary for the email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: Your Name \r\n";
$headers .= "To: ".$email."\r\n";
$headers .= "Content-Type: multipart/alternative;boundary=" . $boundary . "\r\n";

//here is the content body
$message = "This is a MIME encoded message.";
$message .= "\r\n\r\n--" . $boundary . "\r\n";

$message .= "Content-type: text/plain;charset=utf-8\r\n\r\n"
//Plain text body
$message .= "Hello,\nThis is a text email, the text/plain version.
\n\nRegards,\nYour Name";
$message .= "\r\n\r\n--" . $boundary . "\r\n";
$message .= "Content-type: text/html;charset=utf-8\r\n\r\n";

//Html body
$message .= "
 Hello,
This is a text email, the html version.

Regards,
Your Name";
$message .= "\r\n\r\n--" . $boundary . "--";
$message .= "Content-type: text/x-amp-html;charset=utf-8\r\n\r\n"

//AMP Email body
$message .= '<!doctype html>

  <meta charset="utf-8">

Hello World in AMP!

';
$message .= "\r\n\r\n--" . $boundary . "\r\n";

//invoke the PHP mail function
mail('', $subject, $message, $headers);

Comment: Thanks, It looks good! I will give it a try. The only thing I noticed before testing, you must place AMP Email body before the HTML body.

How to send AMP Emails with PHP?


Does joint integrability imply marginal integrability for non-negative continuous functions?

Question: Suppose that $f:\mathbb R^2\to\mathbb R_+$ is a non-negative continuous function and that $$\int_{y\in\mathbb R}\int_{x\in\mathbb R}f(x,y)\,\mathrm dx\,\mathrm dy<\infty.$$ Is it true that $$\int_{x\in\mathbb R}f(x,y)\,\mathrm d x<\infty$$ for all $y\in\mathbb R$, as opposed to merely almost all $y\in\mathbb R$?
My hunch is that the answer is affirmative given the continuity of $f$, but I can come up with neither a proof nor a counterexample. Any hint would be appreciated.
Answer: This is false. Consider the function
$$
f(x,y) = \exp\left(-\left|\sqrt{\smash{|y|}\vphantom{L}} \cdot x\right|\right) \cdot (1 - y^2) \cdot 1_{(-1,1)}(y).
$$
This is continuous and integrable, but $f(x , 0) \equiv 1$ is not integrable.
Comment: Great counterexample, thank you!


Beginner rbind function

Question: I cannot for the life of me understand the rbind function. I've tried using the examples on here, but I can't figure out what I am doing incorrectly. All I would like to do is add the data from my second data frame under the first.
Does rbind require the columns be the same name or...?
ParticipantA=c("A","B","C","D")
Score1A=c("21","20","21","21")
Score2A=c("32","40","32","31")
Score3A=c("47","50","43","46")
BlockA=data.frame(ParticipantA,Score1A,Score2A,Score3A)
BlockA$Major=c("Computer_Science","Computer_Science","Computer_Science","Computer_Science")
BlockA$Gender=c("Female","Female","Male","Male")
ParticipantB=c("E","F","G","H")
Score1B=c("28","28","21","22")
Score2B=c("30","36","37","32")
Score3B=c("41","49","49","46")
BlockB=data.frame(ParticipantB,Score1B,Score2B,Score3B)
BlockB$Major=c("Medical","Medical","Medical","Medical")
BlockB$Gender=c("Female","Female","Male","Male")

Answer: rbind requires that all columns be of the same name and class.
Answer: The problem is in the column titles.  rbind uses column titles to orient how it will bind the rows.  The columns can be in different orders, R will just use the first element to determine column order.
Alternatively, adding another column to your data frames, with the value "A" or "B" in it could preserve your information without putting "A"s and "B"s in your column names <-- the reason you can't use rbind.  The additional column would also allow you to do more analyses in R, e.g. regression and other linear models.
Here is one way to handle your data:
Create a uniform set of column names that can be used for the data frames "BlockA" and "BlockB"
final_colnames <- c("Block", "Participant", "Score1", "Score2", "Score3")

Create a new list to identify which block the participants belong to.
BlockA = c("A", "A", "A", "A")

Your previous data
ParticipantA = c("A", "B", "C", "D")
Score1A = c("21", "20", "21", "21")
Score2A = c("32", "40", "32", "31")
Score3A = c("47", "50", "43", "46")

The label "BlockA" is recycled here to name the new data frame, but not before adding the "BlockA" column list of "A" "A" "A" "A".
BlockA = data.frame(BlockA, ParticipantA, Score1A, Score2A, Score3A)

The new column names have to be added at this point, so that the number of names and the number of columns are equal.
colnames(BlockA) <- final_colnames

Now you can add the remaining columns
BlockA$Major = c("Computer_Science", "Computer_Science", "Computer_Science", "Computer_Science")
BlockA$Gender = c("Female", "Female", "Male", "Male")

BlockB is the same process
BlockB = c("B", "B", "B", "B")             # the extra column
ParticipantB = c("E", "F", "G", "H")
Score1B = c("28", "28", "21", "22")
Score2B = c("30", "36", "37", "32")
Score3B = c("41", "49", "49", "46")
BlockB = data.frame(BlockB, ParticipantB, Score1B, Score2B, Score3B)
colnames(BlockB) <- final_colnames         # renaming the columns
BlockB$Major = c("Medical", "Medical", "Medical", "Medical")
BlockB$Gender = c("Female", "Female", "Male", "Male")

Uniform column names mean that rbind will now work.
rbind(BlockA,BlockB)

Beginner rbind function


Inverseof the function $f(x)=\frac{a^{2x}-1}{a^{2x}+1}$

Question: I have problem to invert this function , Can anyone help me to solve it?
$$f(x)=\frac{a^{2x}-1}{a^{2x}+1}$$
My attempt:  change $x$ to $y$ and try to solve for $y$, but I could not.
Comment: @Mufasa Just change x to y and I calculated but I doubt it.
Comment: That approach will work. In general it is better to show what you have tried as you will then get more focused help.
Answer: $\begin{align}
y &=\dfrac{a^{2x}-1}{a^{2x}+1} \\ \implies ya^{2x}+y&=a^{2x}-1\\\implies a^{2x}(y-1)&=-(y+1)\\\implies a^{2x}&=\dfrac{y+1}{1-y} \\\implies Then\ switch\ X\ and \ Y  \\ x&= \frac12 \log_a(\dfrac{y+1}{1-y}) \\\implies y&= \frac12 \log_a(\dfrac{x+1}{1-x})\end{align}$
Answer: Hint:
Switch $x$ and $y$ first in the equation, then solve for $y$.
$x = \dfrac{a^{2y} - 1}{a^{2y}+1} \to xa^{2y} + x = a^{2y} - 1 \to a^{2y} = \dfrac{1+x}{1-x} \to \log_a\left(\frac{1+x}{1-x}\right) = 2y \to y = ??$


How do i add a scrollbar with JtextArea and implement JScrollPane in a GUI?

Question: I need help adding a scrollbar to an empty textbox that will output the information that i input into the required textboxes by then clicking the buttons. My issue is im not sure how to implement the scrollbar correctly with the textbox that is in the code, it just goes over and it and does nothing like in the picture shown. I need it to align with the textbox and not mess with the Jtextfield so that it can properly scroll the textbox, i will handle the events after i finish the design.
Code:
<code>    // Display box for all the inputs
    JTextField outputBox = new JTextField(5);
    wv.add(outputBox, 39, 575, 800, 150);
    JScrollBar outputBoxScrollBar = new JScrollBar(JScrollBar.VERTICAL, 30, 20, 0, 500);
    wv.add(outputBoxScrollBar, 790, 300, 50 , 250);
</code>
Output:

https://i.stack.imgur.com/oHnY8.png - Link for different OS
Comment: 1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Java GUIs have to work on different OS', screen size, screen resolution etc.  using different PLAFs in different locales.  As such, they are not conducive to pixel perfect layout.  Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 3) Provide ASCII art or a simple drawing of the *intended* layout of the GUI at minimum size, ..
Comment: .. and if resizable, with more width and height - to show how the extra space should be used.
Answer:
A JTextField is single-line, I guess you are looking for JTextArea.
You need to wrap JTextArea in a JScrollPane (not a JScrollBar) like this.

<code>        JTextArea outputBox = new JTextArea(5, 20); //rows, columns
        wv.add(new JScrollPane(outputBox), 790, 300, 50 , 250);
</code>


Filter content in view by user field

Question: I'm having problems filtering a view. This is my case:
When a user registers he has to select some suppliers of a list (This is a term reference as a field of my user).
A user can also create a product. Now I would like to show the products where the suppliers reconcile.
This is an example:
USER 1 has suppliers A & B.
USER 2 has supplier A.
USER 3 has supplier B.
USER A can see the products of USER 2 and USER 3.
USER B can see products of USER 1, but NOT USER 3.
USER C can see products of USER 1, but NOT USER 2.
But I'm having trouble making this filter in a view. Could someone help me on my way on how to make this?
Answer: If the Supplier field lives in the user profile you could make the Product fields dependent on the Supplier field using the Conditional Fields module, grant various roles field/taxonomy term access to Product fields using the Field Permissions or Taxonomy Permissions module, and then create a rule that fires based on Supplier field values that modify user role assignments accordingly
Then you would add all Supplier and Product fields to your view, hiding each Product field in the display, and then add a Global: Custom text field called "Products" and use replacement patterns to reference each of the hidden fields one after the other. (Make sure the hidden fields appear before the Global: Custom text field.) Anything that comes up empty simply won't appear.
If those fields live in a node, that may require a slightly different strategy, but the idea should be more or less the same.

Filter content in view by user field


Question about properties of "equality"

Question: There is one thing that is used in a lot proofs but I have never heard of it as an axiom or a theorem. I'm talking about the fact that if $x$ and $y$ are numbers such that $$x=y$$ then $$f(x)=f(y).$$ And it seems true but I have never heard of it as an axiom (or theorem but I don't think that it can be a theorem). The only way (which I see) to prove it, is to somehow use the Peano axioms and one of ways to construct natural numbers but I don't imagine it in practice. So is there such an axiom or theorem?
Comment: that's part of the definition of a function. Specifically from a set theoretic standpoint, a function $f:A \rightarrow B$ is a subset $f \subset A \times B$ such that $\forall a \in A, \exists$ unique $ b \in B$ such that $(a,b) \in f$. We abbreviate $(a,b) \in f$ to $f(a) = b$. Hence by the uniqueness, if $x = y$ in $A$, we know that $(x, f(x))$ and $(y,f(y))$ must be the same ordered pair. Ergo, $f(x) = f(y)$ as members of $B$
Comment: @ЮрійЯрош That is the definition of a function from the point of view of set theory...
Comment: Related: [Multiplying both sides of an equation in proofs](https://math.stackexchange.com/questions/2696628/multiplying-both-sides-of-an-equation-in-proofs).
Comment: @ЮрійЯрош What do you mean by "the most rigorous one?"  It is the *definition*, from the point of view of set theory.  How can it not be rigorous?
Comment: Well, the logic I study has that as a logical axiom. So you can use it in any deduction and from soundness theorem it is valid as well.
Comment: More formally $(x_1=y_1) \land (x_2=y_2)... \implies f(x_1.x_2...)=f(y_1,y_2...)$
Comment: @Joe What definition you're talking about ? The one that uses tuples and sets or other ?
Comment: @XanderHenderson I know. But it's, maybe, the most rigorous one.
Comment: @GitGud Thanks.
Comment: $x=y \implies f(x)=f(y)$ is trivially true by definition of function, if the function is defined for x=y, the reverse implication $ f(x)=f(y) \implies x=y$ is more interesting
Comment: @XanderHenderson I meant that definitions like "it is a rule that assigns some input to some output" is not rigouros.
Comment: @Sorfosh Thanks, actually, it was what I was interested in. Because I was thinking that something is left undefined.
Comment: @ЮрійЯрош The definition you give is not nonrigorous; it is simply a bad definition.  It can be made better by further defining what is meant by a "rule", an "input", and an "output," but those terms are left undefined in most texts that use such a definition.  In the definition that Joe gives, all of the objects and terms used to define a function are also perfectly well-defined.
Comment: See [First-order logic: equality axioms](https://en.wikipedia.org/wiki/First-order_logic#Equality_and_its_axioms).
Comment: @XanderHenderson Yes. It seems to be rigorous but the only thing I'm not sure in the proof is words "the same ordered pair".
Comment: @ЮрійЯрош From a set-theoretic standpoint, if you define the ordered pair $(x,y)$ to be the set $\{x, \{y \} \}$, being "the same ordered pair" follows easily as standard set equality.
Comment: @Joe Then it is clear for me, Thanks.
Comment: @Joe Sorry, I have one more question. You said that "x=y in A so (x,f(x)) and (y,f(y)) are the same ordered pair". Do you use the fact that " x" and "y" are the same things there ? Or am I wrong ?
Comment: @ЮрійЯрош Yes. Since $x$ and $y$ are sets, we have that $\{x, \{f(x)\}\} \in f$ and $\{y, \{f(y)\}\} \in f$. Using the fact that $x=y$ as sets, we have:$\{x, \{f(x)\}\} \in f$ and $\{x, \{f(y)\}\} \in f$. But these must be the same set (uniqueness property), so $\{f(x)\} = \{f(y)\}$. Both of these sets have one element, so they must be the same element. Ergo, $f(x) = f(y)$ as sets.
Answer: I think the answer to your question lies in the meaning of "equality". The statement
$$
x = y
$$
says (in everyday mathematics) that "$x$" and "$y$" are different names for the same object. So of course it follows that
$$
f(x) = f(y) \ .
$$
This doesn't depend on $x$ and $y$ being numbers, or even on $f$ being a function. It can be any expression in $x$ and $y$.
I say "in everyday mathematics" because if you're studying foundations you need to be much more careful about things and the names of things.
For an extended discussion, see this nice essay by Barry Mazur:
http://www.math.harvard.edu/~mazur/preprints/when_is_one.pdf
Comment: "In everyday math" I agree with you. But I thought that there is something about it from the point of view of foundations.
Comment: @ЮрійЯрош Perhaps. To find out here you'd have to make it explicitly a question   about foundations - even more basic than Peano postulates. Ask it as a separate question rather than editing this one. You might enjoy the article I link to in my answer.
Comment: OK, thanks for the article, I will read it.

Question about properties of "equality"


How to generate and receive 16 QAM signal in python?

Question: I want to plot the SNR vs BER plot for 16 QAM. I need help in generating QAM signal
I tried generating it but I'm not sure if it is right
for n in range (0, itr):
    EbNodB = EbNodB_range[n]
    EbNo=10.0**(EbNodB/10.0)#antilog of SNR
    x=(np.random.randn(4,16,1)*2-5)+ 1j*(np.random.randn(4,16,1)*2-5)#QAM
    signal

   h=np.sqrt(np.random.normal(0,1)**2+np.random.normal(0,1)**2)/np.sqrt(2)
   #Magnitude of Rayleigh channel coefficient
   noise_var = 1/sqrt(2*EbNo) #AWGN variance
   noise=noise_var* randn(N) #AWGN noise
   y = h*x + noise
   y_d = y-h
   errors = (x != y_d).sum()
   ber[n] = errors / N

The plot appears empty
Comment: There is no decoder! How do you plan to calculate BER? You need to do some variant of minimum distance decoding (maximum likelihood detection) if you need to get meaningful BER.
Answer: You are missing a receive filter as you are introducing the channel as a distortion to your system without giving any compensation for that.
A very simple way of compensating the channel is by assuming, that you know the channel at the receiver and simply divide the received symbol by the channel
y = h*x + noise
y_filtered=y/h
y_d = y_filtered-h

Note that there are other ways of compensating the channel (especially when you have more than one channel component per transmitting symbol).


$\int_{a}^{+\infty}dx\int_{c}^{+\infty}f(x,y)dy=\iint_{D}f(x,y)dxdy$?

Question: Let $D:=[a,+\infty)\times[c,+\infty) $,where $a,c \in \mathbb{R};$  and let $f:D \mapsto \mathbb{R} $ be a nonnegative continuous function.
Prove that if the existence of either of the iterated integrals $\int_{a}^{+\infty}dx\int_{c}^{+\infty}f(x,y)dy$ and  $\int_{c}^{+\infty}dy\int_{a}^{+\infty}f(x,y)dx$ ,then the improper double integral $\iint_{D}f(x,y)dxdy$ converges to the value of the iterated integral in question.

WLOG,suppose $\int_{a}^{+\infty}dx\int_{c}^{+\infty}f(x,y)dy=I(\in\mathbb{R}).$
Given any $b,d\in\mathbb{R}$  with $b>a,d>c$,by Fubini's theorem,$$\iint_{R}f(x,y)dxdy=\int_{a}^{b}dx\int_{c}^{d}f(x,y)dy,R=[a,b]\times[c,d].$$
Let $\varphi(x,\beta ):=\int_{c}^{\beta}f(x,y)dy,$ then for each fixed $\beta_{0}(>c)$ and $\alpha^{"}>\alpha^{'}>a,$ we obtian $$\int_{a}^{\alpha^{"}}\varphi(x,\beta_{0} )dx\geq \int_{a}^{\alpha^{'}}\varphi(x,\beta_{0} )dx.$$
Since $\int_{a}^{+\infty}dx\int_{c}^{+\infty}f(x,y)dy=I,$
$\int_{a}^{\alpha}\varphi(x,\beta_{0} )dx$ with respect to $\alpha$ has upper unbound on $[a,+\infty).$
So $\lim_{\alpha \rightarrow +\infty}\int_{a}^{\alpha}\varphi(x,\beta_{0} )dx$ exists and is a real number .
Next we have $$\iint_{[a,+\infty)\times[c,\beta_{0} ]}f(x,y)dxdy=\int_{a}^{+\infty}\varphi(x,\beta_{0} )dx.$$
At this time, If we  can prove  $$\lim_{\beta \rightarrow +\infty}\int_{a}^{+\infty}\varphi(x,\beta_{} )dx=\int_{a}^{+\infty}\left (  \lim_{\beta \rightarrow +\infty}\varphi(x,\beta_{} )\right )dx,\quad (*)$$then $$\int_{a}^{+\infty}dx\int_{c}^{+\infty}f(x,y)dy=\iint_{D}f(x,y)dxdy=I$$

But until now,I have no idea to prove $(*)$ is true.I need some help to deal
with it ,or better solutions in other ways .
Comment: you used the formulation of Fubinis Theorem which is thought usually in an undergrad Analysis class. If you study measure theory you will learn a much more general formulation of the theorem! check for example wikipedia for a sketch of the proof.
Answer: $\forall \epsilon>0,\exists b>a$, s.t.$$\Biggl|\int_{a}^{b}dx\int_{c}^{+\infty}f(x,y)dy-I\Biggr|<\varepsilon$$, let $\{d_n\}$ be an ascending sequence satisfying $\lim_{n\to+\infty}d_n=+\infty$ and $\varphi_n(x)=\int_c^{d_n}f(x,y)dy$, $D_n=[a,b)\times[c,d_n)$, then
$$\int_{a}^{b}dx\int_{c}^{d_n}f(x,y)dy=\iint_{D_n}f(x,y)dxdy,$$
by Arzelà's dominated convergence theorem for the Riemann integral,
$$\lim_{n\to\infty}\int_a^b \varphi_n(x)dx=\int_a^b \lim_{n\to\infty}\varphi_n(x)dx=\int_{a}^{b}dx\int_{c}^{+\infty}f(x,y)dy$$
Then therer exists $N>0$, s.t. $\forall n>N$,
$$\Biggl|\int_{a}^{b}dx\int_{c}^{d_n}f(x,y)dy-\int_{a}^{b}dx\int_{c}^{+\infty}f(x,y)dy\Biggr|<\epsilon,$$
the rest of the proof is obvious.
The idea to prove Arzelà's theorem is to find a increasing sequence of continuous functions $\{g_n\}$ satisfying $\lim_{n\to\infty}\varphi_n>g_n(x)>\varphi_n(x)$ such that $\int_a^b g_n(x)-\varphi_n(x)dx$ is small enough, then by Dini's theorem $\{g_n\}$ converges to $\lim_{n\to\infty}\varphi_n$ uniformly, thus $\lim_n\int \varphi_n=\int \lim_n \varphi_n$
Comment: Thanks For Your Effort ! +1


Interpretation Maximum Likelihood Plot

Question: When using the likelihood method, plotting the relative likelihood or evidence against the range of possible values for the parameter ($\theta$) being estimated results in a curve. The maximum value will indicate the estimated parameter with the maximum likelihood (most supported by the data), $MLE=argmax_\theta \mathcal{L}(\theta|x)$, and a range can be extracted such that all the $\theta$ values are supported more than $1/8$ (horizontal orange line below) or $1/16$ (horizontal gray line) as compared to the maximum are highlighted (an estimated range).
For example, in the experiment of throwing a die multiple times, and observing the number of heads to estimate the probability of getting heads (bias),
n <- 4 # Number of coin flips
x <- 3 # Number of heads
theta <- seq(from=0, to=1, by = 0.001) # Possible range of probabilities of getting H.
L <- theta^x*(1-theta)^(n-x) # Likelihood of each theta given x.
df<- as.data.frame(cbind(theta,L))
maxL <- max(L)
ML_theta<-df$theta[which(df$L==maxL)]

plot(L/maxL ~ theta, type='l', col='firebrick', lwd=2, xlab="Theta",
     ylab="Relative likelihood")
lines(range(theta[L/maxL>1/8]), c(1/8,1/8), col='orange', lwd=2)
lines(range(theta[L/maxL>1/16]), c(1/16,1/16), col='slategray', lwd=2)
arrows(x1=ML_theta,x0=ML_theta, y1=0, y0=1, col='blue')

the MLE is $\theta = p(H)=0.75$ if we know that we got $3 \, heads\,1\, tail$, but the possible true probability of getting heads can be different, except for $0$ or $1$, and we may give a range of $\theta$'s with a minimum support of $1/8$, range(theta[L/maxL>1/8])= 0.262 to 0.986, (or similarly, we could do the same for $1/16$, yielding 0.203 to 0.993) relative to the maximum. This makes sense.
The question refers to the wording in the Coursera course (Brian Caffo, "Mathematical Biostatistics Boot Camp"; lecture 6 (slide 15)) I came across this, and the wording that is repeated several times in the recorded lecture:
"Parameter values above the $1/8$ reference line, for example, are such that no other point is more than 8 times better supported given the data."
Is the wording obtruse by necessity or by choice? Is my interpretation above wrong or incomplete, explaining why I'm missing the need for this painful and cryptic wording of the meaning of the plot? What is the lecturer trying to convey by making it so difficult? OK, I admit it, I don't know what he means... Can someone please explain?
Comment: The plot is really a plot of the likelihood function. A "maximum likelihood plot" would presumably consist just of the point (0.75,1).
Answer: OK... I had to think a bit about this tongue-twister.
In the plot in the OP, the y-axis shows the relative likelihood with a maximum of $1$, because every possible $\theta$ value in the $x$-axis is compared to the maximum likelihood point or value, which will have $1$ in the $y$ axis (it's divided by itself... sort of a normalization procedure).
By drawing a horizontal line along $1/8$ in the $y$ axis we guarantee that NONE of the $x$ axis points inside the interval defined by that line and the intersection with the curve will be MORE than eight times better supported by the data than the endpoints of the line (or segment) - the points of crossover of the line with the curve.
To see this, the question to ask is, are there ANY points within the interval limited by the line $two times$ (for example) better supported by the data? And the answer would be... any point in the interval defined by the horizontal line through $1/4$ (red line in the plot below), because any point along the red segment will have a relative evidence compared to the ends of the $1/8$ line at least $\frac{1/4}{1/8}=2$ times greater.

Yet, we won't find any points WITHIN the $1/8$ confines MORE than eight times better supported - the maximum is the maximum likelihood point ($1$), which is $\frac{1}{1/8}=8$ times better supported, but NOT... MORE than $8$.
So straightforward... In any event, I'm posting it in case someone else gets stuck with this play of words.

Interpretation Maximum Likelihood Plot


How to style a specific react-google-login component

Question: So, I am trying to style a GoogleButton from the react-google-login package, with external CSS. More specifically, I am trying to center it. However, try as I might, it won't center. I have tried:

align-content
align-items
align-self
box-align

All with no avail. How would I possibly style the component, considering it has a className of signInButton?
Here is a depiction of my current situation:
Comment: Have you tried setting the left/right margins to `auto`?
Comment: Try adding style style={{width: "50%"}}
Comment: @jo_va Tried both `left` and `margin-left` (and their right counterparts), but with no avail
Comment: @HemadriDasari tried this as well right now, nothing changed
Answer: Try this:
.signInButton {
  float:none;
  position:static;
  display:block;
  margin:auto;
  width:max-content;
}

if it will not work then you should provide list of used CSS properties for that button.
Note that these two
  float:none;
  position:static;

are optional, I put them there to override potential values that may interfere with alignment.
Answer: Make sure parent element is a flexbox.
.parent {
    display: flex;
    justify-content: center;
}

You can wrap the component into a new div and style it if you don't want to affect parent element.
Answer: You have to use renderProps to create a custom button:
render={renderProps => (
      <button onClick={renderProps.onClick} disabled={renderProps.disabled}>This is my custom Google button</button>
    )}

Check out this link.


Confusion in understanding classpath

Question: I'm confused in understanding, how java interpretor and java compiler searches for all the necessary jar files it requires from environment variables. As I have only set the set path variable for JDK directory, but I've not set any variable to search for any class libraries, which jvm requires. How can it search those important jar files?
Comment: What class libraries do you mean? Which jvm requires? Do you mean JVM jars? Those are already on classpath, by default.
Answer: Which jar files are you talking about? Java already knows about the jar files it "owns" (such as rt.jar) - you don't have to tell it about them explicitly. This is known as the bootclasspath - you can override it, but usually you don't want to.
Answer: For better understanding of how classes are found and loaded by JVM read How Classes are Found.
Comment: +1, but more recently: http://java.sun.com/javase/6/docs/technotes/tools/findingclasses.html
Comment: @trashgod Thanks for pointing that out.

Didn't notice that it was for 1.3.  :(  But most of the concepts still hold true thanks to Java's backward compatibility.
Answer: CLASSPATH is an enviromental variable is like the path file (which helps windows to find executables). It lists a set of all places the JVM looks for classes. You can also give the classpath on the command line when starting the jvm and java compiler

Confusion in understanding classpath


Access denied when enabling or setting by default a theme (on Nginx)

Question: I get an Access denied error page when attempting to enable or set by default a theme. It is kinda weird as I am allowed to perform other admin tasks.
I checked that my user is an administrator and it has all the permissions granted. I also made other checkings that I found in Drupal's forums and Drupal Answers but everything seems to be OK.
I have a standard install with no additional modules. Watchdog logs show the access denied warnings from http://drupal-testing/admin/appearance/enable?token=<...>&theme=encoreweb. In addition to check the permissions of my user, I reviewed settings.php to verify $cookie_domain was commented.
I've found that I'm not the only one with this problem, but I couldn't come to a conclusion.
Comment: Is it a clean install? Or what modules you are using? What's in watchdog? *"I also made other checkings"* - which ones?
Comment: @Mołot I just edited my question. Thank you very much!
Answer: I've got a solution after several hours working on it.
I am using Nginx instead of Apache and I did not configure it to add the query string in the rewriting to index.php. So neither the token nor the theme parameters were reaching the script and system_theme_enable()/system_theme_default() (located in /modules/system/system.admin.inc) always returned MENU_ACCESS_DENIED, which I consider to be a very confusing behavior by the way.
This is how the server config looks like now and makes it work:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Comment: This affected various operations involving a query string for me - everything from performing a search, to clearing the cache. It threw a non-specific 404 (missing token), so was hard to track down.
Answer: Adding to this question my specific scenario. I had installed Drupal 8.0.3 on Debian 8 (jessie), with php5-fpm and nginx. The install seemed to go flawlessly, until I tried to add a theme. I got "Access Denied" when attempting to set default theme from the administration page.
I had followed some guides for NGINX/Drupal installs, and wound up with the following section in my nginx.conf:
location / {
    try_files $uri $uri/ /index.php;
}

Per this answer on drupal.org, the $args parameter worked for me, updating the section to:
location / {
    try_files $uri $uri/ /index.php?$args;
}


What are HTTP request headers?

Question: Posting a form using AJAX
My AJAX script wasn't working before (it wouldn't send data) but setting the request headers solve the problem. It's great that it works but I want to understand why they are needed for it to work. Thanks :-)
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

javascript
function request(elm, type, url, str, fn) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        if (!fn) elm.innerHTML=xhr.responseText;
        else fn(xhr);
    }
}
      xhr.open(type, url, true);
      //yay it works with this :-)
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.send(str);
}

var form = document.getElementById("form_login")
var btnLogin = form.getElementsByClassName("btn")[0];
addEvent(btnLogin, "click", function(e)
{
    preventDefault(e);
    var post ="",input,inputs = form.getElementsByClassName("input");
    for (var i=0, l=inputs.length; i<l; i++)
    {
        input = inputs[i].getElementsByTagName("input")[0];
        post += input.name + "=" + encodeURI(input.value) + "&";
    }
    post = post.substr(0,post.length-1);
    var help = form.getElementsByClassName("help")[0];
    request(help, "POST", "user/login-exe.php?dt='" + new Date() + "'", post);
});

and if its all valid it will log the user in that bit isn't shown though.
Comment: Did you do any research?
Comment: @immanish you really need to post your server-side code. None of them are required. In fact, the later 2 don't do anything as they are something the browser must decide for you.
Comment: The first thing that comes to my mind is to ask the guy who answered your last question.
Comment: How I can't post comments yet. Wait where did this come from?
Comment: @immanish, sorry, my bad. Well, the second thing that comes to my mind is [this](https://google.com/search?q=What+are+request+headers)
Comment: Thanks but why do i have to set the content-length? and why is connection set to close? do i need all three and why doesn't it work without them.
Comment: @immanish: Did you happen to test the script on chrome? and it didn't work out for you? And after setting those headers it worked a charm?
Comment: @verisimilitude: It works in chrome, Firefox and IE tested on all newest versions.
Answer: This isn't strictly a requirement, PHP will just automatically populate $_POST when the request specifies content-type of "application/x-www-form-urlencoded".
You can still get access to the values with
file_get_contents("php://input");

In fact, any server should allow you to get access to the raw request body.
The other headers are not doing anything, the browser will not allow you to change them as is specified. If you were able to change them, you would probably report the wrong Content-Length everytime. Because .length counts UTF-16 code units where as Content-Length must be in bytes.
Reference: http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Terminate these steps if header is a case-insensitive match for one of
  the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Content-Transfer-Encoding
Date
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
Comment: Do I need all three header thingy's or is there a specific one that makes it work. :-)
Comment: @immanish it's just the content-type header, the other ones are not doing anything
Comment: I don't think it's necessary too. The default is `application/x-www-form-urlencoded` isn't it?
Comment: @verisimilitude in chrome, the default is `application/xml`. The specification says that the default must be `text/plain`.
Comment: Oh, so it mustn't have worked for the OP when he tested his script on chrome.
Comment: @verisimilitude it doesn't matter what browser, I don't think any browser has `application/x-www-form-urlencoded` as default. Firefox is following the standard and using `text/plain`.
Comment: Oh. :( I'm confused. So you mean @Esailija that none of the browsers encode a  ``'s data in the default `application/x-www-form-urlencoded`. Terribly confused :(
Comment: @verisimilitude he is not posting a form but sending an `XMLHttpRequest`. I never talked about any form elements and neither did the OP...
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/15229/discussion-between-verisimilitude-and-esailija)
Comment: If I am sending passwords do I have to do anything else to my script. I have edited my post to include it.
Answer: 1.) "Content-type" header for a <form>: Specifies the content-type to encode the form data set while submitting the form data over to the server.
application/x-www-form-urlencoded: Says to encode the form's data as
a.) Control names and values are listed in the order they appear; control name is seperated from it's value by an '=' and control names and values are delimited by an '&'
b) Control names and values are escaped. Space characters are replaced with a '+' and other reserved characters are escaped as described in RFC1738.
2) "Content-length" : This header indicates the size of the message body in decimal octets - What's the "Content-Length" field in HTTP header?
3) Connection: The state of the connection.
I don't think so setting "Connection" is required.
Comment: How can it be recommended when those 2 headers cannot be changed with XHR?
Comment: Which two? I only said "Content-length" above.
Comment: Well, I mean how can it be recommended to specify `Content-Length` when it is not allowed in the first place?
Comment: Ok. got it. Got it removed. And I also didn't know that chrome had it set to `application/xml` by default.
Comment: Well, yeah. But according to specification it must be `text/plain`. So it doesn't really matter. PHP will only fill `$_POST` with `application/x-www-form-urlencoded`

What are HTTP request headers?


Calculadora AndroiStudio

Question: Boa noite
Estou a criar uma aplicação utilizando 5 "caixas" (EditText) em que podesse multiplicar as caixas que quisesse.
Exemplo: valorodd1 * valorodd2= resu.... valorodd1*valorodd2*valorodd3=resu....valorodd1*valorodd2*valoodd3*valorodd4=resu....valorodd1*valorodd2*valoodd3*valorodd4*valorodd5=resu
Como na seguinte imagem:

Código:
public void somar (View v){

        EditText odd1 = (EditText) findViewById(R.id.editText7);
        String stringodd1 = odd1.getText().toString();

        EditText odd2 = (EditText) findViewById(R.id.editText8);
        String stringodd2 = odd2.getText().toString();

        EditText montante = (EditText) findViewById(R.id.editText12);
        String stringmontante = montante.getText().toString();

        NumberFormat formatter = new DecimalFormat("#0.00");

        if (stringodd1.trim().isEmpty() || stringodd2.trim().isEmpty()|| stringmontante.trim().isEmpty() )
        {
            Toast.makeText(getApplicationContext(), "Campos em branco",
                    Toast.LENGTH_LONG).show();
        }
        else
        {

            double valorodd1 = Double.parseDouble(stringodd1);
            double valorodd2 = Double.parseDouble(stringodd2);
            double valormontante = Double.parseDouble(stringmontante);

            double resu = valorodd1 * valorodd2 * valormontante;

            TextView resultado = (TextView) findViewById(R.id.textView15);
            resultado.setText (formatter.format(resu) + "€" );

Comment: Qual a questão que tem ou dificuldade que está a encontrar? Aproveite e acrescente o código que está a utilizar na aplicação que foca o sua duvida/dificuldade.
Comment: Tenho este código com uma simples soma na caixa 1 e 2. O meu objetivo é poder calcular a caixa 1 x 2 = total, ou caixa 1 x 2 x 3 = total ou caixa 1 x 6 = total.   Obrigado
Comment: Você tem algum botão que quando clica ele faz as operações ?
Comment: Fazer N multiplicações sucessivas ? E iam ser postas onde ? Existem N `TextViews` para esses resultados ?
Comment: Sim, como mostra no meu código acima tenho o botão para calcular as multiplicações. O erro no meu código é que tenho 6 Edittext para introduzir 1 número e 1 textview para apresentar o resultado, quando eu quero multiplicar 2 números não dá, pois sou obrigado a preencher as restantes "caixas" com números para fazer a multiplicação e eu quero poder utilizar a "caixas" que quiser. Se eu quiser multiplicar 2 número meto um número numa caixa e outro numero na outra caixa, se eu quiser multiplicar 3 meto pelo mesmo 1 numero em cada caixa e multiplico. Espero que tenham entendido. Obrigado
Answer: O melhor para o que pretende seria mesmo utilizar um array para os EditText e um ciclo/laço para os percorrer e efetuar as multiplicações caso contenham valores.
Seguindo essa ideia, ficaria assim:
public void somar (View v){

    //cria um array com os edits todos
    EditText[] edits = new EditText[] {
        (EditText) findViewById(R.id.editText7),
        (EditText) findViewById(R.id.editText8),
        (EditText) findViewById(R.id.editText9),
        (EditText) findViewById(R.id.editText10),
        (EditText) findViewById(R.id.editText11),
        (EditText) findViewById(R.id.editText12) //12 é o montante
    }

    TextView textResultado = (TextView) findViewById(R.id.textView15);

    double resultado = 1;
    boolean algumPreenchido = false;

    //aqui percorre agora todos os edits, sejam eles quantos forem
    for (int i = 0; i < edits.length; ++i){

        //aqui vê se o edit foi preenchido, e só multiplica se tiver valor
        if (!edits[i].getText().toString().trim().isEmpty()){
            resultado *= Double.parseDouble(edits[i].getText().toString());
            algumPreenchido = true;
        }
    }

    NumberFormat formatter = new DecimalFormat("#0.00");

    //Mostra o resultado caso tenha sido considerado algum valor, ou 0 caso contrário
    textResultado.setText (formatter.format(algumPreenchido ? resu : 0) + "€" );
}

Note que o programa irá falhar no calculo se algum dos EditText tiver valores preenchidos que não sejam números. Nessa situação terá que adicionar captura de exceções com try catch e dar o tratamento que considera apropriado.

Calculadora AndroiStudio


Add "timestamp" type for MySQL

Question: I used Drupal 7 and the Data module to import a table into Drupal. I could import the orphaned table, but my table has a column of type "timestamp" which does not show up when I try to edit the schema of the data table. I get the following error:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'published': ALTER TABLE {resource_profiles} CHANGE published published INT NOT NULL DEFAULT 'CURRENT_TIMESTAMP'; Array ( ) in db_change_field() (line 2988 of C:\xampp\htdocs\drupal\includes\database\database.inc).

I followed http://drupal.org/node/1466122, and added the timestamp datatype to /includes/database/mysql/schema.inc.
Where can I edit the schema information for my data table?
Comment: Where do you retrieve this error? I guess that the issue is into type you are trying to use (INT) and defining as a default value the current timestamp...
Comment: Yes.. the type is INT and I am trying to store a timestamp into it. But I added a new type called timestamp in the mysql database schema in drupal but "timestamp " does not show up when I try to edit the schema later within ui.
Comment: Also, if it's not a duplicate, and you want it to be possible in Drupal 7, then it would be a feature / backport request for Drupal 7 rather than a real question, and as such should be posted in issue queue on Drupal.org, not here.
Answer: Like Gian says, you can't have a default value of CURRENT_TIMESTAMP for an int field.
Due to Drupal's database abstraction layer timestamp is not a supported field type.
This is due to not all databases supporting timestamp or now() as a field default value as apposed to mySQL where it is supported. The solution / work around if you're using mySQL is to add a query to your .install that modifies the field default to now() where the field type is int. See the Data Type doc page for further discussion: http://drupal.org/node/159605 or see here for more info on Drupals DB Schema: https://api.drupal.org/comment/48593

Add "timestamp" type for MySQL