How many times does the number 111 appear in this sequence?

Question: Let $(a_n)$ be an integer sequence such that $a_1 = 1$ and for $n \geq 1$ positive integer,
$a_ {2n} = a_n + 1$ and $ a_ {2n + 1} $ = $10a_n$ How many times does the number $111$ appear in this sequence?
First $31$ terms of sequence (table):

$n- 1, 2, 3, 4, 5, 6, 7 , 8, 9 , 10 , 11,12,13,14,15,16$
$a_n - 1, 2, 10, 3, 20, 11, 100, 4, 30 , 21,200,12,110,101,1000,5$

$n - 17, 18,19,20,21,22,23,24,25,26,27,...$

$a_n - 40,31,300,22,210,201,2000,13,120,1100,...$

I made my way back to the first term, found $14$ times. is there anymore formalized method for finding the right value?
Comment: the answer should be the same as how many ways to make $111$ from $1$ by operate $\times10$ and $+1$ each time
Comment: I presume $10_{a_n}$ means $10$ in base $a_n$, so $a_{2n+1}=a_n$?
Comment: I think so! Not sure, I used a very logical and archaic method
Comment: If my interpretation is correct than $111$ appears infinitely many times. Please give the question definition of $a_n$.
Comment: It is the sequence of integers
Answer: I get $14$ times.  The number of times $n$ appears is the number of ways to reach $n$ by starting with $1$ and either adding $1$ or multiplying by $10$. If $f(n)$ is the number of ways $n$ appears we have the recurrence
$$f(n)=\begin {cases} 1&n=1\\
f(n-1)&n \not \equiv 0 \pmod {10}\\
f(n-1)+f(\frac n{10})& n \equiv 0 \pmod {10} \end {cases}$$
We have $f(100)=12$ because you can add $1\ 100$ times, you can multiply by $10$ twice, or you can add $1$ a number of times from $0$ to $9$, multiply by $10$ and add $1$ enough other times to get to $100$


move_uploaded_file returns false always when uploading file from Node server

Question: I am sending a file from node server to Api in PHP.
$name=dirname(dirname(dirname(__FILE__))).'/location/uploads/'.$files["image"]["name"];
if(!(move_uploaded_file($files["image"]["tmp_name"], $name))){
    $errmsg.= '5';
}

But move_uploaded_file returns false everytime without any errors.
Answer: The errors are stored in $_FILES, see example code on the move_uploaded_file manual page.
Check it with
var_dump($_FILES);

Somewhere in there is an error key.


Characteristic function characterize the distribution

Question: Theorem: Let $\phi(t)=\int{e^{itX}dF_X}$ be a characteristic function of a random variable $X$. Then $$\displaystyle \lim_{T \to \infty}\int_{-T}^{T}{{\frac{e^{-ita}-e^{-itb}}{it}}\phi(t)dt}=P(X\in (a,b))+\frac{1}{2}(P(X=a)+P(X=b)).$$
I want to prove that if two random variables $X,Y$ have the same characteristic function, then they have the same distribution function. Obviously using the result. Obviously if $P(X=a)=0=P(Y=a) \: \forall a\in \Bbb R$ then the result is clear.
Answer: Let $S$ denote the sets of points $a$ for which $\mathbb P\{X=a\}+\mathbb P\{Y=a\}\gt 0$. This set is at most countable. Hence, if $a\lt b$ are fixed, either $a,b\notin S$, and in this case $\mathbb P_X(a,b)=\mathbb P_Y(a,b)$, or at least one of these points is in $S$. If that happens, since $S$ is a countable set we can find $b_n\downarrow b$ such that $b_n\notin S$ and $a_n\uparrow a$ such that $a_n\notin S$ for all $n$. Then
$$\mathbb P(a \leq X \leq b)=\mathbb P\left(\bigcap_n \{X \in (a_n,b_n)\} \right)=\lim_n \mathbb P(a_n<X<b_n)=\lim_n \mathbb P_X(a_n,b_n),$$
and since $\mathbb P_X(a_n,b_n)=\mathbb P_Y(a_n,b_n)$ the desired result follows.


Consulta javascript no controller asp.net

Question: Eu preciso fazer uma consulta em um método da API (JavaScript) do google maps, porém pelo controller, é possível ?
Eu tenho uma requisição ajax que monta uma grid e dentro dela faço um consulta na tabela dbo.Atlas setando latitude e longitude para retornar o endereço, porém essa tabela não tem todos os endereço cadastros e nesse caso, precisaria executar esse procedimento para além de retornar na tela, também salvar na banco, assim da proxima vez ter esse registro na tabela.
Códigos:
public ActionResult ListaPosicoes(string pocsag)
        {

            dalOperador dalOper = new dalOperador();

            List<modOperadorDashLatLng> listaPosMapa = new List<modOperadorDashLatLng>();

            listaPosMapa = dalOper.pubEventosProcessadosDashMapa(pocsag);
            dalAtlasEndereco dalAtlas = new dalAtlasEndereco();

            foreach (var evento in listaPosMapa)
            {

                if (evento.latitude != 0 && evento.longitude != 0)
                {
                    evento.endereco = dalAtlas.pubTrasformaLatLongEndereco(evento.latitude.ToString(), evento.longitude.ToString());
                    if (string.IsNullOrEmpty(evento.endereco))// caso não exista na tabela dbo.Atlas
                    {
                        evento.endereco = ""; // Endereço que deveria retornar na API do google.Maps passando como parametros a latitude e longitude

                        //Inserir na tabela dbo.Atlas passando endereço, latitude e longitude.
                    }
                }

                else
                {
                    evento.endereco = "Não válido";
                }

            }
            var pontosMapa = Json(listaPosMapa, JsonRequestBehavior.AllowGet);

            pontosMapa.MaxJsonLength = int.MaxValue;
            return pontosMapa;
        }

Comment: Utilize o HttpClient para fazer a requisição
Answer: Boa tarde Igor, se eu entendi corretamente, essa seria uma alternativa para você consumir essa api pela controller:
    HttpClient _servico = new HttpClient();
    ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
    //base da url da api
    _servico.BaseAddress = new Uri("http://url");
    //Aqui vc define se deseja o retorno em json ou xml
    _servico.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    //Se necessário autenticacao, toten...
    _servico.DefaultRequestHeaders.Add("usuario", "senha");

    HttpResponseMessage resposta = _servico.GetAsync().Result;

//resposta com sucesso
if (resposta.IsSuccessStatusCode)
{
    //Sua variavel para guardar a lista de resultados
    listaResultados = resposta.Content.ReadAsAsync<List<ResultadoAPI>>().Result;
}


Criar uma div com aparência de balão de quadrinhos

Question: Como posso criar uma div com aparência de balão de quadrinhos (não sei se essa é a melhor expressão).
Objetivo:

Realidade:

*Favor ignorar fontes e cores em questão, o foco é ponta da div.
Segue o código no JSFiddle:
Answer: Versão CSS3
HTML

Oi!

CSS
.balao {
    float:left;
    background-color:#39c;
    border-top:10px solid #39c;
    border-left:10px solid transparent;
    background-clip: padding-box;
    padding: 0 10px 10px 10px;
}

Veja funcionando no JS Fiddle
Versão CSS2
HTML

Oi!

CSS
.balao {
    float:left;
    background-color:#39c;
    border-top:10px solid #39c;
    border-left:10px solid #eee; /* Usar mesma cor do fundo*/
    padding: 0 10px 10px 10px;
}

Veja funcionando no JS Fiddle
Comment: ou `transparent` ;)
Comment: IE7+ eu sei que funciona. Sabe algum outro que dê problema?
Comment: Muito obrigado! diante do projeto a solução funcionaria, valeu
Comment: @beterraba com CSS3 dá pra usar `transparent`, mas precisa de `background-clip: padding-box;`. Pus uma versão CSS3 pra usar sua sugestão.
Comment: Realmente excelente @Bacco ! Só ainda estou tentando entender em como o border-left criou só aquela tirinha, e não colocou a borda inteira verticalmente.
Comment: @AllanRamos espie essa versão para facilitar a visualização: http://jsfiddle.net/Bacco/7egdpw0g/5/ - só tem borda em cima e à esquerda, esse foi o "truque".
Answer: Outro exemplo aqui:
.content_ballon{
    background: #37688D;
    height: 50px;
    width: 100px;
    position: relative;
    margin-left: 9px;
    color: #fff;
    padding: 3px 5px;
}

.ballon img{
    position: absolute;
}

jsFiddle
Ai você movimenta a classe "ballon" para onde quer.
Comment: Dica de ferramenta para gerar speech bubbles em CSS: http://www.ilikepixels.co.uk/drop/bubbler/
Comment: Bacana esse heim @OnoSendai, não conhecia ainda. Valeu!
Comment: Valeu cara! Era exatamente isso que procurava obrigado XD
Comment: Por nada, estamos ai pra ajudar.
Answer: Uma outra forma de fazer:
.balao {
    background:blue;
    position:relative;
}
.balao:before {
    content:'';
    position:absolute;
    left:-10px;
    top:0;
    border-bottom: 10px solid transparent;
    border-right:10px solid blue;
}

Exemplo completo: FIDDLE
Comment: Muito obrigado extremamente util e sem a necessidade de utilizar imagem ou criar outro elemento, valeu XD


Convert 2D string array into 2D int array (Multidimensional Arrays)

Question: I want to replace string[,] 2D array
public static readonly string[,] first =
{
    {"2", " ", " ", " ", "1"},
    {"2", " ", "4", "3", " "},
    {" ", "2", " ", "1", " "},
    {" ", "1", " ", "3", " "},
    {"1", " ", " ", " ", " "}
};

into int[,] array
int X=-1;
public static readonly int[,] second =
{
    {2, X, X, X, 1},
    {2, X, 4, 3, X},
    {X, 2, X, 1, X},
    {X, 1, X, 3, X},
    {1, X, X, X, X}
};

Is it possible to convert a string[,] array to an int[,] array? If yes, how can I convert the string[,] into int[,]? Thank you.
Comment: I have tried to solve this with a loop, but I couldn't do it because the X should be the empty String `""`
Comment: I don't understand what you're trying to do, then. If `X` isn't an `int`, then you can't put it in an `int` array.
Answer: string[,] first =
{
    {"2", " ", " ", " ", "1"},
    {"2", " ", "4", "3", " "},
    {" ", "2", " ", "1", " "},
    {" ", "1", " ", "3", " "},
    {"1", " ", " ", " ", " "}
};

int[,] second = new int[first.GetLength(0), first.GetLength(1)];
int x = -1;
for (int i = 0; i < first.GetLength(0); i++)
{
    for (int j = 0; j < first.GetLength(1); j++)
    {
        second[i, j] = string.IsNullOrWhiteSpace(first[i, j]) ? x : Convert.ToInt32(first[i, j]);
    }
}

Answer: Live example: Ideone
public static readonly string[,] first =
{
     {"2", " ", " ", " ", "1"},
     {"2", " ", "4", "3", " "},
     {" ", "2", " ", "1", " "},
     {" ", "1", " ", "3", " "},
     {"1", " ", " ", " ", " "}
};

Convert (note that when the string  = " ", I'm putting a 0 instead):
int[,] second = new int[first.GetLength(0), first.GetLength(1)];

for (int j = 0; j < first.GetLength(0); j++)
{
    for (int i = 0; i < first.GetLength(1); i++)
    {
        int number;
        bool ok = int.TryParse(first[j, i], out number);
        if (ok)
        {
            second[j, i] = number;
        }
        else
        {
            second[j, i] = 0;
        }
    }
}

Answer: Assuming X = -1:
private static int[,] ConvertToIntArray(string[,] strArr)
{
    int rowCount = strArr.GetLength(dimension: 0);
    int colCount = strArr.GetLength(dimension: 1);

    int[,] result = new int[rowCount, colCount];
    for (int r = 0; r < rowCount; r++)
    {
        for (int c = 0; c < colCount; c++)
        {
            int value;
            result[r, c] = int.TryParse(strArr[r, c], out value) ? value : -1;
        }
    }
    return result;
}

Answer: Use the loop you are using and replace the empty strings by null values, and if you're going to use this array just check if the value is not null.


VSPEX vs vBlock

Question: I've been reading about storage and the next two solutions (reference architecture / converged) made me a little confused whether is more advantageous to go with one of another assuming the following assumptions as standards:
Virtualization: VMware
Networking: Cisco
Compute: any
I understand that vspex is flexible (not bound to single vendors) but assuming you want the same technologies included in the vblock what would make to go to one route or another?
Does it vspex also offers a "single support phone number"?
Thanks
Answer:
but assuming you want the same technologies included in the vblock what would make to go to one route or another?

vBlock is a set architecture from VCE, which is a partnership between Cisco, EMC, and VMWare. You don't get to choose which vendors VCE supports in a vBlock. It's these three. You have latitude based on which switches and blades and storage shelves you get, but they're all coming from these three vendors and are supported by VCE.
vSpex, on the other hand, is a set of reference architectures that include components from other vendors such as HP. This is not supported by VCE. This is installed and (potentially) supported by larger VARs that partner with EMC. VSPEX is entirely EMC-driven.

I understand that vspex is flexible (not bound to single vendors) but assuming you want the same technologies included in the vblock what would make to go to one route or another?

If you build a "VSPEX" architecture out of EMC, Cisco, and VMware and don't buy it as a vBlock, then there's no advantage. What you're doing is buying the three separately and you don't get to leverage unified VCE support.

This is a good read on the difference, and why VSPEX came about: http://www.virtualizationpractice.com/emc-vspex-vs-vblock-or-netapp-flexpod-can-vmware-vars-refuse-the-offer-15560/

VSPEX vs vBlock


Why is FastQC not working after using Trim galore?

Question: I have a FASTQ file and I'm able to run the FASTQC program to analyse the file. but when I use trim_galore, FASTQC (or the FASTQC option in trim_galore) is not working anymore.
$ fastqc ./sub1_val_1.fq.gz

This is the output:
Started analysis of sub1_val_1.fq.gz
Analysis complete for sub1_val_1.fq.gz
Failed to process file sub1_val_1.fq.gz
java.lang.ArrayIndexOutOfBoundsException: -1
    at uk.ac.babraham.FastQC.Modules.SequenceLengthDistribution.calculateDistribution(SequenceLengthDistribution.java:100)
    at uk.ac.babraham.FastQC.Modules.SequenceLengthDistribution.raisesError(SequenceLengthDistribution.java:184)
    at uk.ac.babraham.FastQC.Report.HTMLReportArchive.startDocument(HTMLReportArchive.java:336)
    at uk.ac.babraham.FastQC.Report.HTMLReportArchive.<init>(HTMLReportArchive.java:84)
    at uk.ac.babraham.FastQC.Analysis.OfflineRunner.analysisComplete(OfflineRunner.java:155)
    at uk.ac.babraham.FastQC.Analysis.AnalysisRunner.run(AnalysisRunner.java:110)
    at java.lang.Thread.run(Thread.java:695)

Is the Failed to process file an error because the version is not correct between trim_galore and FastQC?
I found this, but that wasn't that helpful.
I'm using FastQC v0.11.5 and trim_galore v0.4.1.
I subsetted a library (reads in paired-end) using this:
seqtk sample -s100 ./SRR2937435_1.fastq.gz 10000 | gzip  > sub1.fastq.gz
seqtk sample -s100 ./SRR2937435_2.fastq.gz 10000 | gzip > sub2.fastq.gz

The sub1_val_1.fq.gz file was after passing sub1.fastq.gz into trim_galore. FastQC with sub1.fastq.gz is working.

Note: As suggested posted on biostars.org.
Comment: Consider asking your bioinformatics-related questions at https://www.biostars.org/
Comment: I'm new to this, so thank you for your help redirecting me to the best place.
Answer: I found the answer:
You have to uncompress it. Probably, trim_galore is only working with tar.gz and not fastq.gz.
gzip -d -k sub1.fastq.gz > sub1.fastq
y # to accept to overwrite
gzip -d -k sub2.fastq.gz > sub2.fastq
y # to accept to overwrite

trim_galore  --illumina --paired --fastqc sub1.fastq sub2.fastq


Instance member cannot be used when its already declared

Question: I'm declaring UIColors in an extension: UIColor file but I keep getting error like "instance member 'red' cannot be used on type 'UIColor', when I declared it already in the extension file. I will list a picture of the error and the code below.
Error image
Extension UIColor File
import Foundation
import UIKit

  extension UIColor {

var red: CGFloat {
    get {
        let components = self.cgColor.components
        return components![0]
    }
}

var green: CGFloat {
    get {
        let components = self.cgColor.components
        return components![1]
    }
}

var blue: CGFloat {
    get {
        let components = self.cgColor.components
        return components![2]
    }
}

var alpha: CGFloat {
    get {
        return self.cgColor.alpha
    }
}

func alpha(_ alpha: CGFloat) -> UIColor {
    return UIColor(red: self.red, green: self.green, blue: self.blue, alpha: alpha)
}

func white(_ scale: CGFloat) -> UIColor {
    return UIColor(
        red: self.red + (1.0 - self.red) * scale,
        green: self.green + (1.0 - self.green) * scale,
        blue: self.blue + (1.0 - self.blue) * scale,
        alpha: 1.0
    )
}
 }

Swift file where I would like to use one of the colors.
var color: UIColor = UIColor.red {
    didSet {
        setup()
    }
}

Answer: The red, green, and blue property names you added in your extension conflict with the class variables of the same names. Rename the properties in your extension.
FYI - there is no need for your alpha method in your extension. UIColor already provides the same method (named withAlphaComponent).
And your implementation of red, green, and blue may crash. You are assuming the CGColor always has 3 components and you assume it is an RGB color. Neither case is always true.
Comment: @LeoDabus I thought that at first too but then I looked closer at their `white` method. It's definitely quite different. This one is shifting the current color, not just creating a shade of gray.
Comment: to make it complete you should mention that his white method is also useless as UIColor has already an initializer specific for that purpose `init(white:alpha:)` https://developer.apple.com/reference/uikit/uicolor/1621944-init


Find an implicit function $H(x,y)=c$ on which the trajectories of $\frac{dx}{dt}=2y+xy^2, \frac{dy}{dt}=8x-y^3$

Question: Find an implicit function $H(x,y)=c$ on which the trajectories of $\frac{dx}{dt}=2y+xy^2, \frac{dy}{dt}=8x-y^3$.
I am studying for my qualifying exams and this problem came up. I have no idea how to approach it.
Comment: is there a reason why such an invariant $H$ should exist?
Comment: @abel Indeed. The phase diagram of the system shows that most trajectories "escape to infinity", a fact which severely restricts the candidates for such an invariant.
Comment: the divergence of the vector field is $(2y+xy^2)_x + (8x-y^3)_y = -2y^2$ so does not bendixon's criteria rule any closed orbits? have only the origin, a hyperbolic fixed point only goes to confirm that.
Comment: @abel On the other hand, the absence of closed orbits does not prevent the existence of an invariant H... :-)
Comment: @Saif were you able to obtain the official solution? Based on the lengthy, but now deleted, discussions/ideas with other members, I'm pretty sure such a solution doesn't exist.
Comment: unfortunately I wasn't. This was a question, word for word from a qualifying exam a few years ago.
Comment: I wonder who deleted the lengthy discussion of Agunra R's possible solution? If you try to push the idea used in that solution further, you would be able to show there doesn't exist such function $H(x,y)=c$. Note that my proof requires A and B are constants (in fact, this is the only possible case!) due to the way he set up the equations to solve for each partial derivative.
Comment: @user177196 Actually, what you call "possible solution" does not go very far since, once straightened up, it simply says that every solution $H$ is such that $$\frac{\partial H}{\partial x}=(y^3-8x)\cdot L(x,y),\quad\frac{\partial H}{\partial y}=(2y+xy^2)\cdot L(x,y),$$ for some unknown function $L$. And now what? We know this is impossible with $L$ some nonzero constant but some cleverly chosen, nonconstant, function $L$ could yield a nontrivial invariant $H$ of the dynamics.
Comment: @Did it is possible that such L doesn't exist.
Comment: @user177196 Beware that to exist and to admit a simple analytical form are two different notions. Assume for example that every solution $(x(t),y(t))$ meets the $x$-axis exactly once, then define $H$ by the condition that the solution starting from $(x,y)$ meets the $x$-axis at $(H(x,y),0)$ (for example, $H(x,0)=x$). Thus $H$ would *exist* but we would have no (general) formula for $H$.
Comment: @Did the main issue is: how do we know such a solution $(x(t), y(t))$ exists, and whether they meet the x-axis exactly once?
Comment: @user177196 No, this was just an example to explain concretely that H might exist, but be intractable.
Answer: 1st hint: from the two equations, $\frac{dy}{dx}=\frac{8x-y^3}{2y+xy^2}$. Solving this DE may be quite difficult, but you may want to try:)
2nd hint: We have $y\frac{dx}{dt}+x\frac{dy}{dt}=2x^2+8y^2$. Thus $(xy)'= 2x^2+8y^2$. By integrating both sides, we get $xy=\frac{2x^3}{3}+ \frac{8y^3}{3}$? (Edit: and actually we don't...)
Comment: I that is the point I got to as well. But I figured it was the incorrect path because of how horrendous it is.
Comment: "By integrating both sides", we do not get what you write.
Comment: @Did: that's why I left the question mark at the end...
Comment: No. If one writes "hint", one states that the approach DOES lead to a solution. Otherwise, one is taking the risk to send the hapless OP into a dead-end. Are you saying you knowingly took that risk in the present case?
Comment: @Did: yeap... my bad:P
Comment: @Did: were you able to prove that there doesn't exist such function $H(x,y)=c$ based on the ideas of Agunra's R possible solution, which was once posted but deleted two weeks ago?
Comment: @user177196 No, see my comment to the main question.


Ruby - Regular Expression to allow any Non-ASCII - Chinese characters in URL

Question: I am trying to write a regex for a URL which contains Chinese characters too. Purpose to write such a regex is whenever a URL containing Chinese characters is encountered, it doesn't match the URL and gives output as no results found.
I have a regex which is working for normal URLs which is as below:
^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$

This covers anything which is as for example www.google.com but doesn't work for URL like http://www.詹姆斯.com/.
I have also tried Ruby's URI module for validating the URLs but it doesn't work.
I am using Rubular to check my regex.
Expected: A regex in Ruby which validates any URL including characters in any language(i.e. French, Chinese etc) along with its query string parameters as http://www.詹姆斯.com/?abc=1234.
Comment: Try `/\A(?:https?:\/\/)?[\d\p{L}_.-]+\.([\p{L}.]{2,6})(?:\/[^\s\/]*)*\/?\z/`
Comment: Or, `/\A(?:https?:\/\/)?[\d\p{L}_.-]+\.([\p{L}.]{2,6})(?:\/[^?#\s\/]*)*(?:[?#]\S*|\/)?\z/`
Comment: Then try `\A(?:https?:\/\/)?(?!www\.[^\/]*$)[\d\p{L}_.-]+\.([\p{L}.]{2,6})(?:\/[^\s\/]+)*\/?\z`, see https://rubular.com/r/9Wnl7HLoYSg7nT
Comment: Try replacing `a-z` with `[:alpha:]` and `\w` with `[:alnum:]_`. If it does not help, try `\p{L}` instead of `a-z` and `\p{L}0-9_` instead of `\w`.
Comment: @WiktorStribiżew: Thanks. This worked for the host part only but not for the rest of the URL which can be `www.chinese-char-url.com/?abc=1234`.
Comment: @WiktorStribiżew: Both of your above options works. But it also matches a URL such as `https://www.abc` which is not a valid URL as `.com` is missing, hence it shouldn't get matched.  I hope you can fix this issue and write as an answer below so that i can approve. Thanks.
Comment: Worked !!! Please write the same in answers below so that I can mark it as approved.
Answer: I'm not sure about the rest of your regex (the query/path part),  so let me focus just on the host part. You need to use unicode character classes, e.g. \p{L} instead of [a-z] that is ASCII-only. For instance:
'http://www.詹姆斯.com/?abc=1234'.match(/^(https?:\/\/)?([\d\p{L}\.-]+)/)
# => #<MatchData "http://www.詹姆斯.com" 1:"http://" 2:"www.詹姆斯.com">

See more in docs.
Comment: Thanks for the response. The problem here is that it should match the query string parameters too. To match only the `host` doesn't solve my problem in this case. Let me know if you have any queries.
Answer: You may use
/\A(?:https?:\/\/)?(?!www\.[^\/]*\z)[\d\p{L}_.-]+\.[\p{L}.]{2,6}(?:\/[^\s\/]+)*\/?\z/

See the regex demo
NOTE: To match a whole string with a Ruby regex, you should use \A and \z, not ^ and $ that match start and end of any line. That is why the demo is different from the final regex posted.
Pattern details

\A - start of string
(?:https?:\/\/)? - an optional http:// or https://
(?!www\.[^\/]*\z) - the text that is immediately to the right cannot be www. and followed with any 0+ chars other than / up to the end of the string
[\d\p{L}_.-]+ - 1 or more digit, letter, _, . or - chars
\. - a dot
[\p{L}.]{2,6} - 2 to 6 letters or dots
(?:\/[^\s\/]+)* - 0 or more sequences of / and 1+ chars other than whitespace and /
\/? - an optional /
\z - end of string.


Supervisor not using /etc/environment

Question: I have an script in PHP that prints an environment variable set in /etc/environment with getenv.
It works fine when I execute it manually, but when is executed by supervisor, it doesn't work.
I don't want to put manually this environment variable on supervisor conf file, I want it to read /etc/environment correctly.
Any help? Thanks in advance
Answer: As it says in supervisord config files documentation:
supervisord config documentation
In the section environment:

Note that the subprocess will inherit the environment variables of the shell used to start "supervisord" except for the ones overridden here.

I supose that you start supervisord using systemd.
In that case you could check your supervisord.service and in the Service section add:
<code>EnvironmentFile=/etc/environment
</code>
After doing a systemctl daemon-reload and systemctl restart supervisord I supose it should work
You could check where is your supervisord.service file using:
<code> systemctl status docker
 docker.service - Docker Application Container Engine
    Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: disabled)
</code>
I have used docker because I have not installed supervisor in my dev machine, but it's the same
Answer: getenv gets the value of an environment variable, it doesn't read values from a file. If the environment variable isn't set for your supervisor's session then how can getenv retrieve the value?
From your session, enter the 'set' command. What is the output of that command?
From your supervisor's session, enter the 'set' command? What is the output?
Are you certain that the environment variables for your session are getting set via /etc/environment?
Comment: Environment variables are set by /etc/environment as @olibiaz linked

Supervisor not using /etc/environment


Prove by induction... With exponent and factorial

Question: Could someone please help me to prove this by induction?
$$ \left(1+\frac{1}{1}\right) ^1\cdot \left( 1+\frac{1}{2}\right)^2\cdot...\cdot\left( 1+\frac{1}{n-1}\right)^{n-1}=\frac{n^n}{n!}, $$  for $n\ge2$
Thanks!
Comment: What have you tried so far? Add your best attempt in the question so people know how to most appropriately answer you.
Comment: May be you mean that the domain of $n$ is $n\geq 2$ rather than $n=2$
Comment: sorry, thats what I meant, domain $n\geqslant 2$.
Comment: I´ve already regarded that in my answer.
Answer: $n\geq 2$ is the domain of $n$. Then start with the base case
$\texttt{Base case:}$ For $n=2$ we have $\left(1+\frac{1}{1}\right)=\frac{2^2}{2}\Rightarrow 2=\frac42 \checkmark$
$\texttt{Inductive step:}$ Let $X= \left(1+\frac{1}{1}\right) ^1\cdot \left( 1+\frac{1}{2}\right)^2\cdot...\cdot\left( 1+\frac{1}{n-1}\right)^{n-1}$
Then for $n+1$ the equation is
$\left( 1+\frac{1}{n}\right)^{n}\cdot X=\frac{(1+n)^{n+1}}{ (n+1)!}$
$\left( 1+\frac{1}{n}\right)^{n}\cdot X=\frac{(1+n)^n\cdot (n+1)}{n!\cdot (n+1)}$
Canceling out $(n+1)$.
$\left( 1+\frac{1}{n}\right)^{n}\cdot X=\frac{(1+n)^n\cdot }{n!}$
We have $n\cdot \left  ( 1+\frac{1}{n}\right)=n+1$. Therefore $\left( 1+\frac{1}{n}\right)^{n}=\left(\frac{n+1}{n}\right)^n $
I think you can take it frome here.


Where cookies are stored in system?

Question: If i use Response.Cookies["test"].Value ="Hi"; where are cookie stored in system?
Can i check Cookies["test"] value in my pc because cookies are stored in text format.
I am using VS 2008. Operating system is Windows 7.
I have tried to find in Google but not getting the exact answer. Please help to sort out this problem.
Comment: Click Start, type shell:Cookies to display the cookies folder (be sure hidden files & folders are visible). See: http://www.hevanet.com/tech/win7shortcuts.html
Answer: IE and Windows keeps cookies here:
%AppData%\Microsoft\Windows\Cookies

Points to the same directory as @Sohnee's does under Windows Visa and newer, but his doesn't under Windows XP and earlier, my - does.
also Temporary Internet Files can contain some cookies.
Meanwhile Firefox keeps cookies into SQLite database under profile root:
%AppData%\Mozilla\Firefox\Profiles\%FirefoxProfile%\cookies.sqlite

To read the data you need to connect to that database using any SQLite client and execute next query:
select value
from moz_cookies
where name = 'test'

I did it just now using trial SQLite Maestro. And don't forget to close all running Firefoxes before connection attempt.
Comment: can you please explain how to use this tool?
Answer: Cookies are stored in the cookies folder on Windows 7. To open the cookies folder, open run in Windows and type shell:cookies. Also, as suggested above, they might be in Temporary internet files. However, I see that your cookies are not persistent. This means you are not setting any expiration on them. Therefore, they won't be stored on your machine and they will only be part of the browser's memory.
Comment: Good point: without an expiry, it will be a session cookie stored in RAM. Which raises the question, do any browsers have tools that reveal session cookies, or do you have to use a tool like Fiddler to intercept what is received and sent?
Answer:
C:\Users\<user_name>\AppData\Local\Google\Chrome\User Data\Default

Also note, "Local" is a hidden folder.
Answer: For Windows :

C:\Users\Your User Name\AppData\Local\Google\Chrome\User
  Data\Default.

For Mac:

~Library/Application\ Support/Google/Chrome/Default/Cookies

You can use SQLite Browser for access it .
Answer: Your cookies are stored in your user folder:
%userprofile%\AppData\Roaming\Microsoft\Windows\Cookies

You will need to "show" hidden / system files to see them.
Comment: Hey Thanks but I did not find Cookies folder inside Windows folder.
Comment: I have tried to find cookies but not getting any thing.Mozila 3.6.10
Comment: Okay, you could do a search for folders named "Cookies", it should be in that kind of area. What browser are you using?
Comment: `AppData\Roaming` doesn't exist under Windows XP and earlier
Comment: I am using windows 7 live..I got the path %userprofile%\AppData\Roaming\Microsoft\Windows\
Comment: @abatishchev - the question is explicitly about Windows 7.
Comment: Anyway hard-coding OS-specific directory name is a bad idea, right?
Comment: @abatishchev - the question seems to be in relation to debugging, i.e. checking the cookie that has been programatically created - not about manually getting cookies from the specified directory.
Answer: On Windows 10, I press Win+R and type shell:Cookies to open the cookies folder.
it's a hidden folder, the path is

C:\Users\admin\AppData\Local\Microsoft\Windows\INetCookies

Where cookies are stored in system?


PDOException: SQLSTATE[42000]: Syntax error or access violation

Question:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1118
  Row size too large. The maximum row size for the used table type, not
  counting BLOBs, is 8126. You have to change some columns to TEXT or
  BLOBs:

Database storage Engine : Innodb
Do we have to switch over for MyIsam?
Comment: The reason of the error is because the uc_products['Ubercart Table'] table exceeds the limited size of innodb support.
Comment: InnoDB restricts row size to something less than half a database page (approximately 8000 bytes), not including VARBINARY, VARCHAR, BLOB, or TEXT columns.
Comment: could you please provide more info on exactly in which scenario you encountered this error.
Answer: Sounds like a case of InnoDB File Format issues.
SUGGESTION #1
If you are not using innodb_file_per_table, you may need to export all the data with mysqldump, delete ibdata and ib_logilfe0 and ib_logilfe0. Then, reimport that data. I wrote a detailed step-by-step process for this 2 years ago.
SUGGESTION #2
Increase the size of your InnoDB Log Files. Each file (ib_logfile0,ib_logfile1) needs to be more than 10 times as big as the biggest BLOB in your dataset:
Here are several links discussing this scenario

https://serverfault.com/q/293406/69271
https://serverfault.com/a/3979/69271
http://www.mysqlperformanceblog.com/2008/11/21/how-to-calculate-a-good-innodb-log-file-size/
http://bugs.mysql.com/bug.php?id=39168

MySQL's maximum size of innodb_log_file_size for a log group of of 2 files is 2047M. Should you ever need InnoDB Log Files that can exceed the 4GB combined barrier, you must upgrade to Percona Server.
I also wrote a detailed step-by-step process for resizing InnoDB Log Files.
SUGGESTION #3 (OPTIONAL)
You may want to switch the innodb_file_format to Barracuda. Bill Karwin's answer in the DBA StackExchange and links thereof explains why.
Comment: Faced this issue when installing Drupal 8 with a translation. Increasing "innodb_log_file_size" fixed the problem. Thanks!


Java contain string search in codechef problem

Question: I am new to codechef. Tried solving simple problem at FANCY problem statement.
Copying below problem statement for easy reference:
Chef was reading some quotes by great people. Now, he is interested in classifying all the fancy quotes he knows. He thinks that all fancy quotes which contain the word "not" are Real Fancy; quotes that do not contain it are regularly fancy.
You are given some quotes. For each quote, you need to tell Chef if it is Real Fancy or just regularly fancy.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single string S denoting a quote.
Output
For each test case, print a single line containing the string "Real Fancy" or "regularly fancy" (without quotes).
Constraints
1≤T≤50
1≤|S|≤100
each character of S is either a lowercase English letter or a space
Subtasks
Subtask #1 (100 points): original constraints
Example Input
2
i do not have any fancy quotes
when nothing goes right go left
Example Output
Real Fancy
regularly fancy
My solution is below which runs fine locally on my machine but gives NZEC exception when I try to run on codechef. Submitting this solution results in "Wrong Answer". Used try/catch block because I read here that it will avoid the exception but still answer is not right. I don't understand where am I wrong in this simple problem.
/* package codechef; // don't place package name! */

import java.util.Scanner;

public class Main
{
    private final static String REAL_FANCY   = "Real Fancy\n";
    private final static String REGULARLY_FANCY  = "regularly fancy\n";
    private final static String MATCH_WORD   = " not "; //note: space both sides
    private final static String MATCH_WORD_START = "not "; //note: space at end
    private final static String MATCH_WORD_END   = " not";//note: space at start

    public static void main(String[] args)
    {
    try
    {
        Scanner scanner = new Scanner(System.in);
        int testCases = Integer.parseInt(scanner.nextLine());

        StringBuilder output = new StringBuilder();
        String str = null;
        for (int i = 0; i < testCases; i++)
        {
        str = scanner.nextLine();
        if (str.startsWith(MATCH_WORD_START) || str.contains(MATCH_WORD)
            || str.endsWith(MATCH_WORD_END))
            output.append(REAL_FANCY);
        else
            output.append(REGULARLY_FANCY);
        }
        scanner.close();
        System.out.println(output.substring(0, output.length() - 1));
    }
    catch (Exception e)
    {
    }
    }
}

Comment: Should `cannot` be *regularly fancy* or *real fancy*? Also is there anyway we can run your code snippet on codechef?
Comment: "cannot" is regularly fancy NOT real fancy because it doesn't contain **_not_ as word** though it contains **_not_ as char sequence**. Yes code can be run on codechef and that's how I got NZEC exception.
Answer: There is a logic issue with your code as it fails just recognize 'not ' (notice the space) as a Fancy word.
You can change your if logic and use a regex instead.
if (str.matches(".*\\bnot\\b.*")) {
    output.append(REAL_FANCY);
} else {
    output.append(REGULARLY_FANCY);
}

Here the regex pattern matches the whole word not only. In detail explanation of this regex can be found here.
Comment: That won't work. Take an example of test case -> _He cannot go_. Here "cannot" is regularly fancy NOT real fancy because it doesn't contain **not as word** though it contains **_not_ as char sequence.**
Comment: Please consider upvoting the answer as well.


HTTP Status: 12002 in .net browser control

Question: I am getting HTTP status 12002 while opening my webpage in Browser control inside my desktop application. But its working fine in internet explorer. I am using .NET 3.5.
Error:

An unknown error occured. Http Status: 12002

What can be the issue?
Answer: Coming late but hopefully this will help someone else.
After hours of searching I found out that this is an IE client issue. Unfortunately the only answer is to change a local registry setting.
<code>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\
InternetSettings\ReceiveTimeout
</code>
Set that to more than 10000 (10 seconds).
Comment: In my case, the key did not exist so I had to add it.  Once I did, I started getting status=200 (I was also originally getting 12002 on Windows Server 2012)


How many have there pairs of disjoint subsets of a set of $n$ elements?

Question: -How many have there pairs of disjoint subsets of a set of $n$ elements?
I did other assignments about pairs of subsets where one is a subset of the second, using functions similar to characteristic functions. But I dont have an idea about this one.
Answer: Assuming you mean ordered pairs:
Step 1: Choose a subset.
Step 2: Choose a subset from the remaining (unchosen) elements.
If you restrict your attention to the situation in which the first subset has size $m$, there are $\binom{n}{m}$ ways to choose the first subset, and $2^{n-m}$ ways to choose the second given the first.  (This assumes that the empty set is allowable.) So, the number you want would be
$$
\sum_{m=0}^{n}\binom{n}{m}2^{n-m}.
$$
How can we simplify this?  Well, we can write
$$
\sum_{m=0}^{n}\binom{n}{m}2^{n-m}=2^n\sum_{m=0}^{n}\binom{n}{m}\left(\frac{1}{2}\right)^m=2^n\left(1+\frac{1}{2}\right)^n=3^n.
$$
That might seem surprising; but there's another way we could've gotten it.  To every one of your $n$ elements, assign a label $0$, $1$, or $2$. The ones with $0$ are left out; the ones with $1$ occur in the first subset; and the ones labeled $2$ occur in the second subset.  This is a bijection which shows that there are as many arrangements as there are functions from $n$ objects to $\{0,1,2\}$, which is also precisely $3^n$.
Comment: Thanks a lot Nick Peterson!
Answer: For each subset $A$ with $k$ elements in the set $X$ with $n$ elements, a paired subset is any subset $B\subset \mathcal P(X-A)$, which has $2^{n-k}$ elements. Hence the number of pairs of disjoint subsets of $X$, taking the order into account, is:
$$\sum_{k=0}^n\binom nk 2^{n-k}=\sum_{k=0}^n\binom nk 2^k=3^n.$$
If you do not take the order into account, as each pair is obtained twice, this number becomes $\;\dfrac{3^n}2$.


Como passar o classe (Teste2 teste2) como referencia no ("super") construtor do C++?

Question: Com base nessa resposta Em C++ qual o comando correspondente a super() do Java?
Class Teste2{
int x;
int y;
public:
  Teste2(int x, int y){
.
.
.
}
}
class Testando{
 Teste2 *teste2;
public:
   Testando(Teste *teste2)
{.
 .
 .
 .
class Teste : public Testando {
    string nome;
    int numero;
    public:
         //Supondo que Teste2 teste2 foi instanciado na Classe Testando
        Teste(Teste2 *teste2, string nome, int numero) : Testando(teste2) {
            this.nome = nome;
            this.numero = numero;

Como passar por referência uma classe no construtor ?
Comment: É difícil te ajudar porque apensar de você dizer que vai mudar, sempre coloca códigos tudo pela metade, sem contexto, sem organização, a gente fica perdido sem saber sequer o que o código deveria fazer e ter que ficar completando, arrumando, até o código compilar. Já leu isto? http://pt.stackoverflow.com/help/mcve O código deve ser compilável pelo menos na parte que não faz parte da dúvida. Jogar código de qualquer jeito dificulta qualquer ajuda.
Comment: Não entendi o que você quer, nem o objetivo, principalmente, mas não só, porque falta contexto.
Comment: @bigown na outra pergunta era uma `string`  agora uma classe ou tipo Test2, ficou claro ou não?
Comment: @bigown entendo, que esse código crie na hora aqui no site não tenho pronto, mas acredito que seja as bibliotecas que estão faltando. `#include`
Answer: O código tem diversos pequenos problemas, eu nem sei o que dizer para esclarecer a dúvida da pergunta porque não a entendi, nem sei se tem um dúvida específica mesmo. Havia um código jogado sem muito critério e que sequer dava pra testar. Note que eu não mudei nada para fazer funcionar o que foi perguntado, fui arrumando erros básicos de sintaxe e o que mais poderia ser uma dúvida é a mudança do operador . para o operador -> no this.
#include <string>
using namespace std;
class Teste2 {
    int x;
    int y;
    public:
        Teste2(int x, int y) {}
};
class Testando {
    Teste2 *teste2;
    public:
        Testando(Teste2 *teste2) {}
};
class Teste : public Testando {
    string nome;
    int numero;
    public:
         //Supondo que Teste2 teste2 foi instanciado na Classe Testando
        Teste(Teste2 *teste2, string nome, int numero) : Testando(teste2) {
            this->nome = nome;
            this->numero = numero;
        }
};
int main() {
    auto teste = Teste(new Teste2(1, 2), "joão", 1);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Pra falar a verdade acho que a maioria desses códigos não fazem sentido e não acredito que isto está ensinando alguma coisa realmente útil.
Comment: minha dúvida era nesse trecho do código `  Teste(Teste2 *teste2, string nome, int numero) : Testando(teste2) { ` o jeito que coloquei estava correto?
Comment: Sim, só não sei se realmente precisa isto, mas como eu digo código soltos sem contexto qualquer coisa que compila está certa.


Standard Deviation Given Only the Mean

Question: A company that manufactures large LCD screens knows that not all pixels on their screen light, even if they spend great care when making them. In a sheet 6 ft by 12 ft that will be cut into smaller screens, they find an average of 5.7 blank pixels. They believe that the occurrences of blank pixels are independent.
What is the Standard Deviation of blank pixels / square foot?
I can't figure out how to calculate SD when only given the mean. the mean is 0.079 blank pixels per square foot
Comment: Have you tried anything? Please show us your thoughts on the question.
Comment: I believe this question has insufficient information. If we knew how many pixels were in one square foot, or if we had any other way of figuring out that number, we would have enough information.
Comment: Together, the assumption "They believe that the occurrences of blank pixels are independent" and the commonsense assumption that the total number of pixels per square foot is much greater than the average number of blank pixels per square foot suggest that the distribution of the number of blank pixels per square foot is governed approximately by a Poisson distribution, which are specified by a single parameter (e.g., the mean). For such distributions, the variance is equal to the mean.
Comment: Travis's comment makes me think my first comment was too pessimistic. Mathematically, the variance of a binomial distribution is slightly smaller than the mean, but if the probability of individual failure is close enough to zero the mean and variance will be very close. One could assume $N$ pixels per square foot and see what comes out of that.
Comment: In the binomial distribution, if you know the number of trials and the mean then you can deduce the standard deviation. This is presumably a binomial distribution, but the number of trials isn't given.
Comment: @Travis That seems like an answer.
Comment: @DavidK I'll write a proper answer if OP indicates that that's likely what they're looking for. It's hard to tell without a little more context.
Answer: Without any other information, it is not possible to deduce the Standard deviation from the mean alone. Presumably someone at the company has access to the data used to calculate the mean. That very same dataset should help you calculate all the stats that you need.

Standard Deviation Given Only the Mean


$\lim_{n \to \infty} \int_1^a \frac{n}{1+x^n}dx$ solution with term-by-term integration of series

Question: Term-by-term integration was given as one of the solutions:
https://math.stackexchange.com/a/339717/851293
From the theory, the power series can be integrated term-by-term on an interval lying inside the interval of convergence, but how to prove this solution is allowed for this particular case since the function also depends on $n$?
Answer: it can be shown that:
$$\int_1^\infty\frac{1}{1+x^n}dx$$
converges for all $n>1$ so the integral part will converge. One nice way you could do it would be:
$$\frac{1}{1+x^n}<\frac 1{x^n}\,\,\,\,x\ge1$$
so:
$$\int_1^a\frac{n}{1+x^n}dx<\int_1^a\frac{n}{x^n}dx=\frac{(a^n-a)n}{a^n(n-1)}=a\frac{n}{n-1}\frac{a^{n-1}-1}{a^n}=\frac{n}{n-1}\frac{a^{n-1}-1}{a^{n-1}}=\frac{n}{n-1}\left(1-a^{1-n}\right)=L_n$$
which when we look at very large values of $n$ it is clear that:
$$\frac{n}{n-1}\to1$$
$$1-a^{1-n}\to1$$
also since the function is always positive and $a>1$ then the integral must also be positive, and so:
$$0\le I<1$$


Google map mileage function to return mileage between two addresses

Question: For each loop quit working.
public static function getMiles($to, $from)
{

    $from = urlencode($from);
    $to = urlencode($to);
    $data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$from&destinations=$to&key=MyKey");

    $time = 0;
    $distance = 0;

    /* return as an object for easier notation */
    $json=json_decode( $data, false );
    $origins = $json->origin_addresses;
    $destinations=$json->destination_addresses;

    /*  if there are multiple rows, use a loop and `$rows[$i]` etc */
    $elements=$json->rows[0]->elements;

    foreach( $elements as $i => $obj ){
    }
    //extract the mileage as meters
    $miles = $obj->distance->value;

    //converting the meters to miles
    $distance= round(($miles * '0.000621371192'), 1);
    //returning miles
    return $distance;

}

The end result is to return mileage between 2 addresses.
Error message is "'Invalid argument supplied for foreach()'".
Comment: that means that the `$elements=$json->rows[0]->elements` is not an array try to check what is inside it using `print_r()`
Comment: When I add the following:            /* return as an object for easier notation */
        $json=json_decode( $data, false );
        $origins = $json->origin_addresses;
        $destinations=$json->destination_addresses;
       echo "$destinations";
        die();  The result is "array".   when I use the print_r ($destinations);  I get a blank screen.
Answer: Your function works without problem on my end. I actually only get this "Invalid argument supplied for foreach()" error when I obfuscate my API key from the Distance Matrix API request.
Try running the code below with a valid API key (replacing "YOUR_KEY"):
function getMiles($to, $from)
{
    $from = urlencode($from);
    $to = urlencode($to);
    $data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$from&destinations=$to&key=YOUR_KEY");

    $time = 0;
    $distance = 0;

    /* return as an object for easier notation */
    $json=json_decode( $data, false );
    $origins = $json->origin_addresses;
    $destinations=$json->destination_addresses;
    /*  if there are multiple rows, use a loop and `$rows[$i]` etc */
    $elements=$json->rows[0]->elements;

    foreach( $elements as $i => $obj ){
    }
    //extract the mileage as meters
    $miles = $obj->distance->value;

    //converting the meters to miles
    $distance= round(($miles * '0.000621371192'), 1);
    //returning miles
    return $distance;
}

echo "\nMiles: " . getMiles("paris,france", "berlin,germany");

The output you get should be Miles: 659.
I recommend you go through these guides to double-check your key, project and billing account are all in good standing.
Hope this helps!
Comment: Thanks Evan, it was the billing account
Comment: Glad to hear you resolved the issue after re-enabling billing. :)
Answer: Well, it is my fault.  Upon further digging, I was able to determine that my credit card had expired.  Reset my expire date and code is working again.
Thanks for helping me Muhammad Omer Aslam for pointing me to get the right answer.


Drupal block-level form submit URL?

Question: I have a form:
function form_search_products($form, &$form_state) {
  $form = array();

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter keywords (ie: Fat free milk)'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add item to my shopping list'
  );

  return $form;
}

Simple and its loaded into a block region above product listings via:
function products_block_view($delta = '') {
 $block = array();

  switch ($delta) {
    case 'search_form':
    {
      $block['content'] = drupal_get_form('form_search_products');
      break;
    }
  }
  return $block;
}

I am trying to figure out how to map a submit handler now as there is no menu...
My current menu looks like this:
function products_menu() {
  $items = array();

  $items['products/mycity'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'Enjoy shopping in MyCity',

    'page callback' => 'html_list_products',
    'access arguments' => array('access products')
  );

  $items['products/autocomplete.json/%'] = array(
    'type' => MENU_CALLBACK,

    'page callback' => 'json_list_products',
    'page arguments' => array(2),
    'access arguments' => array('access products')
  );

  return $items;
}

What or how do I add to the menu_hook above so that I can process form submissions done through the above block code???
Alex
Answer: Form submissions aren't dependent on there being a path to view/submit the form at, all you need to do is one of the following:

Name the submit function as FORMNAME_submit() and Drupal will pick it up automatically
Add the handler manually in the form function itself, e.g.
$form['#submit'][] = 'my_submit_function';

Drupal block-level form submit URL?


Who would like to participate in developing and maintaing a Blog Overflow Community Blog for Magento StackExchange

Question: Given that our little corner of the "interwebs" was recently promoted to a full StackExchange network site, I thought we might commemorate the occasion by launching a community-drive Blog Overflow for Magento StackExchange.  If you're only recently discovering this SE feature you can quickly checkout the other current community driven blogs hosted on the SE platform and learn more about the original vision behind adding this feature to the core SE Experience in this blog post.  There's also a SE Chat dedicated to Community SE Blogs.
Technically, no new community driven blogs are going to be opened given the lackluster effort originally spent integrating them into the SE experience.
To this I say "Pish! Posh! And Likewise Phooey!" The #RealMagento community NEVER shies away from a challenge!
All kidding aside, we have a unique user base - we develop some of the most complex software deployed in the world on a daily basis powering nearly 1/4 of all e-commerce transactions. Our ranks are overflowing with some of the most innovative and hard-working people in ANY online community.  Not so sure?  Take a minute to check this out. And then compare it to the grandaddy of them all.  There's a tremendous amount of overlap for a SE community that just exited beta a few weeks ago.
I'm officially volunteering to start the effort off and will maintain whatever role you feel appropriate and will happily accept any and all offers of assistance in any capacity whatsoever.  But I'll commit to owning getting this effort off the ground and enlisting a core team of co-conspirators.
I have no doubt we can address the concerns raised not only for our own community blog but also assist the SE team on translating our soon-to-be success into a broader set of guidelines to drive the deeper integration of this feature across other SE communities.
So, the challenge, should you choose to accept it:

Vote on this question to show your endorsement / rejection of the core concept of a Community Magento SE Blog.
Next provide your input on the following items based on the original announcement post...

Raise the idea on the child meta. A community blog needs the involvement of community members.  These blogs don't exist to be the
  personal blog of a community member.  They are both for and run by the
  community.  It needs to be something the community collectively wants
  and will cultivate.
Define the scope and purpose of the blog. Is the blog about the
  site?  Is it about the site's topic? Is it about the industry
  the topic? Keep in mind the audience of your community and their
  around interests. Another generic blog about may not be all that.
  interesting.  A community blog should be interesting to both
  current members and potential new members.
Recruit contributors. Who will write entries for the blog? Starting
  a blog is a bit like going through the buffet line. Be
  realistic – don't let your eyes be bigger than your stomach. Think
  seriously about if and how often you will be able to contribute a blog
  post, including research/prep time.  The more contributors there are,
  the less frequently each contributor needs to post.  One post a month
  is a much easier to stomach than a couple posts every week.
Plan a schedule. Given the results of steps #2 and #3, think about
  a week, posted Mondays? Will there be posts on Tuesdays and posts on
  Fridays? You don't need to be pushing out posts daily, but you should
  post at least once a week.a rough idea of a schedule for the blog.
  Will there be one post

We need to engage GraceNote and share our discussion with the SE team to see if our initial efforts are worthy of a temporary lift of the new-blog embargo.
Comment: "Take a minute to check this out" and "compare it to the grandaddy of them all" both link to the Magento leaderboard. What exactly do you want us to compare? :)
Comment: Nice idea! Love the community aspect of the blog as it's easy for people to jump in and contribute without owning and setting up a seperate blog. Hope we'll find some people interested to join :)
Comment: Thanks for catching that Fabian - was supposed to link to StackOverflow's leaderboard.
Answer: I'd like to point you to a similar thread on meta.Worldbuilding - specifically, my response:

If per-site blogs are ever coming back, it won't be for a long time. We love the enthusiasm, and we still think new ongoing blogs would be super cool, but site blogs are just not anywhere near the front of the line for resources right now. It'll be 6-8 something... but it definitely isn't "weeks".
I've suggested Medium publications as a solution to this problem before on other sites because I personally think they are a good fit and I'd love to see a community take them for a test drive. A Medium publication wouldn't be in the SE ecosystem, but then again, Blog Overflow barely is anyway. But publications work pretty well as a conceptual replacement: anyone can write a post, and a publication editor can invite them to contribute it to the "collection".

This isn't an Official Recommendation. It's just my personal opinion that Medium publications are an excellent replacement for what per-site blogs were intended to be (and which they rarely actually succeed at becoming).
Even if Blog Overflow were an option (which it isn't), there are almost no benefits to using it. It doesn't sync with the site in any way, so there's no consistency across user names or profiles, and it's a black box of terrible Wordpress-ness that communities have no control over, and it's the redheaded stepchild of SE development so there'd be few enhancements (or probably even software patches, let's be real)...
...whereas the Medium publication solution is lightweight, administered by you (the community), actively worked on by a dedicated dev team, and part of a larger ecosystem that will help drive traffic (if that's the goal).
All other steps in the process you outlined still apply - you can just axe step 3. Like I said to the Worldbuilding folks:

You could set this up today if you felt like it. If you want the SE name on it, just make sure it's credited to "the [Magento] Stack Exchange community" - I think that's the verbiage we ask for to specify that it's community-owned and keep it from looking like it's run by SE Inc.

I'd love to see other blog-minded communities take something like this for a test drive.
Comment: Thanks for the candor and genuine support of the idea.  And thanks for the medium suggestion.  That's actually a great idea and probably better for #realmagento and medium.  Is there any way that we might be able to hook into any level of SE functionality / integration?  I lea is there anything even available?  I ask because one benefit of SE is the cohesion and sense of joint ownership of values and the duty to support & nurture the community.  If I can convince enough people to participate it would be great we could at least get beta access to some functionality and try and hack something up
Comment: I think that it might be a really interesting way to leverage a great blog platform, a bunch of really talented and motivated OSS developers and the existing community and value of the SE ecosystem.  Have no idea if there has been any discussions even of something like this internally but the more i think about the idea of figuring out a way of extending SE at any level deeper and offering some way for the community to create something new but still integrally part of SE the more I get excited about it.


Hibernate Discord bot discord.js

Question: I'm trying to make a hibernate mode, where the bot doesen't do anything, but it stays online. I wrote some stuff below
    let configstuffs = JSON.parse(fs.readFileSync('config.json')) //figuring out if hibernate mode is on
    if (configstuffs.hibernate === true) {
    client.user.setPresence({ status: 'idle' })
    client.user.setActivity('Bot is hibernating')
    console.log('hibernating')
    return
    } else {
        client.user.setPresence({ status: 'online' })
        client.user.setActivity('')
        console.log('no longer hibernating')
    }

I put this outside of my message listener, inside my bot.once('ready', () => {} but it says something like 'cannot read property 'setPresence' of null.'
My goal is to make it so that when hibernate mode is active, the bot becomes idle, and sets its game as 'Hibernating' or something similar, then ignores all messages, or bypassing the message listener. Anyone got any ideas?
Answer: I had a hibernate option in my bot and this is what I did
let isHibernating = false; //Global (top level) variable
const Hibernate = (client) => {
    if(!client){ return(false) }
    client.user.setPresence({ //Sets detailed presence
        activity: {
            name: "Hibernating",
            type: "PLAYING"
        },
        status: "idle",
        afk: true
    });
    isHibernating = true;
}

And in your on-message handler
client.on("message", message => {
    if(isHibernating){ return(false) } //Bot is Hibernating
    // other things
    if(message.content === "hibernate" && message.author.id == "Bot owner ID"){
        Hibernate(client);
    }
});

Hibernate Discord bot discord.js


The tangent space of $\mathrm{Aut}(T_eG)$

Question: Let $G$ be a Lie group and $e \in G$ be the identity. I want to understand the following sentence.

"$\operatorname{Aut}(T_eG)$ being just an open subset of the vector space of endomorphisms of $T_eG$, its tangent space at the identity is naturally identified with $\operatorname{End}(T_eG)$."

I don't understand

why $\operatorname{Aut}(T_eG)$ is an open subset.
how to naturally identify $T_e(\operatorname{Aut}(T_eG))$ with $\operatorname{End}(T_e G)$.

I think I am lacking basic knowledge about tangent spaces.
I appreciate any help.
Answer: If $G$ is a manifold of dimension $n$, then $T_eG$ is just a $n$-dimensional real vector space, so that after choosing a basis of $T_eG$, we can make an identification $T_eG\cong \mathbb{R}^n$. The endomorphisms of $\mathbb{R}^n$ (i.e., the linear maps from $\mathbb{R}^n$ to itself) can be identified with the $n\times n$ matrices, and hence so can the endomorphisms of $T_eG$. The automorphisms of $\mathbb{R}^n$ are the invertible, a.k.a. "non-singular" matrices. The space of $n\times n$ matrices has its own topology, and in this topology, the invertible matrices form an open set; that is covered in this older answer of mine.
As to your second question, for any real vector space $V$ of finite dimension $n$, and any $v\in V$, there is a natural identification of $T_vV$ with $V$ (this is Prop 3.8 in Lee's Introduction to Smooth Manifolds, 1st ed.). That gives us an identification
$$T_\text{id}(\operatorname{End}(T_eG))\cong \operatorname{End}(T_eG)$$
where $\text{id}\in\operatorname{End}(T_eG)$ is the identity map from $T_eG$ to itself (I assume this is what you intended in your problem statement). Additionally, for any manifold $M$, any open set $U\subseteq M$, and any $p\in U$, there is a natural identification of $T_pU$ with $T_pM$ (this is Prop 3.7, ibid.). Thus, we have a sequence of identifications
$$T_\text{id}(\operatorname{Aut}(T_eG))\cong T_\text{id}(\operatorname{End}(T_eG))\cong \operatorname{End}(T_eG).$$
Comment: [I am a link $2^2$?](http://math.stackexchange.com/q/65988/264)
Comment: possible duplicate of [Is the set of all strings with countably infinite length bijective to $\lbrack 0,1\rbrack$](http://math.stackexchange.com/q/65988/264)
Answer: Let me just expand on Zev's answer.
Any finite dimensional vector space $V$ has a unique linear topology. This essential comes from identifying $V$ with $\mathbb{R}^{\dim V}$. Although such an identification is not unique, it turns out that the topology on $V$ that comes from such identifications is. Moreover, the determinant map $\det:\operatorname{End} V\rightarrow\mathbb{R}$ is continuous in this topology. Indeed, under an identification of $V$ with $\mathbb{R}^{\dim V}$, the determinant map becomes a polynomial. Since a linear map is invertible if and only if it has a non-zero determinant, we have $\operatorname{Aut}V=\det^{-1}(\mathbb{R}\setminus\{0\})$. Since $\mathbb{R}\setminus\{0\}$ is open, and $\det$ is continuous, we conclude that $\operatorname{Aut}V\subseteq\operatorname{End}V$ is open. We obtain an answer to your first question by letting $V=T_eG$.
Now, if $U\subseteq V$ is open, for every $p\in U$ we have a natural identification of $T_pU$ with V. Namely, every vector $X\in T_pU$ is defined by a curve $\gamma:\mathbb{R}\rightarrow U$ such that $\gamma(0)=p$. Indeed, we define the action of $X$ on $f\in C^\infty(U)$ by $Xf:=(f\circ\gamma)'(0)$. However, $\gamma$, being a function between two vector spaces, has a derivative. In this particular case, this dervative is of the form $$\lim_{t\rightarrow 0}\frac{\gamma(t)-p}{t}=\tilde{X}.$$ We can then associate the vector $X$ to the vector $\tilde{X}$, showing there is a natural identification between $T_pU$ and $V$. We obtain an answer to your second question by letting $V$ be $\operatorname{End}(T_eG)$ and $U$ be $\operatorname{Aut} T_eG$.


What musical activities can locked down musicians do via video-conferencing?

Question: The UK Brass Band I play with has already hosted one on-line meeting for our locked down brass players (via Zoom).
It was immediately apparent that timing latency makes it impossible for us all to perform together as though we were all in the same room. So we can't play pieces together.
But we can do exercises. If we were all in the same room, this is the sort of thing we might do:

breathing exercises
scales and intervals
lip slurs
copying back a played phrase
watching the conductor
improvising over a held chord
listening for intonation
fingering patterns
stylistic techniques, e.g. how to swing
etc.

When I physically stand in front of an ensemble my ears tell me which players are OK with what they've been asked to do, and who might need extra explanation/encouragement. But in video conferencing, the sound is mono, so everyone's sound comes from one point in space. It's much harder to know who needs the explanation/encouragement. So mono sound is another limitation of video conferencing.
My question is - what useful exercises can a group of musicians in lockdown do that still work despite timing latency and mono soundfield?
Comment: There was a brass band on national news this morning. It's on BBC I-player, maybe ask how they did it.
Comment: @Tim Which band was that?
Comment: Sorry, can't remember - or find out!
Comment: Cory Band, the finest brass band in the world.
Comment: Hope that was of some interest to you! For the future, if you ever get the band recorded, it would be fun to issue each member/section with 'music minus one' - the recordings without their part. I've just done similar for a vocalist so he can sing along to the rest of the tracks because his voice I've taken off.
Comment: It doesn't seem to be a problem for them: https://youtu.be/wo-44qmk2JY
Comment: We've made our own video. Each of our seven brass bands did a lockdown video, and this show combines them all: https://www.facebook.com/WantageSilverBand/videos/551503742209495/
Comment: related question: [How to play together online?](https://music.stackexchange.com/questions/10576/how-to-play-together-online)
Answer: As a preface, my experience playing duets via Zoom is that in addition to the latency, Zoom doesn't handle the simultaneous sounds well -- I can hear myself or my partner, but not both.
That said, a few experiments you could try:

IF the latency between each instrumentalist and the conductor is close enough to the same, the conductor can conduct as usual, and to each player, it will seem they are in time. The burden falls to the conductor to stay consistently ahead of the beat (and therefore out of sync with the heard performance). It might be necessary for each performer to turn off their own speakers.

Try arranging or creating some music that incorporates phasing, and therefore might even benefit from the latency. This would be highly non-traditional as far as brass band repertoire, but could be a fun, experimental way to incorporate the kinds of exercises you describe above. For example, take a look/listen to "In C" by Terry Riley

or any of Steve Reich's "phasing" pieces, such as

)
The pieces I mention depend on rhythmic exactness, so you wouldn't be able to play them as intended, but the latency problem might allow you to catch the spirit of them in interesting ways.

Have one musician improvise a short musical segment or phrase and have each band member in succession pick up the idea and continue or develop it in some way. Latency would probably create awkward rhythmic breaks between each musician, but since the primary exercise is one of listening and being musically creative, the breaks between phrases might be not only tolerable, but necessary.

Picking up on that idea, you could try a game of "operator". Only two musicians communicate at a time, with everyone else turning off their speakers. Musician #1 plays a musical idea — maybe from a piece you're rehearsing, maybe improvised — to Musician #2. Musician #1 turns speakers off and Musician #3 turns them on. And so forth until you come back to Musician #1 to see if the phrase has maintained correct notes, rhythm, tempo, dynamics, etc. No cheating by watching to see what fingering is being used.

A "Watching the conductor" exercise / game: The conductor conducts and everyone else tries to guess which piece (or section thereof) is being conducted. Good practice for both conductor and band!
Answer: Just seen that question, so I am years late to the game.  It still makes sense to put an answer here because, well, the pandemic is not over to the degree where it will not significantly affect attendance, and even after that there are reasons for remote practice.
We've practised throughout the hard lockdown in our country (about half a year) using Jamulus, free software with a long history (at one point of time, it used to be called llcon instead).  It uses a centralised server architecture focused around UDP packaging of Opus-encoded data (these days, WebRTC might make more sense), where the server is responsible for creating the individual mixes (everyone has their own mixer for managing the sources) and sending them out again.
Since it is audio-only, integrating a conductor requires some imagination.  The central server should be in "network vicinity" to the clients (which can mean that it may be better situated near a network interconnection point 100km away than in the same town as the participants) and have sufficient power for handling all the clients.  If you don't want to depend on a public server, renting an on-demand server of sufficient power and connectivity will make sense because they tend to have better connectivity than a private user.
Running the server is what requires technical savvy (Linux offers itself), setting up the clients (Windows, Linux, MacOSX, by now also iOS and Android) is somewhat straightforward, but low-latency setups (avoiding WiFi, preferring soundcards that can reach low latency, typically ruling out bidirectional USB microphones that would otherwise be perfect) do warrant some experience.  Note that a traveling expert can provide help here in one-on-one scenarios that are less problematic than group settings regarding pandemic safety measures.
For fast pieces and mixed user latencies it may be helpful if someone will inject a fixed rhythm from an arranger keyboard or a similar "deaf drummer" contraption: that helps avoid "creeping slowdown".  Headphones are mandatory since echo compensation is not done for speed/efficiency reasons.
The individual tracks can be recorded on the server and a mix generated and distributed from it afterwards: voice separation is much better than can be achieved in a live setting which may make this a helpful tool outside of pandemic reasons.
For getting your feet wet, it can be easiest to start installing a client, then connecting to some public jam session on a public server.  Be sure to have read up on stuff well enough not to disrupt the session if you can avoid it.  Developers and users tend to be friendly, however.
A different software would be "Sonobus" which has a peer-to-peer architecture and consequently has increasing network and performance requirements for every client as the number of users grows: for Jamulus only the server needs to scale up to the number of users regarding network and processing power.
Some people claim to get along better with JamKazam particularly regarding the complexity of the setup, however it requires working with a central server that has a fee scheme for membership.
All of those solutions are audio-only.  For some public Jamulus sessions it is not uncommon to have a Jitsi session for video only in parallel, but in my experience it affects the audio network performance too much to be really desirable.
Answer: The bandmaster could play (alone or with a small ensemble) a piece in his style and make a video that shows him conducting and giving the accents, fermatas etc. Each member can play at home his part to the video just when he wants to practice.


MySql determine all elements of string list exists in other string list

Question: I have these tables:
category_table
+--------+-----------------+---------+
| id     | title         | parent_id |
+--------+---------------+-----------+
| 1      | f             | null      |
| 2      | h             | null      |
| 3      | j             | 1         |
| 4      | y             | 3         |
| 5      | d             | 3         |
+--------+-----------------+---------+

post_table
+--------+---------------+-------------+
| id     | title         | categoryies |
+--------+---------------+-------------+
| 1      | title1        | 1           |
| 2      | title2        | 1,2         |
| 3      | title3        | 4,5         |
| 4      | title4        | 4           |
| 5      | title5        | 3           |
+--------+---------------+-------------+

and a procedure that find all posts that has '3,5,2' categories.
how procedure will search string list in other string list similar to:
Create Procedure post_select(IN category_ids Varchar(200))
Begin
   Select *
   From post
   Where
   // all category_ids exists in post categories column
   // such as FIND_IN_SET('1', '1,2,3') but first parameter
   // should be list string for example:
   // FIND_IN_SET('2,3,4','2,4,5,6,7,8')

End;

Comment: Stop. See normalisation.
Comment: @Gunaseelan Who cares? Until the schema is fixed, there's no point 'trying' anything!
Comment: This question needs some clarification (and some typo fixing too). Do you want the procedure to receive a parameter with a comma-separated string that's interpreted as a list of values, of which any will make the row appear in the result? Also it's helpful to demonstrate the desired result, to cross-check if we understand it right.
Answer: You should consider creating a post_category table where you store the post_id together with the category_id.
Comment: I need comma separated search but don't have any function for searching list in other list ...
Comment: @SLDev If you need that, don't bother using an RDBMS.
Comment: @SLDev The point is simple. Either normalise your schema, or don't use a relational database management system; there's nothing wrong with using comma separated lists, and there's nothing wrong with using relational databases; just don't try to use both together.


Calling setState in componentDidUpdate for animations based on refs

Question: Hi Stackoverflow community,
I'm doing some custom animations in my React app involving updating margins on a component with position: absolute. It's a menu that can toggle in and out.
I have a ref for the element it's toggling behind, whose node height I'm grabbing in componentDidMount. I use this height to know how far to move my toggling component.
I noticed when my app renders the first time my component isn't animating right because the height value is always zero. When I toggle it subsequently it works because the componentDidMount fires and updates the height of the other node properly.
To fix this I moved my divHeight field into the state and started calling setState in componentDidMount, now my toggleable component renders correctly each time.
Is this an anti-pattern? I can't see how else I would update my UI based on physical attributes of the HTML nodes, since those are only available through refs in componentDidMount...
Answer: There is another method to perform physical changes in html elements instead of using refs. Instead you can toggle classes on and off elements to do what you want, like toggling a menu in and out of frame.
Below is an example of how its done without the use of refs. Click the button and you can imagine the red div is your top navigation menu.

class MenuExample extends React.Component {
  constructor(props) {
    super(props);
    this.onToggleMenu = this.onToggleMenu.bind(this);
    this.state = { menuToggle: false };
  }

  onToggleMenu(e) {
    this.setState({ menuToggle: !this.state.menuToggle });
  }

  render() {
    return (

        <button onClick={this.onToggleMenu}>Open menu</button>
        <div className={`menu ${this.state.menuToggle && 'active'}`} />

    );
  }
}

// Render it
ReactDOM.render(
  <MenuExample/>,
  document.getElementById("react")
);
button {
  position: absolute;
  top: 150px;
}

.menu {
  position: absolute;
  top: -100px;
  left: 0px;
  width: 100%;
  height: 100px;
  background-color: red;
  transition: all .3s ease-in;
  -webkit-transition: all .3s ease-in;
}

.menu.active {
 top: 0px;
}

Comment: Thanks for the quick response! The issue with this is that my elements don't have fixed heights - so I wouldn't be able to do something like ```top: -100px```, so I need to get their heights after they've rendered.
Comment: Hmmm. If the height of the item varies, then i can only suggest you put a min and max-height on the item, then `top: - max-height` guarantees the item will be hidden while allowing for some variable height


Solving $\sin x = x^3-2x^2+1$ using Newton's Method

Question: Given $2$ equations:
$$\text{1) }\ y= \sin (x),\ \ \ \text{2) }\  y= x^3-2x^2+1.$$
I was told to look a graph online, and then solve using newton's method. After looking it up, I realized that there are $3$ separate intervals in which you had to solve on.
I set $\sin (x)$=$3x^2-2x^2+1$. Then I moved $\sin(x)$ over, getting $x^3-2x^2+1-\sin(x)=0$, with the interval $[0,1]$.
Then, I set up, and used Newton's equation.
$$x_{n+1}=x_n-{x_n^3-2x_n^2+1-\sin(x_n)\over 3x_n^2-4x_n-\cos(x_n)}.$$
After making a common denominator and simplifying more, I got:
$$x_{n+1}= {2x_n^3-2x_n^2-\cos(x_n^2)+\sin(x_n)-1\over 3x_n^2-4x_n-\cos(x_n)}.$$
After doing Newton's method on my calculator, the values keep jumping around. I started with $x_1=1$. The real answer is about $.568$. When using newtons method, for $x_2$, I got $.294$... and $x_3 \sim .935$ and $x_4 \sim .3514$...
The numbers keep jumping around. I'm confused what I did wrong. Did I do the wrong range, or am I plugging it into my calculator wrong, or is my equations wrong?
Comment: If you implement it s Moo said above then it works perfectly fine: if $0 \lesssim x_0 \lesssim 1$ then it will converge to the zero at $\simeq 0.568$. For larger $x_0$ it will converge to $\simeq 1.979$ which is a second root. For $x_0 \lesssim 0$ it will converge to the third root $\simeq -0.782$.
Comment: I know the formatting isn't that good, but can anyone still try explaining to me why I can't find the correct answer; .568.
Comment: @AaronM What?!  Um, you can't just change things around willy nilly and expect them that it "doesn't really matter mathematically..." because it does.
Comment: $x_ {n + 1}=
 x_n - \dfrac {x_n^3 - 2 x_n^2 - \sin (x_n) + 1} {3 x_n^2 -
     4 x_n - \cos (x_n)} $, choose $x_0 = 0.5$,  the result is $x^{*} = 0.5680257385175188$.
Comment: In the future, note that \cos and \sin render much better and rather than using x_(n+1), you should use x_{n+1}.  In general, "{$\dots$}" group stuff so you can do whatever it is you want to do to it as a grouped object.
Comment: @Moo Yeah... it seems to me he didn't mean to say $3x^2$ but meant $x^3$.  But yeah, also the +1 should be at the end.
Comment: @Moo in the denominator, I wrote $3x_n^2$, why did you write $9x_n^2$, plus I don't think I made mistakes with the +1, it doesn't really matter mathematically...
Comment: OMFG, I think I wrote the problem wrong. Thanks a lot guys!
Comment: Yeah, I'm sorry to bother you guys again, but @Moo I think I wrote the problem wrong, could you please comment what you would get with the updated equations
Answer: I did not not understand why, starting with $x_0=1$, you have problem $$f(x)=x^3-2 x^2+1-\sin (x)$$ $$f'(x)=3 x^2-4 x-\cos (x)$$ $$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}=\frac{2 x_n^3-2 x_n^2+\sin (x_n)-x_n \cos (x_n)-1}{3 x_n^2-4 x_n-\cos (x_n)}$$ So, the iterates are
$$\left(
\begin{array}{cc}
 n & x_n \\
 0 & 1 \\
 1 & 0.5798249292 \\
 2 & 0.5765888390 \\
 3 & 0.5765861544
\end{array}
\right)$$
In fact, your first formula is totally correct but "after making a common denominator and simplifying more", there is a "small" mistake : $x_n \cos(x_n)$ is not $\cos(x_n^2)$.
Comment: @AaronM: What Claude is saying is that Newton's method **may fail even if there is a root**. You must not ignore the required conditions if you want it to converge. If you do not start close enough to the root, it is possible that it oscillates, such as for $( x \mapsto \frac{x}{3+x^2} )$ starting at $1$. Also, if the function is not differentiable at the root, such as $( x \mapsto x^{1/3} )$, then it may be that it will always diverge no matter how close you start to the root!
Comment: Thanks so much! I'd never find that mistake even if I did the problem hundreds of times.
Comment: @AaronM. You are very welcome. May I confess that I did not see it at first galnce ?
Comment: @ClaudeLeibovici Nah, I didn't see it either.  Totally glanced over once I saw the first equation was right.
Comment: Yeah, it really bothered me because the roots kept bouncing, and I knew they should be converging to .568. Thanks again.
Comment: @AaronM. They could have been bouncing ! Take care that the method works under a certain number of conditions.
Comment: @ClaudeLeibovici I know they could have been bouncing, but I graphed the equation before doing the problem algebraically, so I knew the answer; I just needed to do it using Newton's Method.
Comment: Ok, I see what you mean. I'll keep that in mind.
Answer: $\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

We can see that $\ds{\mrm{f}\pars{x} \equiv \sin\pars{x} - x^{3} + 2x^{2} - 1}$ has a change of sign in $\ds{\bracks{0,1}}$. We can set the starting point as $\ds{x_{0} = {0.0 + 1.0 \over 2.0} = 0.5}$ with
  $$
x_{n + 1} =
x_{n} - {\sin\pars{x_{n}} - x_{n}^{2}\pars{x_{n} - 2} - 1 \over
\cos\pars{x_{n}} -x_{n}\pars{3x_{n} - 4}}\,,\qquad n \geq 0
$$

The $\texttt{javascript}$ code at the end $\pars{~\texttt{nr0.js}~}$ makes the job. You can run it in the console $\pars{~\mbox{'as an script'}~}$ with $\texttt{node}$, from https://nodejs.org/en/:
$\texttt{> node nr0.js}$
The result is given by

0.5, f(0.5) = -0.145574461395797
0.5684224734698207, f(0.5684224734698207) = 0.0008518369364767242
0.5680257404259389, f(0.5680257404259389) = 4.097584049844727e-9
0.5680257385175188, f(0.5680257385175188) = 0
0.5680257385175188, f(0.5680257385175188) = 0

// nr0.js
"use strict";
var n = 0;
var s = "";
var x = 0.5;

function f(x)
{
 return Math.sin(x) - x*x*(x - 2.0) - 1.0;
}

function next(x)
{
 return x - f(x)/(Math.cos(x) - x*(3.0*x - 4.0));
}

do {
    s += x + ", f(" + x + ") = " + f(x) + "\n";
    x = next(x);
} while (++n < 4);

s += x + ", f(" + x + ") = " + f(x) + "\n";
console.log(s);


Comparing javascripts native "for loop" to prototype's each()

Question: So I was having a debate with a fellow engineer about looping in JavaScript. The issue was about the native for loop construct and prototype's each() method. Now I know there are lots of docs/blogs about for and for-each, but this debate is somewhat different and I would like to hear what some of you think.
Let's take the following loop for example
example 1
var someArray = [blah, blah, blah,...,N];
var length = someArray.length;

for(var index = 0; index < length; index++){
    var value = someFunction(someArray[index]);
    var someOtherValue = someComplicatedFunction(value, someArray[index]);
    //do something interesting...
}

To me, this comes second nature mainly because I learnt how to code in C and it has carried me through. Now, I use the For-each in both C# and Java (bear with me, I know we are talking about JavaScript here..) but whenever i hear for loops, i think of this guy first. Now lets look at the same example written using Prototype's each()
example 2
var someArray = [blah, blah, blah,…..,N];
someArray.each(function(object){
    var value = someFunction(object);
    var someOtherValue = someComplicatedFunction(value, object);
    //do something interesting...
});

In this example, right off the bat, we can see that the construct has less code, however, i think each time we loop through an object, we have to create a new function to deal with the operation in question. Thus this would preform badly with collections with large number of objects. So my buddy's argument was that  example 2 is much easier to understand and is actually cleaner than example 1 due to its functional approach. My argument is that any programmer should be able to understand example 1 since it is taught in programming 101. So the easier argument doesn't apply and example 1 performs better than example 2. Then why bother with #2. Now after reading around i found out that when the array size is small the overhead for example 2 is minuscule. However people kept on talking about the lines of code you write is less and that example 1 is error prone. I still don't buy those reasons, so I wanted to know what you guys think…
Comment: I think the `each` in Prototype works the same as that in jQuery which means that the passed function is applied n-times, once for each item in the collection
Comment: for array iteration, it dosen't creat a new function, check the source. http://prototypejs.org/assets/2010/5/13/prototype.js
Comment: does it really create a new function for every item in the collection? it could simply store the function and call it n-times
Comment: i think it does, let me change that statement to say "i think it creates a new function" since i am not sure... :-)
Comment: I'm fairly sure the code above does create a new function for each item in the collection. You could define the function before and do `someArray.each(functionName);` which shouldn't.
Comment: @licideer, it does NOT create a new function for each item in the collection. Functions in JS are passed by reference.
Answer: You are not creating a new function on each iteration in the second example. There is only one function that keeps getting called over and over. To clarify the point of only a single function being used, consider how would you implement the each method yourselves.
Array.prototype.each = function(fn) {
    for(var i = 0; i < this.length; i++) {
        // if "this" should refer to the current object, then
        // use call or apply on the fn object
        fn(this[i]);
    }
}

// prints each value (no new function is being created anywhere)
[1, 2, 3].each(function(v) { console.log(v); });

Sure, there is the overhead of calling a function in the first place, but unless you are dealing with massive collections, this is a non-issue in modern browsers.
Personally I prefer the second approach for the simple reason that it frees me from worrying about unnecessary details that I shouldn't be concerned about in the first place. Say if we are looping through a collection of employee objects, then index is just an implementation detail and in most cases, if not all, can be abstracted away from the programmer by constructs such as the each method in Prototype, which by the way is now a standard in JavaScript as it has been incorporated into ECMAScript 5th ed under the name forEach.
var people = [ .. ];
for(var i /* 1 */ = 0; i /* 2 */ < people.length; i++ /* 3 */) {
    people[i /* 4 */].updateRecords();
    people[i /* 5 */].increaseSalary();
}

Marked all 5 occurrences all i inline with comments. We could have so easily eliminated the index i altogether.
people.forEach(function(person) {
    person.updateRecords();
    person.increaseSalary();
});

For me the benefit is not in lesser lines of code, but removing needless details from code. This is the same reason why most programmers jumped on the iterator in Java when it was available, and later on the enhanced for loop when it came out. The argument that the same grounds don't hold for JavaScript just doesn't apply.
Answer: I'm fairly certain it does not create a new code function for every iteration, but rather calls the function on each one.  It may involve a little more overhead to keep track of the iterator internally, (some languages allow the list to be changed, some don't) but it shouldn't be all that very much different internally than the procedural version.
But anytime you ask which is faster, you should ask, does it really matter?  Have you put a code profiler on it and tested it with real world data?  You can spend a lot of time figuring out which is faster, but if it only accounts for .0001% of your execution time, who cares? Use profiling tools to find the bottlenecks that really matter, and use whichever iteration method you and your team agree is easier to use and read.
Comment: You are right i wasn't really looking for performance reasons. It was just an educational debate...
Answer: Example one is not only error prone, for arrays of trivial length it's a poor choice - and the each (or forEach, as defined in JavaScript 1.6, yet IE8 still does not support it) is definitely style-wise the better choice.
The reason for this is simple: you are telling the code what to do, not how to do it. In my tests with firefox, the forEach method is about 30% the speed as a for loop. But when you're doing miniscule arrays it doesn't even matter that much. Much better to make your code cleaner and easier to understand (remember: what it's doing instead of how to do it), for not only your sanity the next time you come back to it, but for the sanity of anyone else looking at your code.
If the only reason you're including prototype is for the .each method, you're doing it wrong. If all you want is a clean iteration method, use the .forEach method - but remember to define your own. This is from the MDC page on forEach - a useful check to give yourself a .forEach method if none exists:
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

You can tell from how this works, that a new function is not created for each item, though it is invoked for each item.
Comment: I see where you are coming from but it is interesting that arrays of trivial length provides poor performance. Did you perform some profiling to come to this conclusion?
Comment: I used JSLint to benchmark. No matter the length of the array, performance of .each is about 30% of the performance of the loop. This, of course, is simply the overhead of the loop - all I was doing was incrementing a counter within the loop. The overhead of what you actually do within the loop is likely to be a much more apparent bottleneck in performance. If you iterate over extremely large collections, think about using setTimeout to iterate - it will perform even worse, but it will not lock up the browser as it iterates. (prevents "unresponsive script" errors due to how setTimeout works)
Answer: The answer is - its subjective.
For me, example 2 is not really THAT much less code, and also involves downloading (bandwidth) AND parsing/executing (execution-time) a ~30kb library before you can even use it - so not only is the method itself less efficient in and of itself, it also involves setup overhead. For me - arguing that example 2 is better is insanity - however that's just an opinion, many would (and are perfectly entitled to) disagree completely.
Comment: as @warfangle mentioned, if the only desired functionality is the `Array.each` method, then just use that. There's no need to fetch the entire library for one function.
Answer: IMO the second approach is succinct and easier to use, though it gets complicated (see prototype doc) if you want to use things like break or continue. See the each documentation.
So if you are using simple iteration, use of the each() function is better IMO as it could be more succinct and easy to understand, although its less performant than the raw for loop


How to execute/run puppet class

Question: I am new to puppet. I want to know how to execute/run a simple puppet class. Below is the class I am trying to execute using
puppet apply classExample.pp

classExample.pp is the file in which class is written.
This code just compiles the class and nothing happens.
How to execute this class?
 # A class with no parameters
class exampleClass {

 #create a directory
  file {"create directory":
    path => '/root/rahil/puppet/puppetDemo/tmp',
    ensure => "directory",
  }

}

Answer: What you did is defining a class.
But you also need to declare it.
For the sake of the example, it could look like this:
# A class with no parameters
class example_class {

  #create a directory
  file {"create directory":
    path => '/root/rahil/puppet/puppetDemo/tmp',
    ensure => "directory",
  }

}

class { 'example_class': }

Please note that I changed the name to example_class as upper case letters should not be used in class names.
And also note that usually you don't define and declare classes in the same file.
How that is done is a bigger topic, see Modules fundamentals Documentation for a start.
Comment: Most documentation uses `class { '...': }` for declaration these days, but I personally prefer `include ` whenever possible. See the [discussion](https://docs.puppetlabs.com/puppet/latest/reference/lang_classes.html#include-like-vs-resource-like) in the documentation.
Comment: The link for https://docs.puppetlabs.com/puppet/latest/reference/modules_fundamentals.html is now broken. Do you have an up to date one?

How to execute/run puppet class


Removing MouseListener() from a JLabel

Question: I added a MouseListener to a JLabel. Now if I want to disable this MouseListener associated with the JLabel, when the label is clicked once, how can I do it.
I know there is a big way to set a boolean or int variable when the label is clicked and then call a method and remove MouseListener there, but I want to learn a compact and easy way. Is there a way to do this?
Answer: In your mouse listener:
public void mouseClicked(MouseEvent event) {
    // Do stuff...
    ((Component) event.getSource()).removeMouseListener(this);
}

Comment: That's about as simple as it will get.
Answer: What's wrong with label.removeMouseListener(listener)? It works just fine. If you want to create listener that removes itself call label.removeMouseListener(this)

Removing MouseListener() from a JLabel


Finding the derivative of a function using its series expansion

Question: I recently came across a proof which stated that the derivative of $\sin{x}$ is $\cos{x}$ because if we differentiate the Maclaurin series expansion of $\sin x$, we get the series expansion of $\cos x$. Is this a valid proof? My doubt is that the Maclaurin series expansion itself is defined based on the derivative of the function.
The following expansion is the Maclaurin series where $a=0$ and $f^{(n)}$ denotes the $n^{th}$ derivative of the function.
$$\sum_{n=0} ^ {\infty} \frac {f^{(n)}(a)}{n!} \, (x-a)^{n} $$
We can clearly see that we need the derivative in the first place before we can get the expansion. Is the proof valid?
Comment: So how do we find the McLaurin series of $sinx$ in the first place?
Comment: That is exactly my question @imranfat
Comment: The question goes much deeper then you think. Conventionally, the MacLaurin series is set of based on multiple derivatives and traditionally that is how we establish Series of a host of transcendental functions. Alternatively, one can define the MacLaurin series for the sine and work backwards to establish its properties and so forth...This is less intuitive, but it can be done
Comment: @imranfat Could you explain a little more?
Comment: Have you taken a course on Complex analysis?
Comment: @imranfat No, I haven't done so.
Comment: Don't know where you currently are in math, but that course would be a good one to take....
Answer: You can do this:
Define
$e^x = \sum_\limits{n\to 0}^{\infty} \frac {x^n}{n!}$
and
$e^{ix} = \cos x + i\sin x$
And then it will fall out that
$\sin x = \sum_\limits{n\to 0}^{\infty} \frac {x^{2n+1}}{(2n+1)!}$
and from here you can indeed show that $\frac {d}{dx} \sin x = \cos x$
However, using this approach we have not shown that this function has any of the properties we expect $\sin x$ to have, and that will have to be verified.
Comment: might be worth noting why one can differentiate termwise or that doing so is not always ok. +1 regardless


Is this site getting a custom layout?

Question: This is the first time I've participated in a StackExchange site that's made it out of beta. I've seen other sites have a custom layout and I think I heard in the StackOverflow podcast that some sites get custom layouts.
Is this site getting one just for making it out of beta or is it only popular sites that have this privilege?
Comment: It's my understanding that they will, but perhaps someone from Stack can respond.
Answer: From Feedback Requested: Design-Independent Graduation

The Community Team announces that a site is cleared for graduation. Without delay...

the beta label is removed
elections are held
migration paths are set up
community ads are run
a link to the site is added to the footer

...Then, as it becomes available

the site gets their custom design.
privilege thresholds are increased to graduated site levels

The key to the answer is "as it becomes available". I remember reading in another thread that the SE designers have a bunch of custom designs in their queue, so Magento SE will get one eventually.
Comment: I can only imagine the amount of work required to make and maintain custom layouts for every site. I can picture somone in that team saying _"What were we thinking?!"_
Comment: They say they're hiring designers as fast as they can on-board them, but I also imagine there would be a critical mass point where all the design work would be eaten up in a month and then everyone would get laid-off. I imagine they're attempting to get it all done, but also be sustainable.
Answer: The info in fschmengler's answer is the most current available at the moment. Just to confirm, we do intend to give all graduated sites custom designs, but unfortunately, it could take quite some time (several months at least) before your design actually arrives. Generally a designer drops by meta to share a first draft shortly before anything goes live.

Is this site getting a custom layout?