Get number of characters in an array?

Question: I want to send a content length with a http request. For a normal string, I can use the function strlen(). But how do I using that for an array specially for a multidimensional array in PHP? I've found the following script to extract an array like the var_dump(). But what do I need for the Content-Length?
function count_array_chars($array){
  foreach($array as $key => $value){
      if (!is_array($value))
      {
          echo $key ." => ". $value ."\r\n" ;
      }
      else
      {
         echo $key ." => array( \r\n";

         foreach ($value as $key2 => $value2)
         {
             echo "\t". $key2 ." => ". $value2 ."\r\n";
         }

         echo ")";
      }
  }
}

UPDATE:
$data_array = array(
    "end"=>array("dateTime"=>$end),
    "start"=>array("dateTime"=>$start),
    "summary"=>$name
  );

Comment: content length of what ? an array or what ?
Comment: For a HTTP-Request. To send data to Google via POST, I must using a Content-Length in the request-header. I've updated my question with an example of the array.
Answer: Assuming that you only want to count the values, you can use this approach:
$array = array(
    "1" => "abcd",
    "2" => "xyz"
);

function count_array_chars(array $array)
{
    $charNumber = 0;
    array_walk_recursive($array, function($val) use (&$charNumber)
    {
        $charNumber += strlen($val);
    });
    return $charNumber;
}

print count_array_chars($array);

If you also want to count the keys, it looks like that:
$array = array(
    "end" => array("dateTime"=>"end"),
    "start" => array("dateTime"=>"start"),
    "summary" => "name"
);

function count_array_chars(array $array)
{
    $charNumber = 0;
    array_walk_recursive($array, function($val, $key) use (&$charNumber)
    {
        $charNumber += strlen($val) + strlen($key);
    });
    return $charNumber;
}

print count_array_chars($array);

Comment: Thanks for your answer. I think the request catch it, but I'm not there where I want. I have to create a new question.
Answer: Since you want to send the array as part of an http request, you can prepare it with http_build_query and count the strlen of the chain returned by http_build_query:
<?php

$data_array = array(
    "end"=>array("dateTime"=>'end'),
    "start"=>array("dateTime"=>'start'),
    "summary"=>'name'
  );

$http_build_query = http_build_query($data_array);
echo strlen($http_build_query);

Get number of characters in an array?


How can I find $\int \tan x \cos 2x \, dx$

Question: How can I find $$\int \tan x \cos 2x \, dx?$$
Comment: $\cos\;2x=2\cos^2\;x-1$
Answer: HINT
(1) $\cos 2x = \cos^2x-\sin^2x=2\cos^2x-1$.
(2) $2\sin x\cos x = \sin 2x$.
(3) $\frac{d}{dx}\log(f(x))=?$
Comment: @MAx: Why not try replacing the $\cos\;2x$ first with one of AD's suggestions and see where it leads you?
Comment: @MAxcoder: I do not want to spoil the fun parts.
Comment: thanks for your answer.But , Can you write step - by -step solution ?
Comment: The answer for checking purposes is the following:
$-\frac {\rm 1}{\rm 2}\rm{\cos(\rm 2x)}+\rm \ln(\cos(\rm x))$.
Answer: Suppose I gave you an integral of the form
$\displaystyle \int \cot x \ \ f(\sin x) \ \text{dx}$
Can you think of a substitution to get rid of the $\cot x$ term?
For a concrete example, can you try evaluating
$\displaystyle \int \cot x  \ \ (1 + \sin^5 x) \ \ \text{dx}$ ?
Answer: I'm going to tell you that by parts done directly isn't the way to approach this:
$$\int \tan(x)\cos(2x)dx = -\ln(\cos(x))\cos(2x) - 2\int \ln(\cos(x))\sin(2x)dx$$
As you can see, this expression is not likely to become any more manageable by solving the next integral.
In short, your problem comes down to simplifying the expression $\tan(x)cos(2x)$. Big hint. The other answers have shown you how to do this. Once you simplify it, you will have a much easier job of integrating said expression and you most certainly won't need integration by parts.
Answer: $\int\tan\;x\;\cos\;2x\;\mathrm dx$
=$\int\frac{sinx}{cosx}\;\cos\;2x\;\mathrm dx$
=$-\int\frac{1}{cosx}\;\cos\;2x\;\mathrm -sinx dx$                    $\frac{d(cosx)}{dx}$ = -sinx.dx
=$-\int\frac{1}{cosx}\;\cos\;2x\;\mathrm d(cosx)$
cos2x=2${cos^2x}$-1
=$-\int\frac{1}{cosx}\cdot(2{cos^2x}$-1) d(cosx)$
=$-\int(2{cosx}-\frac{1}{cosx}) d(cosx)$
= $-[\int(2{cosx}d(cosx)$ - $\int\frac{d(cosx)}{cosx}$
= $-[{cos^2x} + C1 - log (cosx) -C2]$
=$log(cosx)-{cos^2x}+C2-C1$ [C2,C1 - Integral Constants]
Comment: Please format your posts using MathJax to make them easier to read.


ARP requests, etc.

Question: I'm trying to run arp spoofing on a network. I've been working on this for about a week, and all the information I find is dated year 2000-2001.
My issue is, after testing a script that uses arpspoof on one network (worked fine, more or less), on another network, it doesn't seem to work at all. There doesn't seem to be any redirection.
My question is, since I can't find any new information on this, I'm beginning to think that ARP is old, outdated technology, that was abandoned due to its vulnerabilities. I'd like for someone to tell me I'm wrong.
Otherwise, is it possible that the network is using some protection from arp spoofing? If so, how does it work, and are there workarounds?
Thank you very much for your time!
Comment: It's worth noting that IPv6 does not have ARP, it has neighbour discovery which performs the same purpose
Comment: ARP is in use in 99% of networks today and has been unchanged for years. Switches are able to protect from ARP poisoning in some cases, but not all depending on the setup. Its very common for large public networks to have some protection from this attack.
Answer: ARP is still very much in use in IPv4 networks, but it is definitely possible for switches to lock a given IP to a specific MAC address (ARP resolves IP addresses to their MACs) which would prevent this from working.
How it's being done depends on how it was configured, but the only way to work around it is likely to contact whomever runs the network and explain what you are trying to do and see if they will allow it.
Comment: I don't honestly know about the popularity of different techniques.  I personally put each customer into their own VLAN so gratuitous ARPs can only impact their own services, I suspect that that old saw is true about this as well: If you ask 10 network engineers what is a popular way of protecting networks from ARP attacks, you'll probably get a dozen answers.  :-)
Comment: Is that a popular way of protecting a network from ARP spoofing?
Answer: ARP spoofing is a vulnerability known by switch vendors for quite some time. Long enough for countermeasures to start being put into place. Sometimes these have to be turned off when things like virtual IP addresses are used by (some) clusters; these networks have a legitimate reason for two devices to ARP the same address.

ARP requests, etc.


How to determine if a function or set is convex?

Question: I am trying to learn about how to prove whether functions or sets are convex. Unfortunately my teacher uses very hard to understand (for me anyway) notation and I am struggling to get my head around it. I understand that a set is convex if the the line between two points in the set is contained in the set, but are there specific steps to follow or things to check whether or not a function is convex?
-
I have two examples that I am unsure if I am approaching correctly:
(1) Is $x -> (Px,x)^{1/2} $ convex for $P>0?$
This gives $\sqrt{x^TPx}$. So if I take $P=\begin{pmatrix}1&0\\0&1\end{pmatrix}$
then
$x^tPx$ = $(x_1 x_2)$$\begin{pmatrix}1&0\\0&1\end{pmatrix}$$\begin{pmatrix}x_1\\x_2\end{pmatrix}$ = $x_1^2 + x_2^2$
This result will always be positive, therefore for any P > 0, the function will be convex. Is this method a correct way to prove convexity?
(2) Is the following set convex:
${x: ‖x‖_p  ≤1},p=1,2,3 $
I take it as this is the p-norm of $x$ which is the same as writing:
$$(\sum_{i=1}^3 |x_i|^p)^{1/2}$$ where p=1,2,3
So if $f(x)=‖x‖_p$, then f is convex for any p because
$f(x)=‖x‖_p,1≤p< +∞$ (any natural number which includes 1,2 & 3)
$f(0)+(x,y)≤‖x‖_p ‖x‖_q,$  where  $1/p+1/q=1$
$∂f(0)={c(0): ‖c(0)‖_q≤1}$
Where ∂f(v) is the set of all sub-gradients of f at point v (also known as the sub-differential).
Does this make sense? I got this from my lectures but I am a little unsure what it actual means in layman terms
-
Any extra advice or pointers in general about checking whether a set is convex or not would be greatly appreciated!
Comment: You prove (1) only for one P, not for any P. For (2) the power should be 1/p. Hint for 1: use the second derivative. Hint for 2: use the definition of a convex set, and use general properties of norms (like the triangle inequality).
Comment: @LinAlg Thank you for your feedback. I am a little unsure how am I to get the second derivative of 3 "unknown" or undefined matrices? That is why I defined P. Is it that $x*x^T$ would give $(x_1^2 +x_2^2)*P$ then you get the second derivative? Would that give 2? Sorry for the confusion, still learning!
Comment: $P$ is fixed, so merely $x$ is unknown. To get the $(i,j)$th element of the Hessian, first take the derivative w.r.t. $x_i$, then to $x_j$.
Comment: @LinAlg Apologies for all the questions but just wanted to check is this how I should be taking the derivative?

$ df/dx_1$ = $ P_{11} {x_1}_1 {x_2}_1 +P_{12} {x_1}_2 {x_2}_2 + P_{13} {x_1}_1 {x_2}_3 +P_{21} {x_1}_2 {x_2}_ 1+ P_{22} {x_1}_2 {x_2}_2 + P_{23} {x_1}_2 {x_2}_3 + P_{31} {x_1}_3 {x_2}_1 + P_{32} {x_1}_3 {x_2}_2 + P_{33} {x_1}_3 {x_2}_3$
Comment: @LinAlg Also is (2) correct, I changed the power to be $1/p$
Answer: (1) In general, any norm is convex. This follows from
$\| tx + (1-t)y\| \le t \|x\| + (1-t) \|y\|$ for $t \in [0,1]$.
Note that $x \mapsto \langle Px, x \rangle$ is a norm iff $P>0$.
(2) In general, if $f$ is convex, then the set $L = \{ x | f(x) \le C \}$ is
convex. To see this note that if $x,y \in L$, then
$f(tx+(1-t)y) \le t f(x)+(1-t) f(y) \le C$, hence
$tx+(1-t)y \in L$.
Note that the functions $x \mapsto \|x\|_p$ are norms for $p \ge 1$.


read the data line by line from text file and then assign the value to the corresponding field in a structure

Question: I am beginner in Perl scripting.
I want to read the data line by line from text file and then assign the
value to the corresponding parameter into a structure
my_input.txt
filed_ind 0x0B uint8.unsigen int
tx_offset 0x0C uint8.unsigen int
rxpowe    0x0D uint8.unsigen int
fillers   0x0A uint8.unsigen int
cellid    0x12 uint8.unsigen int
cellnum   0x13 uint8.unsigen int

Encoding:
I want to assign each of values to their corresponding parameter
(for e.g.filed_ind-> 0x0B ) it will be more like creating structure.
structure ABC
{
 filed_ind 0x0B
 tx_offset 0x0c
 rxpowe    0x0D
 fillers   0x0A
 cellid    0x12
 cellnum   0x13
}

Decoding:
from structure I want to extract the values in an array like my_message
(for e.g. my_message [0x0B,0x0c,0x0D,0x0A,0x12,0x13])
my code is given below
 #!/usr/local/bin/perl
 use strict;
 use warnings;
 my $file = 'my_input.txt';
 open my $fh, '<', $file or die "Could not open '$file' $!\n";
  while (my $line = <$fh>)
  {
   chomp $line;
   my @strings = $line =~ /([a-z_A-Z_0-9-]+)/;
   foreach my $s (@strings)
   {
    print "$1\n";
   }
 }

I was try to extract the vales from text file above code works only for extracting the parameter. what I ma looking for that I want the generate a structured message from text file which is like encoding and again extract the values from message structure like decoding.
Answer: It's not completely clear what you want to do. But this code loads the data you're interested in into a Perl hash (which is the closest thing Perl has to a struct) and then displays it.
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my %struct;
while (<DATA>) {
  my ($key, $val) = split;
  $struct{$key} = $val;
}

say Dumper \%struct;

__DATA__
filed_ind ox0B uint8.unsigen int
tx_offset ox0c uint8.unsigen int
rxpowe    ox0D uint8.unsigen int
fillers   ox0A uint8.unsigen int
cellid    ox12 uint8.unsigen int
cellnum   ox13 uint8.unsigen int

The output is:
$VAR1 = {
          'fillers' => 'ox0A',
          'tx_offset' => 'ox0c',
          'cellid' => 'ox12',
          'rxpowe' => 'ox0D',
          'filed_ind' => 'ox0B',
          'cellnum' => 'ox13'
        };

Comment: Hi Dave, thanks for your reply what I understand from your code that you are dumping the structure but If I want to modify some structure parameter again I have to go back to text file this will take more time so I want to modify in perl script itself. the output is not sorted
Answer: your question is not clear , below code stores [ox0B,ox0c,ox0D,ox0A,ox12,ox13]
into my_message .
use strict;
use warnings;
use Tie::IxHash;

my %hash;
tie %hash, 'Tie::IxHash';

my $file = 'my_input.txt';
open my $fh, $file or die "died opening $file";

while (my $line = <$fh>) {
    if(length($line) > 1) {
        chomp $line;
        my @a = split(" ", $line);
        $hash{$a[0]} = [$a[1], $a[2], $a[3]];
    }
    else {
        next;
    }
}

my @my_message;
foreach my $v (keys %hash) {
    push @my_message, $hash{$v}[0] ;
}

Comment: error:Use of uninitialized value $a[0] in hash element at test3.pl line 14, <$fh>
Comment: you need to format your input file or handle blank lines
Comment: fillers1{2}  { 0x00, 0x00 }       Uint8,unsigned char
  n312_conn     0x02               Uint16, unsigned short , if the value start with Curly brackets how to remove curly brackets and value type is uitn16 then I need to pad with 0x00 (0x00,0x02) ..thanks for you reply


Dual predictable projection of a jump process

Question: It is stated in Jacod/Shyraev: Limit theorems of stochastic processes that the predictable projection of a jump process $\Delta A$ of a process $A\in\mathcal{A}^+$ (see below for the notation) is equal to the jump process of the compensator of A, that is it is equal to $\Delta (A^p)$.
In order to show this, there is a hint to use that for a local martingale $X$, the predictable projection of X given by ${}^p X$ is equal to $X_{-}$ and ${}^p(\Delta X)=0$.
So we have $$\Delta (A-A^p)=A-A^p-A_{-}+(A^p)_{-}=\Delta A-\Delta A^p$$ which yields $$0={}^p(\Delta A)-{}^p(\Delta A^p)$$, thus
$${}^p(\Delta A)={}^p(\Delta A^p)$$.
It remains to show that ${}^p(\Delta A^p)=(\Delta A^p)$, but i am not sure how to do this?

Notation:
Let $\nu^+$ be the set of all real valued processes $A$ that are càdlàg, adapted with $A_0=0$ and whose each path is non-decreasing.
Let $\mathcal{A}^+$ the set of all processes $A\in\nu^+$ which satisfy $$E[A_\infty]<\infty$$ where $\text{Var}(.)$ is the variation of a stochastic process.
Answer: ${}^p(\Delta A^p)=\Delta A^p$, since $\Delta A^p=A^p-A^p_-$ is predictable.


Converting to Prenex Normal Form

Question: I have to convert the following to Prenex Normal Form. I'm not sure what's the best way.
$$\left( \forall x \exists y P(x,y) \leftrightarrow \exists x \forall y \exists z R \left(x,y,z\right)\right)$$
Any ideas/hints on the best way to work?
Thanks!
Comment: Is the quantifier $\forall A$ a typo? $A$ does not occur anywhere else in the formula.
Comment: @HansHüttel thank you! fixed it to $\forall x$
Answer: Let's do this!
$$\forall x \exists y P(x,y) \leftrightarrow \exists x \forall y \exists z R \left(x,y,z\right)$$
You can't pull quantifiers out of a biconditional, so we have to rewrite it as two conditionals first:
$( \forall x \exists y P(x,y) \rightarrow \exists x \forall y \exists z R (x,y,z)) \land ( \exists x \forall y \exists z R (x,y,z) \rightarrow  \forall x \exists y P(x,y) )$
Now let's rename the variables so they all have a unique name:
$\left( \forall x_1 \exists y_1 P(x_1,y_1) \rightarrow \exists x_2 \forall y_2 \exists z_1 R \left(x_2,y_2,z_1 \right)\right) \land \left( \exists x_3 \forall y_3 \exists z_2 R \left(x_3,y_3,z_2 \right) \rightarrow  \forall x_4 \exists y_4 P(x_4,y_4) \right)$
Now we can pull out the quantifiers using the following two equivalences (which you can find on the wikipedia page as referenced by Hans):
Where $\varphi$ is a formula that does not contain $x$ as a free variable:
$$\varphi \rightarrow \forall x \ \psi(x) \Leftrightarrow \forall x (\varphi \rightarrow \psi(x))$$
$$\varphi \rightarrow \exists x \ \psi(x) \Leftrightarrow \exists x (\varphi \rightarrow \psi(x))$$
$$\forall x \ \psi(x) \rightarrow \varphi \Leftrightarrow \exists x (\psi(x) \rightarrow \psi)$$
$$\exists x \ \psi(x) \rightarrow \varphi \Leftrightarrow \forall x (\psi(x) \rightarrow \psi)$$
(Note the change in quantifier for the last two!)
OK, applied to what we had:
$\exists x_1 \forall y_1 \exists x_2 \forall y_2 \exists z_1 \left(  P(x_1,y_1) \rightarrow  R \left(x_2,y_2,z_1 \right)\right) \land \forall x_3 \exists y_3 \forall z_2  \forall x_4 \exists y_4 \left( R \left(x_3,y_3,z_2 \right) \rightarrow   P(x_4,y_4) \right)$
And finally we can pull the quantifiers outside the $\land$ using two more Prenex equivalences (also listed on that page):
Where $\varphi$ is a formula that does not contain $x$ as a free variable:
$$\varphi \land \forall x \ \psi(x) \Leftrightarrow \forall x (\varphi \land \psi(x))$$
$$\varphi \land \exists x \ \psi(x) \Leftrightarrow \exists x (\varphi \land \psi(x))$$
Applied to what we had:
$\exists x_1 \forall y_1 \exists x_2 \forall y_2 \exists z_1 \forall x_3 \exists y_3 \forall z_2  \forall x_4 \exists y_4 ((  P(x_1,y_1) \rightarrow  R \left(x_2,y_2,z_1 \right) \land \left( R \left(x_3,y_3,z_2 \right) \rightarrow   P(x_4,y_4) \right))$
And now it is in Prenex Normal Form!
Two final notes:

Note how due to the change in quantifier we cannot pull a quantifier outside a biconditional, and have to rewrite as two conditionals.
If you are putting the statement in PNF as a precursor to skolemization, you can make your life a bit easier to pull out the existentials before the universals, so you don't have to introduce functions symbols when skolemizing. So, if we had done that on your statement, we could have gotten:

$\exists x_1 \exists x_2 \forall y_2 \exists z_1 \forall x_3  \exists y_3 \forall x_4 \exists y_4 \forall y_1  \forall z_2    ((  P(x_1,y_1) \rightarrow  R \left(x_2,y_2,z_1 \right) \land \left( R \left(x_3,y_3,z_2 \right) \rightarrow   P(x_4,y_4) \right))$
Comment: Thank you for this great answer!!!
Comment: @Alan You're welcome!
Comment: How did you pull out the existensials? It was $\exists x_2 \forall y_2 \exists z_1$ originally, how did you manage to swap them into $\ldots \exists x_2 \exists z_1 \ldots \forall y_2  \ldots$?
Comment: @sas Ah, good catch!  Will fix ...
Answer: Hint: Rename the bound variables such that they are all distinct, then move the quantifiers outside using the rules for connectives. See https://en.wikipedia.org/wiki/Prenex_normal_form#Conversion_to_prenex_form for details.
Comment: Thanks! could you be a little more specific? I don't seem to understand this topic very well. I think I just need a good exmaple
Comment: A biimplication $\phi_1 \leftrightarrow \phi_2$ is really a conjunction $\phi_1 \leftarrow \phi_2 \wedge \phi_2 \leftrightarrow \phi_2$. So use this first. Next, use the rules for implication (see the reference I gave in my answer).

Converting to Prenex Normal Form


What is the "variance component parameter" in mixed effect model?

Question: On page 12 of Bates' book on mixed effect model, he describes the model as follows:

Near the end of the screenshot, he mentions the

relative covariance factor $\Lambda_{\theta}$, depending on the variance-component parameter, $\theta$

without explaining what exactly is the relationship. Say we are given $\theta$, how would we derive $\Lambda_{\theta}$ from it?
On a related note, this is one of many instance in which I find Bates' exposition to be a bit lacking in details. Is there a better text that actually goes through the optimization process of parameter estimation and the proof for the distribution of test statistic?
Comment: I think $\theta$ just means what kind of variance-component you will assume, such as AR(1) or UN, etc.
Comment: @DeepNorth I have been reading the text more closely, and at some point the author talks about optimizing the likelihood with regards to $\theta$. So I think $\theta$ must be an actual parameter. (page 108, sec 5.4.2)
Comment: Have you abandoned the question? So far, two answers have been provided, without a single comment on them. Please consider giving constructive feedback on the answers, such that, if they are not providing a (satisfactory) solution, at least a discussion can develop narrowing down the problem and leading to its solution. Not reacting to the answers of your question discourages further answers.
Comment: Did you manage to figure this out?, I'm having the same difficulty understanding the relationship between the covariance matrix and theta.
Answer: The variance-component parameter vector $\theta$ is estimated iteratively to minimise the model deviance $\widetilde{d}$ according to eq. 1.10 (p. 14).
The relative covariance factor, $\Lambda_\theta$, is a $q \times q$ matrix (dimensions are explained in the excerpt you posted). For a model with a simple scalar random-effects term, (p. 15, Fig. 1.3) it is calculated as a multiple of $\theta$ and identity matrix of dimensions $q \times q$:
$$\Lambda_\theta = \theta \times {I_q}$$

This is the general way to calculate $\Lambda_\theta$, and it is modified according to the number of random-effects and their covariance structure. For a model with two uncorrelated random-effects terms in a crossed design, as on pp. 32-34, it is block diagonal with two blocks each of which is a multiple of $\theta$ and identity (p. 34, Fig. 2.4):

Same with two nested random-effects terms (p. 43, Fig. 2.10, not shown here).
For a longitudinal (repeated-measures) model with a random intercept and a random slope which are allowed to correlate $\Lambda_\theta$ consists of triangular blocks representing both random-effects and their correlation (p. 62, Fig. 3.2):

Modelling the same dataset with two uncorrelated random-effects terms (p. 65, Fig. 3.3) returns $\Lambda_\theta$ of the same structure as shown previously, in Fig. 2.4:

Additional notes:
$\theta_i = \frac{\sigma_i}{\sigma}$
Where $\sigma_i$ refers to the square root of the i-th random-effect variance, and $\sigma$ refers to the square root of the residual variance (compare with pp. 32-34).
The book version from June 25, 2010 refers to a version of lme4 which has been modified. One of the consequences is that in the current version 1.1.-10. the random-effects model object-class merMod has a different structure and $\Lambda_\theta$ is accessed in a different way, using the method getME:
image(getME(fm01ML, "Lambda"))

Answer: It's hierarchical reasoning.  There are a bunch of parameters in your linear model, the components of b.  In a pure fixed effects model you would just get estimates of these and that would be that.  Instead, you imagine that the values in b themselves are drawn from a multivariate normal distribution with a covariance matrix that is parameterized by theta.  Here is a simple example.  Suppose we look at animal counts at five different time periods at 10 different locations.  We would get a linear model (I'm using R talk here) that would look like count ~ time + factor(location), so that you would have (in this case) a common slope for all of the regression (one at each location) but a different intercept at each location.  We could just punt and call it a fixed effect model and estimate all of the intercepts.  However, we want might not care about the particular locations if they were 10 locations selected from a large number of possible locations.  So we put a covariance model on the intercepts.  For instance, we declare the intercepts to be multivariate normal and independent with common variance sigma2.  Then sigma2 is the "theta" parameter, because it characterizes the population of intercepts at each location (which are thus random effects).


What teams have won the Europa League the season after winning the Champions League?

Question: I am looking for a list of football clubs (if any) that have won the UEFA Europa League the season immediately following on from where they won the UEFA Champions League.
I would also be interested in knowing the seasons (years) in which the wins occurred.
Answer: It happened only to Chelsea
Chelsea

2011/2012 Champions League winner
2012/2013 Europa League winner

Those are the table of Champions League finals and Europa League finals
Comment: Thanks, looks like you are correct. I fount [this](http://www.worldfootball.net/winner/champions-league/) and [this](http://www.worldfootball.net/winner/europa-league/) which made it fairly quick to scan though them to confirm your answer!
Comment: Up for you, I add those sources to my answer


MySQL Query Browser mysteriously can't connect

Question: I have a problem with an end-user who can't connect to their MySQL Server.
The facts:

Client is Windows XP on a corporate Domain. Group policy has disabled Windows Firewall and there is no other firewalling software installed.
The software MySQL's own query browser, v1.1.20, and is a permitted install.
The username and password are correct.
The query browser takes longer than a normal connect when trying then returns the error message "MySQL Error Number 2003 - Can't connect to MySQL Server on 'hostname' (10060)"
The query browser can "ping" the server with no problem.
Manually connecting using Window's own telnet command succeeds and the handshake initiation is clearly visible. So the hostname resolves on that PC and there is no networking issue (e.g. routing).
We've tried re-installing the query browser to no avail.
The server is running fine and everyone else who needs to connect (including myself) can successfully connect, most of them using the exact same version. So it is not a server problem.

Googling the error shows this is a classic unavailable connection problem and lots of links show fixes for the server, but the problem seems to reside entirely in the install of the query browser, which doesn't make any sense. Thus Google is no help.
Has anyone else seen this or can offer suggestions?
Answer: This may not be applicable to the OP, as their client is running on a windows XP corporate domain, but I had similar issues under OSX/Unix, encountering 2003 errors when the SSH tunnel was clearly configured correctly. Turned out it was an idiosyncrasy of the MySQL Query Browser:

Note that in *nix OSs (including Mac OS X) you must use 127.0.0.1
  rather than 'localhost' or the connection will be made via a named
  pipe rather than TCP.  Source

I'd always thought they were completely synonymous. Once I'd made the adjustment all worked as expected - hope this helps someone.
Answer: I can't answer your question but can say I have had the same experience once before an a Win XP machine. In that instance it Query Browser wouldn't connect to MySQL server on any machine, including a local instance. As a result, I now use a third party product called MySQL-Front. It's not free, but for me at least it was well worth the price.
Comment: That's depressing. It sounds like a re-install of XP is the only solution. I don't think I can arrange that. :-(
Comment: Rather than reinstall XP why not try some of the alternatives to Query Browser? After all, QB is not all that fantastic.
Comment: QB is a) gratis b) what everyone else here is using. Changing it means I have to support it.
Answer: I may have found a solution to this problem. When connecting to the MySQL server, do not save the credentials and information in MySQL Query Browser. Instead, retype them each time when signing in. This works for me for every computer in the domain.
Comment: Interesting. Without another solution, we coded our own SQL module in the Admin code so people don't have to wrestle with the Query Browser.
Answer: There can be so many reasons why this problem occurs, so I'll try to contribute with a few suggested solutions based on the information you provided. Remember that these suggestions are shots in the dark, since there is absolutely no way to diagnostic this problem without having access to the server. With that said I'll start listing:

Check that the line skip_networking is not set to ON in the config file. If it is try to comment out this line.
You could also check that bind-address = 127.0.0.1 is not set in the config file. This line prevents everyone except localhost to connect to the database and you don't want that.
A third suggestion is that you could try to connect with a local account instead of a domain account. Windows Server don't allow domain accounts to use port 3306.
Check that the user has the privileges required to connect to the server from an external ip-address. You could try the following (or something similar):

GRANT ALL ON database.* TO username@'client ip address' IDENTIFIED BY 'password';
Remember to restart the mysql daemon each time you alter the configuration file. This error message is a little misleading, so I this helps you!
Comment: You didn't read the question. There is nothing wrong with the server it is functioning entirely correctly for all other users which I clearly said. The problem lies solely with the Query Browser on one PC. All your suggestions are for fixing the server.
Answer: If you use Windows XP, then go to network adapter properties, uninstall "Microsoft TCP/IP version 6", restart your computer.


Price levels and inflation in regressions

Question: How would we include price levels in a regression? Would we just take the log of the price index number, e.g.: Consumer Price Index number provided by the Office of National Statistics (UK statistical agency)? If not, then how would we include it? Is it acceptable to just put in the log of the inflation rate as a regressor on the RHS? If I am modelling savings and want to see how it responds to price levels, how would I do this?
Comment: The use of jargon ("CPI" and "ONS") and vague phrases (such as "throw in") make this question difficult to understand and problematic to answer. Please consider editing it to clarify what you would like to know.
Answer: Price levels are nonstationary: both means and variances tend to grow. We usually treat them as exponentially growing series.
In practice all combinations are used: $P_t$, $\Delta P_t$, $\ln P_t$, $\Delta\ln P_t$ etc. It depends on the problem.
For instance, the GDP deflator is essentially $P_t$, i.e. the level. It is used to convert nominal GDP into real GDP.
Inflation is usually in simple percentages, i.e. $P_t/P_{t-1}-1\approx \Delta\ln P_t$, but researches often use the continuously compounded version $\Delta\ln P_t$.
In your case of savings on prices, I would first look at what researchers are doing, by that I mean review the papers. It's not my field, so I can't give you a direct advice. I would start with reviewing the basic macroeconomic theories in this regard, like new Keynesian stuff which you can find in any textbook (Mankiw?). There's also a difference between a realized inflation, and inflation expectations.
I work with somewhat similar problem but in banking (deposits), not macroeconomic context. In deposits we usually look at sensitivity to the rates, not inflation. Economists in this context would probably look at real rates, i.e. interest rates minus inflation. So, if you regress savings, then make sure you don't double count the inflation.


Command line argument No such file or directory error in bash

Question: I have written a bash script and when it is executed as
./script a b c

it is working fine.
then I moved the script to the bin folder and tried to execute it as
script a b c

now it is showing error
a: No such file or directory
b: No such file or directory
c: No such file or directory

Any ideas on how to fix this?
Comment: yes it was there.
Answer: Rename your script. I suppose program script is installed on your system.
See from your bash: man script
Comment: Post output of `file $(which ssh-add)`.
Comment: ok . there was an ssh-add already installed.I renamed my script.Now it is working.
Comment: the script name was not script. it was ssh-add.There was no binary ssh-add installed in my system.The error was not with that
Answer: You execute your script with file as a parameter. When you execute by using
$ ./script a b c

parameter file and script are same location. after moving the file bin folder may be execute script from different location where your parameter file not there.
So execute your script with location of file
$ script /path/of/a /path/of/b /path/of/c

then it will be worked fine.


Solving recurrence relation?

Question: Consider the recurrence relation $a_1=8,a_n=6n^2+2n+a_{n−1}$. Let  $a_{99}=K\times10^4$ .The value of $K$ is______ .

My attempt :
$a_n=6n^2+2n+a_{n−1}$
$=6n^2+2n+6(n−1)^2+2(n−1)+a_{n−2}$
$=6n^2+2n+6(n−1)^2+2(n−1)+6(n−2)^2+2(n−2)+......+a_1$
$=6n^2+2n+6(n−1)^2+2(n−1)+6(n−2)^2+2(n−2)+......+6.1^2+2.1$
$=6(n^2+(n−1)^2+...+2^2+1^2)+2(n+(n−1)+...+2+1)$
$=6×n(n+1)(2n+1)/6+2×n(n+1)/2$
$=n(n+1)(2n+1+1)$
$=2n^3+2n^2+2n^2+2n$
$=2n(n^2+n+n+1)$
$=2n(n^2+2n+1)$
$a_n=2n(n+1)^2$
for $n=99, a_{99}=2×99×(99+1)^2=198×10^4$

I'm looking for short trick or alternative way, can you explain please?
Comment: Just to check, I would do a spreadsheet and solve the 99 steps, assuming $a_{n-1} = 0$
Answer: Let $b_{n}=\frac{a_{n}}{2}$.
Then $b_{n}=3n^2+n+b_{n-1}$.
For any $n$th degree polynomial $Q(x)$, one can find a $n+1$th degree polynomial $P(x)$ such that $P(x)-P(x-1)=Q(x)$.
Then, use this to note that $b_{n}-n(n+1)^2=b_{n-1}-(n-1)n^2$, since $n(n+1)^2-(n-1)n^2=3n^2+n$.
Thus $b_{n}-n(n+1)^2$ is a constant. But since $b_{1}=0$, then this implies that $a_{n}=2n(n+1)^2$.
Thus $a_{99}=198 \times 10^4$.
Comment: If you are wondering why I set $b_n$, it's simply to make calculations simpler.
Answer: The idea is to find a closed form solution. We start with
$$
a_1 = 8 \\
6n^2+2n = a_n -a_{n−1}
$$
which is an inhomogenous linear recurrence relation and look for the previous
sequence elements:
$$
6(n-1)^2 + 2(n-1) = 6n^2 -12 n + 6 + 2n - 2 = 6 n^2 - 10n + 4
= a_{n-1} - a_{n-2}
$$
Substraction gives
$$
12n - 4 = a_n - 2 a_{n-1} + a_{n-2}
$$
where the inhomogenous polynomial has been reduced by one degree and the order has increased from $1$ to $2$. Repeating the procedure leads to
$$
12(n-1) - 4 = 12 n - 16 = a_{n-1} - 2 a_{n-2} + a_{n-3} \Rightarrow \\
12 = a_n - 3 a_{n-1} + 3 a_{n-2} - a_{n-3} \Rightarrow \\
12 = a_{n-1} - 3 a_{n-2} + 3 a_{n-3} - a_{n-4} \Rightarrow \\
a_n = 4 a_{n-1} - 6 a_{n-2} + 4 a_{n-3} - a_{n-4}
$$
which now is a homogenous recurrence relation of order $4$.
The characteristic polynomial is
$$
p(t) = t^4 - 4 t^3 + 6 t^2 - 4 t + 1 = (t-1)^4
$$
so the solution is
$$
a_n = k_1 1^n + k_2 n 1^n + k_3 n^2 1^n + k_4 n^3 1^n = k_1 + k_2 n + k_3 n^2 + k_4 n^3
$$
The $k_i$ follow from the $a_i$ values:
\begin{align}
a_1 &= 8 \\
a_2 &= 6 \cdot 2^2 + 2 \cdot 2 + 8 = 36 \\
a_3 &= 6 \cdot 3^2 + 2 \cdot 3 + 36 = 96 \\
a_4 &= 6 \cdot 4^2 + 2 \cdot 4 + 96 = 200
\end{align}
We get a linear system
$$
\begin{pmatrix}
1 & 1 & 1 & 1 \\
1 & 2 & 4 & 8 \\
1 & 3 & 9 & 27 \\
1 & 4 & 16 & 64
\end{pmatrix}
\begin{pmatrix}
k_1 \\
k_2 \\
k_3 \\
k_4
\end{pmatrix}
=
\begin{pmatrix}
8 \\
36 \\
96 \\
200
\end{pmatrix}
$$
with the solution
$$
k =
\begin{pmatrix}
0 \\
2 \\
4 \\
2
\end{pmatrix}
$$
so we have
$$
a_n = 2 n + 4 n^2 + 2 n^3 = 2n (1 + 2n + n^2) = 2 n (n + 1)^2
$$
Then
$$
a_{99} = 2 \cdot 99 \cdot 100^2 = 198 \cdot 10^4
$$
and $K = 198$.
Answer: As $a_n-a_{n-1}$ is a quadratic polynomial, $a_n$ must be a cubic polynomial. By integration, close to $\dfrac63n^3=2n^3$.
Then the factor $10^4$ is very likely to be $(99+1)^2$, and we can gamble on the expression $2n(n+1)^2$. It works for $n=1$ ($a_1=8$) and $n=2$ ($a_2=36$). This is convincing enough.
$$2n=198.$$

By better knowledge of Faulhaber's formula, (the first coefficient is always $\dfrac1d$, the second coefficient is always $\dfrac12$), we can predict that the cubic term is exactly $\dfrac63n^3=2n^3$ and the quadratic term is exactly $\dfrac62n^2+n^2=4n^2$. This fits with $2n(n+1)^2$.
Answer: $$a_n-a_{n-1}=6n^2+2n$$
Now sum both sides from $n=2$ to $x$. You end up with a telescoping sum on the left hand side which will drastically make things easier and help you find the closed form, assuming you know some summation formulas.
$$\sum_{n=2}^x (a_n-a_{n-1})= \sum_{n=2}^x (6n^2+2n)$$
$$a_x-a_1=\sum_{n=2}^x (6n^2+2n)$$
$$a_x=a_1+\sum_{n=2}^x (6n^2+2n)$$
$$a_x=a_1-8+\sum_{n=1}^x (6n^2+2n)$$
$$a_x=\sum_{n=1}^x (6n^2+2n)$$
Therefore $a_{99}$ would be:
$$a_{99}=\sum_{n=1}^{99} (6n^2+2n)$$
Where now you can apply summation formulas.

Solving recurrence relation?


Como passar mais de uma opção de Controller no routes.MapRoute()

Question: Tenho a seguinte rota:
 routes.MapRoute(
           "Contracts",
           "Home/Contract/{contract}",
           new
           {
               controller = "Home",
               action = "Contract",
               contract = UrlParameter.Optional
           },
           new { contract = @"\w+" }
        );

É possível configurar essa rota para receber tanto o controller Home(como já configurado), quanto para um novo controller chamando Contributor? Basicamente um OR dentro do parâmetro controller.
Comment: A descrição do terceiro parâmetro do método MapRoute(): `"An object that contains default value routes"`.

Quando você da um `new { controller = "Home" }` você esta dizendo que se eu não passar nenhum valor de controller na minha url, é para eu usar um valor default para aquele parâmetro, que no caso seria o seu `Home`. Caso eu passe algum parâmetro com o valor controller, eu ignoro esse valor default.
Comment: Por que não muda a rota pra `"{controller}/Contract/{contract}",`?
Comment: @GabrielColetta entendi, obrigado pela explicação, então só para ver se eu entendi mesmo... o que conta mesmo para montar a rota é o segundo parametro? no caso `"Home/Contract/{contract}",`?
Comment: @LINQ mas e o parametro controller que está dentro do metodo routes.MapRoute?
Comment: @LINQ funcionou.... eu só nao entendi porque, se eu estou declarando o controller = "Home", action = "Contract".  Se você puder me explicar porque funcionou mesmo com essa declaração eu agradeceria.
Comment: É isso aí que o Gabriel falou. O primeiro parâmetro é o nome da rota, o segundo é o **formato** dela, o terceiro são os padrões.
Answer: Apenas mude a declaração da rota para:
routes.MapRoute(
       "Contracts",
       "{controller}/Contract/{contract}",
       new
       {
           controller = "Home",
           action = "Contract",
           contract = UrlParameter.Optional
       },
       new { contract = @"\w+" }
    );


Python - can a Matrix be a variable?

Question: I want to convert some Fortran code into Python but there is this block of code:
  do i=1,maxcomp
     do j=1,maxcomp
        do k=1,nvbin
           ng(i,j,k) = 0
        end do
     end do
  end do

these are do-loops, in Python known as for-loops. The line in the middle (ng(i,j,k) = 0) is a matrix and attached to it is a value, 0 in this case and through the for-loops many "variables" get created and you can refer them with the matrices.
Is there something similar in Python so i can convert the code?
Comment: Everything is a variable!  I think you're looking for either a nested list,  or if you're going to be doing a lot of heavy-lifting with the data, a numpy array.
Comment: If you want to work with matrices in python, you should look at [numpy](https://numpy.org/)
Answer: In Python for 2-dimensional matrices or higher dimensional tensors, the pratic is to use the external package numpy. The call ng=np.zeros((maxcomp, maxcomp, nvbin), dtype='float') alone will do it for you.
!pip install numpy. # will install numpy in virtual environments it is nor present.
import numpy as np
ng=np.zeros((maxcomp, maxcomp, nvbin), dtype='float')

Without resorting to Numpy, there are no native types to represent matrices, but it is easy to customize a class to do so. One of the more intuitive ways is to use nested lists - (also one of the worst ways).
Even dictionaries can work nice as matrices, as long as you control the indices and taking care that they lie inside the desired boundaries.
A dictionary can retrieve a value given comma separated numbers (internally they work as a tuple). So, you can just create an empty dict and use the same code you've seem in Fortran:
ng = {}
for i in range(maxcomp):
   for j in range(maxcomp):
       for k i range(nvbin):
           ng[i,j,k] = 0

Just take care that dictionaries map arbitrary keys to arbitrary values: they are not constrained to have 3-coordinates mapping to a scalar. But you can create any code you want expecting a dictionary with this structure, and it will work as a matrix (given you pass the sizes for each axis as separate parameters). If the code uses the .get method to retrieve values, you do not even need to fill the structure with 0s beforehand: each non-assigned value can be "seen" as 0 in a call like ng.get((i, j, k), 0)
Answer: if you want to do matrices, you should do it with numpy:
import numpy as np
templist = []
for i in range(1,maxcomp):
    for j in range(1,maxcomp):
        for k in range(1,nvbin):
           templist.append([i,j,k])
matrix = np.matrix(templist)

Comment: `np.matrix` is being depreciated. you should use an `np.array` instead
Answer: using numpy :
import numpy as np

ng = np.zeros((maxcomp,maxcomp,nvbin))

and probably need to decrease maxcomp and nvbin by 1 , as in python indices start from 0

Python - can a Matrix be a variable?


proof of a set problem

Question: So i have been reading How to prove it by daniel velleman and i have been trying to wrap my head around a specific proof for about 2 hours now. The problem goes like this:
Let U be any set.
 Prove that there is a unique A ∈ P (U) such that for every B ∈
 P (U), A ∪ B = B. (keep in mind that P(U) means the power set of U).
This particular problem has a solution in the appendix which is the following:
Let A = ∅∈ P (U). Then clearly for any B ∈ P (U), A ∪ B =
 ∅ ∪ B = B.
 To see that A is unique, suppose that A' ∈ P (U) and for all
 B ∈ P (U), A' ∪ B = B. Then in particular, taking B = ∅, we can
 conclude that A' ∪ ∅ = ∅. But clearly A' ∪ ∅ = A
 , so we have A' = ∅ = A.
I understand the first part, that is that there is at least one possibility ( the empty set ) where A ∪ B = B. However I cannot grasp why assigning a particular value to the ARBITARY set B and then proving rather trivially that A' = A makes A unique.
Answer: The assumption is that $A' \cup B = B$ holds for any $B \in P(U)$. This means that you can always choose any desired element in $P(U)$ and you would still have the aforementioned equality. So, as the empty set is an element of $P(U)$, we are free to choose it and replace it in that equation.
Answer: To prove uniqueness, the standard way is to assume that there are two objects $A'$ and $A$ that satisfy the conditions and prove that they are actually equal.
So, the proof assumes that $\emptyset$ (this is $A$) and $A'$ both satisfy the given equality.  In other words, for ALL $B\in\mathcal{P}(U)$, $\emptyset\cup B=B$ and $A'\cup B=B$.
Now, the author does something sneaky.  Since you're allowed to choose any $B$, the author chooses $B=\emptyset$ (the empty set is an element of $\mathcal{P}(U)$, so it's a valid choice for $B$).
Now, $A'\cup B=B$ is supposed to be true, but then $A'\cup\emptyset=\emptyset$ is true.  Since $A'\cup\emptyset=A'$, you have $A'=\emptyset$
Comment: Okay, so you assume there are two objects, ∅ and A' that satisfy the conditions. However we do not yet know what A' is, how can we be sure that A′∪B=B is true for all sets in P(U) after only checking that one case holds (namely that B = ∅). What about the other sets in P(U) other than the empty set ?
Comment: @Alexander Because you assumed that $A'$ satisfies the conditions and the conditions are that $A'\cup B=B$ for all $B$.  When you assume the conditions, you're assuming that property.  Think of it like saying "if there were another $A'$ that satisfied the property for all $B$, then it would look like ..."
Comment: By the way i presume what you are reffering to is the following equivalence right?:
 ∃!x P(x) = ∃x P(x) ∧ ∀y∀z((P(y) ∧ P(z)) → y = z).
Comment: @АлександърГьорев Yes, that's the equivalence that I'm (essentially) using.

proof of a set problem


View more than one project/solution in Visual Studio

Question: I am new to visual studio and I am experimenting around with some Windows Services. I have created two solutions and I would like to view both of them at once. Without having to click file->recent projects to switch back and forth.
Ideally this could take place in the solution explorer and just nest the projects, but I am only able to view one solution/project at a time there.
Is there anyway to view multiple solutions/projects in Visual Studio?
Comment: If you're just looking for a faster way to access "File > Recent Projects and Solutions", you can create a custom toolbar or menu entry. Open "Tools > Customize", switch to the "Commands" tab, click "Add Command" and choose "File > Recent Project List". Put it wherever you want.
Comment: Projects possible but solutions in the same solution explorer not possible. Have to start a new instance. But in mac version of visual studio supports it.
Answer: This is the way Visual Studio is designed: One solution, one Visual Studio (VS) instance.
Besides switching between solutions in one VS instance, you can also open another VS instance and open your other solution with that one. Next to solutions there are as you said "projects". You can have multiple projects within one solution and therefore view many projects at the same time.
Comment: Ok that makes sense. So in a nutshell you can nest projects within solutions. But you cannot have many solutions open at once. Thanks.
Comment: @5Daydreams why not compile all? With the optimization what is compiled it doesnt really matter anyway if you order to compile unchanged stuff again. If you mean what to RUN, that is a different matter. Next to the green triangle u click to run stuff, there's a dropdown
Comment: A solution is more or less like the workspace concept in Eclipse - you can't have two loaded in the same instance.
Comment: Mac version of visual studio supports opening multiple solutions in same solution explorer
Comment: With multiple projects, if I have multiple main() methods, how do I select which I want to have compiled?
Answer: There's a much easier (but not so obvious) way; right click on the Visual Studio icon in the taskbar, then right click on the application name in the popup menu, then click "Open". Windows will then open another instance where you can open another solution in.
Comment: Middle click on the VS icon on the taskbar to launch a new instance if one is already up. It's also handy to pin frequently used solutions to the Jump List. Right clicking on the icon and selecting one of those will open it in a new instance instead of the current instance.
Comment: You can open another instance like any other program. On Windows <=7, open as normal. On Windows >=8, you'll have to either hold the shift key or [toggle a global registry setting](http://superuser.com/questions/631967/how-do-i-make-windows-8s-start-menu-always-open-applications-with-open-as-new).
Comment: For OSX, right click on the VS icon in the dock and select "New Instance"
Answer: If you have two separate solutions, then you cannot view them simultaneously in the same VS instance. However, you can open multiple instances of VS and tab between them.
An alternative would be to import the projects from one solution into the other, thus putting all of your projects into one solution. You can do this by following these steps:

In the Solution Explorer, select the Solution into which you want to import a project. Right-click, and select Add->Existing Project from the context menu.
In the file chooser, find the project file that you want to import (it will end in .XXproj where XX is the language you're using).
Click Open and voila! Your project is imported.
Comment: How can I open multiple instances of VS?
Comment: @SasukeUchiha Right-click on the icon in your task bar then click Visual Studio 20xx on the context menu, where xx represents whatever version of Visual Studio you have, i.e. 2012, 2013, 2017, 2019
Answer: There is a way to store multiple solutions in one instance of VS.
Attempt the following steps:

File > Open > Project/Solution
This will bring up the open project window, notice at the bottom where it says options, select add to solution

Then select the file you want to add and click open
This will then add the solution to your project. You still won't be able to run the same project in a single instance of VS, but you can have all your code organized in one place.

NOTE:
This worked for Visual Studio 2013 Professional
Comment: This is the correct answer to the OP's original question: _view multiple solutions at once in the VS Solution Explorer_. Verified this continues to work as described in VS 2017.
Comment: The question has two parts solutions and projects. For solutions, this is not correct. It will add the second solution projects to the first solution. So it modifying the first solution which is wrong. Recently I think this feature is available for mac version but not in windows version.
Comment: This option seems to be missing in VS 2022 professional
Answer: Just right click on the Visual Studio icon and then select "New Window" from the contextual toolbar that appears on the bottom in Windows 8. A new instance of Visual Studio will launch and then you can open your second project.
Comment: This is categorical not what they asked.
Answer: You can create a new blank solution and add your different projects to it.
Answer: You can have multiple projects in one instance of Visual Studio. The point of a VS solution is to bring together all the projects you want to work with in one place, so you can't have multiple solutions in one instance. You'd have to open each solution separately.
Comment: Try that with 100s of projects and see your build time for a solution tend towards infinity. It also clashes with git's philosophy of handling source control for multiple projects. This is a monolithic nightmare.
Answer: Don't know whether this is useful but if you want to work with multiple projects without navigating through projects tree {like multi window} you can try opening VS in another virtual desktop (at least it's possible for Windows 10) by holding Ctrl+win+D. Then open another VS studio and open your other project there. You can switch between projects by Ctrl+win+arrow key {left/right}.
Answer: Two ways come to mind...

Open another visual studio window and open the second solution in it.
It would be preferable to add your existing projects to one solution, just right click and add existing project and navigate to the project file(csproj). .... e.g. C:\Users\User\Documents\Visual Studio 2012\Projects\MySqlWindowsFormsApplication1\MySql Windows Forms Project1\MySql Windows Forms Project1.csproj   ....In this second way you might want to setup multiple start up projects i.e. for people with client-server apps or apps with dependencies. ....To do this Select the solution then GoTo: Project>>Properties>>Startup Project>> Select Multiple Startup projects and set actions to Start. When you debug, the selected as start will run.
For interest sake you could open another multiple solution windows to view different projects at the same time. http://www.schwammysays.net/visual-studio-2012-tip-multiple-solution-explorers/
Answer: After a long research and different experiments the easiest way "FOR MAC USERS" is to create a script:
<code>open -a "Visual Studio" \
"path to first sln" \
"path to second sln" \
...
</code>
:D
Comment: script automation saves the day once again :p. did this for windows (single batch script containing multiple cmds for multiple solutions like so https://stackoverflow.com/questions/44659275/how-to-open-visual-studio-solution-file-from-the-command-prompt/66465812#comment117502294_44659276
Answer: File -> New Window. Select the other project in that window. Each project lives in a separate window. You can tab between them.
Answer: MAC users - this issue was winding me up, as its not possible to open two different Visual Studio instances at the same time.  Ive found a solution that works fine, though its a little unorthodox : get the latest beta testing version, which will install alongside your normal VS install in a separate sandbox (it does this automatically).  You can then run both versions side by side, which is enough for what I needed - to be able to examine one project for structure, code etc., while doing the actual coding I need to do in the 'current' VS install instance.


The complete solution to a system of polynomials over $\mathbb{R}$

Question: If I am solving a positive-dimensional system of polynomials over $\mathbb{R}$, and specifically am searching only for real solutions, how do I know that my solution is complete and there are no other possibilities?  For example, consider the system:
$$x_1^2 + x_2^2 = 1$$
I can solve it by letting $x_1 = t \in [-1,1]$, then $x_2 = \pm \sqrt{1-t^2}$ and I'm golden.  As far as I know there are no more real solutions that are unique (excluding the one that is the same up to the choice of parameter).  But how do I know that?  When the system gets more complicated, is there a nice way to figure it out?
I'd be interested in a general proof over an arbitrary field as well.  However, I suspect my life is going to be made harder because I am working with the real solutions only, and as a result there are solutions over the field extension that I don't consider.
Specifically, the equations are:
$$f\sum_{i=1}^n x_{i4} - K1 = 0$$
$$f\sum_{i=1}^n x_{i3}x_{i2} - K_2 = 0$$
$$f\sum_{i=1}^n x_{i1}x_{i3} - K_3 = 0$$
$$f\sum_{i=1}^n p_{z1}x_{i2}x_{i3} + f\sum_{i=1}^np_{y1}x_{i1}x_{13} - K_4 = 0$$
$$f\sum_{i=1}^n p_{z1}x_{i4} - f\sum_{i=1}^np_{x1}x_{i1}x_{13} - K_5 = 0$$
$$f\sum_{i=1}^n -p_{y1}x_{i4} - f\sum_{i=1}^np_{z1}x_{i1}x_{13} - K_6 = 0$$
along with the "circularity equations":
$$x_{i1}^2 + x_{12}^2 = 1$$
$$x_{i3}^2 + x_{14}^2 = 1$$
where $f \in \mathbb{R}^+$, $K_j \in \mathbb{R}$ (there is technically another set of circularity equations but they are on variables that do not appear in the above system).
Comment: In general, the set of (real) solutions to a system of polynomial equations can be horrible. Very often it is not even parametrizable; systems with parametrizable solution spaces are generally considered to be very nice. If there are particular constraints to the systems you are considering, like the dimension, number of equations or their degrees, that would be very much worth mentioning.
Comment: If all equations are at most quadratic, then the solution space can be parametrized very cleanly. If I understand correctly you have five bilinear equations, which form a linear family on one parameter?
Comment: I didn't see your edit.  I have 6 + 3n equations and 9n variables, where n is an integer.  I have one linear equation, five equations that are bilinear or trilinear in their variables*, and the 3n equations are quadratics in two variables (they are actually just the above equation whose solution is the unit circle, so I can assume that those are nice and solved).  I'm not sure though how that might help.

*they are bilinear with one parameter, or trilinear if I allow the parameter to itself be a variable.
Comment: Let me point out that in the general situation, if one is dealing with a semi-algebraic functions over $\Bbb R$ or another real-closed field as you are here, you can (attempt to) compute a [cylindrical algebraic decomposition](https://en.wikipedia.org/wiki/Cylindrical_algebraic_decomposition) which does exactly what you want.
Comment: For your example, also $x_2=-\sqrt{1-t^2}$ works.
Comment: To your first comment: I agree, edited.  To the second, I luckily have a very nice system that I'm working on in particular.  I would like to know if there is any way to know that I'm done finding solutions.
Comment: Then I suggest you share this system, or whatever properties make it very nice, because (as far as I know) there is no general way to know that you're done.
Comment: I believe that is correct, yes (sorry for the lack of mathematical formalism, I'm a bit new to this).  The equations are of the form: $f \sum_{i=1}^n x_iy_i - K = 0$, where $K \in \mathbb{R}$, or are otherwise very similar.  There are 5 such equations, and each one has the same parameter, $f$.
Comment: I suggest you describe your system in the question body itself. With something concrete to refer to and work with, I'm confident I can explain how to find all solutions and verify *that* these are all solutions.
Comment: Done.  Looking at them now, I was mistaken.  The last three equations of the "big six" are trilinear, but they have nearly the same form.
Comment: I see $4n$ variables of the form $x_{ij}$, and then $p_{x1}$, $p_{y1}$ and $p_{z1}$. Are these $3$ more variables?
Comment: That is correct. The remaining $2n$ variables exist only in a set of $n$ circularity equations and don't otherwise show up in this system, so I consider them to be solved.  The notation $p$ comes from the application itself (which is robotics, where the $p$ represents a position vector), but the $x_{ij}$ and $p$ variables are treated the same mathematically
Comment: The problem is clear now, thank you. Can it happen that $K_i=0$ for some $i$? This possibility forces one to distinguish a **lot** of cases, it would be nice if that could be avoided, at least in part.
Comment: Hmm... Actually, the case I care about is k = 0 except K3, which is a positive real number. The general case can be left to later that's the most important one
Answer: My answer ended up becoming rather much longer than I had hoped, even though I have omitted quite some details. So first I'd like to remark on your original question about general systems of polynomial equations. In the comments I said solving your system is relatively easy because it concerns only polynomials of low degree (in fact it it reduces to a system of equations of degree at most $2$). In spite of my unpleasantly long and cumbersome answer I stand by this comment; in general, solving systems with (many) polynomials of higher degrees is a very ad hoc matter, and is more often than not practically intractible.

In finding all solutions I'll assume familiarity with basic linear algebra; some vector and matrix notation, and solving systems of linear equations. Let ${\bf1}_n=(1,1,\ldots,1)\in\Bbb{R}^n$, let $K_i':=\tfrac{K_i}{f}$ and define $x_1,x_2,x_3,x_4\in\Bbb{R}^n$ as
$$x_j:=(x_{ij})_{1\leq i\leq n}.$$
This allows us to write down the system of six equations more concisely and transparently. Rewriting a bit and substituting the first two equations into the last three, the system becomes
\begin{eqnarray*}
\langle x_4,{\bf1}\rangle&=&K_1',\\
\langle x_2,x_3\rangle&=&K_2',\\
\langle x_1,x_3\rangle&=&K_3',\\
p_{z1}K_2'+p_{y1}x_{13}\langle x_1,{\bf1}_n\rangle&=&K_4',\\
p_{z1}K_1'+p_{x1}x_{13}\langle x_1,{\bf1}_n\rangle&=&K_5',\\
p_{y1}K_1'+p_{z1}x_{13}\langle x_1,{\bf1}_n\rangle&=&-K_6'.
\end{eqnarray*}
What is most striking is that, apart from the coefficient $x_{13}$ in the last three equations, these equations concern the $x_j$ only in terms of inner products! Also note that the variables $x_{24},\ldots,x_{n4}$ appear only in the first equation, which is linear and hence easy to solve. So will omit the first equation from now on.
First we treat some boundary cases. If $x_{14}=\pm1$ then $x_3=0$ and the system of equations becomes
\begin{eqnarray*}
0&=&K_2',\\
0&=&K_3',\\
0&=&K_4',\\
p_{z1}K_1'&=&K_5',\\
p_{y1}K_1'&=&-K_6'.
\end{eqnarray*}
This is a linear system of equations, having solutions (with $x_{14}=\pm1$) if and only if if $K_i'=0$ for all $i$, or $K_2'=K_3'=K_4'=0$ and $K_1'\neq0$. Similarly, if $x_{12}=\pm1$ then $x_1=0$ and the system of equations becomes
\begin{eqnarray*}
\langle x_2,x_3\rangle&=&K_2',\\
0&=&K_3',\\
p_{z1}K_2'&=&K_4',\\
p_{z1}K_1'&=&K_5',\\
p_{y1}K_1'&=&-K_6'.
\end{eqnarray*}
For any choice of $x_{22},\ldots,x_{n2}\in\Bbb{R}$ this is again a linear system. There are no solutions (with $x_{12}=\pm1$) if and only if $K_1'K_4'\neq K_2'K_5'$, or $K_2'=0$ and $K_4'\neq0$, or $K_1'=0$ and $K_5'\neq0$ or $K_6'\neq0$.
Now let $x_{12},x_{14}\in(-1,1)$. It follows from the circularity equations that for all $i$
$$x_{i1}=\pm\sqrt{1-x_{12}^2}\qquad\text{ and }\qquad x_{i3}=\pm\sqrt{1-x_{14}^2}.$$
Hence $x_{i1}=\pm x_{11}$ and $x_{i3}=\pm x_{13}$ for all $i$, so there exist unique vectors $e_1,e_3\in\Bbb{R}^n$ satisfying
$$x_1=\sqrt{1-x_{12}^2}\ e_1\qquad\text{ and }\qquad x_3=\sqrt{1-x_{14}^2}\ e_3,$$
and all their coefficients are either $1$ or $-1$. We may now rewrite the equations as
\begin{eqnarray*}
\sqrt{1-x_{14}^2}\langle x_2,e_3\rangle&=&K_2',\\
\sqrt{1-x_{14}^2}\sqrt{1-x_{12}^2}\langle e_1,e_3\rangle&=&K_3',\\
p_{z1}K_2'+p_{y1}e_{13}\sqrt{1-x_{12}^2}\sqrt{1-x_{14}^2}\langle e_1,{\bf1}_n\rangle&=&K_4',\\
p_{z1}K_1'+p_{x1}e_{13}\sqrt{1-x_{12}^2}\sqrt{1-x_{14}^2}\langle e_1,{\bf1}_n\rangle&=&K_5',\\
p_{y1}K_1'+p_{z1}e_{13}\sqrt{1-x_{12}^2}\sqrt{1-x_{14}^2}\langle e_1,{\bf1}_n\rangle&=&-K_6'.
\end{eqnarray*}
This eliminates $x_1$ and $x_3$ and leaves only $e_1$, $e_3$ in stead in these equations. First consider the case that $m:=\langle e_1,e_3\rangle\neq0$. Then by the second equation we have $K_3'\neq0$, and it can be written as
$$\sqrt{1-x_{14}^2}\sqrt{1-x_{12}^2}=\frac{K_3'}{m},$$
which shows that we must have $\tfrac{K_3'}{m}\in[-1,1]$, or equivalently $|K_3'|<|m|$. In particular we must have $|K_3'|<n$ for solutions to exist at all, as $|m|\leq n$. So let's assume that $|K_3'|<n$, and choose $e_1$ and $e_3$ such that $|K_3'|<|m|$. Counting the number of pairs for which this holds as a function of $K_3'$ is a nice combinatorial problem that is suited for a question of it's own, though it is not complicated.
The first equation is now a linear equation for $x_{22},\ldots,x_{n2}\in\Bbb{R}$. Substituting the second equation into the last three yields the system
\begin{eqnarray*}
\sqrt{1-x_{14}^2}\sqrt{1-x_{12}^2}\langle e_1,e_3\rangle&=&K_3',\\
p_{z1}K_2'+p_{y1}e_{13}\frac{K_3'}{\langle e_1,e_3\rangle}\langle e_1,{\bf1}_n\rangle&=&K_4',\\
p_{z1}K_1'+p_{x1}e_{13}\frac{K_3'}{\langle e_1,e_3\rangle}\langle e_1,{\bf1}_n\rangle&=&K_5',\\
p_{y1}K_1'+p_{z1}e_{13}\frac{K_3'}{\langle e_1,e_3\rangle}\langle e_1,{\bf1}_n\rangle&=&-K_6',
\end{eqnarray*}
which are then also linear equations in $p_{x1},p_{y1},p_{z1}\in\Bbb{R}$, where there are unfortunately a lot of cases to distinguis. The first equation simply tells us that
$$x_{14}^2=1-\frac{K_3'^2}{(1-x_{12}^2)\langle e_1,e_3\rangle^2},$$
which determines $x_{14}$ up to sign.
Finally, consider the case that $\langle e_1,e_3\rangle=0$. Note that this is only possible if $n$ is even. Then $K_3'=0$ and the second equation is obsolete. For each of the $2^n$ choices for $e_1$ there are $\tbinom{n}{\tfrac{n}{2}}$ choices for $e_3$, by changing the signs of precisely half of all coordinates of $e_1$. For every choice of $x_{12},x_{14}\in\Bbb{R}$ the remaining equations are again linear, and there are a lot of cases to distinguish as before.
Comment: This is outstanding I know comments aren't supposed to be for this, but thanks!


Consistency of M-estimator based on plug-in estimator?

Question: Suppose we estimate a quantity $\theta_0$ by the $\tilde{\theta} = \hat{\theta}(\eta)$ that solves the estimating equation

$$S_n(\tilde{\theta}, \eta_0) = 0$$

where $\eta_0$ is a nuisance parameter that is known. Suppose that the assumptions of the M-estimator are satisfied, and

$$\tilde{\theta} \xrightarrow{p}\ \theta_0$$

so that consistency is achieved.

Question: Let suppose we do not know $\eta_0$, but we have a consistent estimator $\hat{\eta}$ of $\eta_0$. If now $\hat{\theta} = \hat{\theta}(\hat{\eta})$, under which condition do we have consistency?

Clearly if we estimate $\hat{\eta}$ through an estimating equation we can stack all our estimating equations and thus obtain consistency automatically.
However, what if $\hat{\eta}$ is not obtained through an estimating equation?
Answer: Background: For consistency when $\eta_0$ is known, we typically need a function $S(\theta, \eta)$ such that for every $\epsilon > 0$ we have

$$\sup_{\theta \in \Theta} \frac{| S_n(\theta,\eta_0) - S(\theta,\eta_0) |}{1 + | S_n(\theta,\eta_0)| + |S(\theta,\eta_0) |}  \xrightarrow{p}\  0$$
  $$\inf_{|\theta - \theta_0| > \delta}| S(\theta,\eta_0) |  >  0 = |S(\theta_0, \eta_0)|$$

with $S_n(\tilde{\theta},\eta_0) = op(1)$.
Note that a more restrictive version of the first assumption is

$$\sup_{\theta \in \Theta} | S_n(\theta,\eta_0) - S(\theta,\eta_0) | \xrightarrow{p}\  0$$

From the infimum condition, for any $\delta >0 $ we have an $\epsilon
> 0$ such that
$$ P\left( \left| \tilde{\theta} - \theta_0 \right| > \delta \right) \le
P\left( \left| S(\tilde{\theta},\eta_0) \right| \ge \epsilon \right) $$
Consistency can then be proved through

$$ \begin{align}| S(\tilde{\theta},\eta_0)   | &\le |  S_n(\tilde{\theta}, \eta_0)  | + |S(\tilde{\theta},\eta_0) - S_n(\tilde{\theta}, \eta_0)  | \\
&\le  op(1) + op(1+|S_n(\tilde{\theta},\eta_0)| + |S(\tilde{\theta}, \eta_0)|) \\
&= op(1 + S(\tilde{\theta}, \eta_0)) = op(1) \end{align}
$$

Hence $P\left( | S(\tilde{\theta},\eta_0)  | \ge \epsilon \right) \to 0$ which proves consistency.
Solution:
Suppose that in addition to the previous assumptions, either

(1) $S_n(\theta,\eta)$ is stochastically continuous uniformly in $\theta$ with respect to $\eta$ at $\eta_0$

or

(2) $S(\theta,\eta)$ is continuous uniformly in $\theta$ with respect to $\eta$ at $\eta_0$

with $S_n(\hat{\theta},\hat{\eta}) = op(1)$.
If (1) is true the proof is trivial, with
$$ \begin{align} |S_n(\hat{\theta},\hat{\eta})| &\le |S_n(\hat{\theta},\eta_0)| + |S_n(\hat{\theta},\hat{\eta}) - S_n(\hat{\theta},\eta_0)|  \\
&\le |S_n(\hat{\theta},\eta_0)| + \sup_{\theta \in \Theta}|S_n(\theta,\hat{\eta}) - S_n(\theta,\eta_0)| \\
&= |S_n(\hat{\theta},\eta_0)| + op(1)
 \end{align}$$
with the last line true because of (1).
We conclude that the $\hat{\theta}$ also satisfies $S_n(\hat{\theta},\eta_0) = op(1)$, and the theory in the background can be applied automatically.
If (2) is true, from the infimum condition, we get that for any $\delta >0 $ we have an $\epsilon_1 > 0$ and $\epsilon_2 > 0$ such that

$$\inf_{\theta :|\theta-\theta_0| > \delta}\inf_{|\eta -\eta_0| \le \epsilon_2 }| S(\theta,\eta) |  >  \epsilon_1 $$

Therefore, we have
$$ P\left( \left| \hat{\theta} - \theta_0 \right| > \delta \right) \le
P\left( \left| S(\hat{\theta},\hat{\eta}) - S(\theta_0,\hat{\eta}) \right| > \epsilon_1 \right) + P(|\hat{\eta} - \eta_0| > \epsilon_2)$$
The last term goes to zero as $n \to \infty$.
Then, we have

$$ \begin{align}
| S(\hat{\theta},\hat{\eta}) - S(\theta_0,\hat{\eta})  | &\le
|S(\hat{\theta},\eta_0) - S(\theta_0,\eta_0)| \\
&+
|S(\hat{\theta},\hat{\eta}) - S(\hat{\theta},\eta_0)| +
|S( \theta_0,\hat{\eta}) - S(\theta_0,\eta_0)|
\\
&\le  op(1)  + 2\sup_{\theta \in \Theta}|S( \theta,\hat{\eta}) - S(\theta,\eta_0)| \\ &= op(1) \end{align}
$$

where the last line is true because of (2).
Comment: Can you not do this more easily by 1. Revisiting the Wilk's-like proof of the consistency of the estimating eq'n solution, 2. Appeal to the Slutsky theorem for the elements of the Taylor expansion
Comment: That requires differentiability. Which proof of Wilk do you have in mind? The one I know is for likelihood functions.
Comment: Hmm.. I may be mistaken. How does one prove the EE estimator is consistent?


How do I find a basis for the following subspace?

Question: I'm unsure how to do the following problem: Find a basis of the following subspace of $R^4$. W = all vectors of the form $(a,b,c,d)$ where $a+b-c+d=0$. Any help would be great, many thanks :)
Answer: It's one equation in four-dimensional space, so the subspace in question has three dimensions. Three linearly independent vectors satisfying the relation would do it. For instance:
$$
(1,0,1,0),(0,1,1,0),(0,0,1,1)
$$


Who scored the most penalties in one season in the UEFA Champions league

Question: Which player scored the most penalties in one season in the UEFA Champions league?
Answer: There are several players with four scored penalties in one season. As three players (Immobile, Werner and Messi) already have scored three penalties this season (group stage 2020) there is a good chance of at least one of them beating this record.
All players who scored four penalties until season 19/20:

Cristiano Ronaldo 2017/18
Robert Lewandowski 2016/17
Thomas Müller 2014/15
Arturo Vidal 2013/14
Lionel Messi 2011/12

The all-time leader is Cristiano Ronaldo with 19 scored penalties.
Here is a list of all goal scorers, including appearances, assists and how many goals were penalties.


Get the last value after spliting a string with hyphen in jquery?

Question: Hi all i will have a string separated with hyphens in and i want to get the lastindex of the string and replace it with new value
   var str1="New-New_Folder"; //Replace New_Folder with Folder so that the str becomes
   var newstr1="New-Folder";

   var str2="New-New_Folder-New_Folder"; //Replace the last New_Folder with Sub_Folder so that the str becomes
   var newstr2="New-New_Folder-Sub_Folder";

can any one help me here?
Comment: I've read this twice, now, and I'm still unsure what you're asking. What string do you want to replace? What do you want to replace it *with*?
Answer: You can use split then get the last index with the length minus one:
var string = "some-hyphen-string";
var parts = string.split("-");
var lastPart = parts[parts.length - 1]; //lastPart is now the final index string split

Demo: http://jsfiddle.net/ACfRU/
Answer: I have to admit this is very unclear, but maybe with tymeJV's answer and mine you can come up with a solution that fits your needs.
var str1="New-New_Folder";
var newstr2 = replaceLast(str1, "Sub_Folder");

alert(newstr2);

function replaceLast(strWhat, strWith) {
    strWhat = strWhat.split("-");
    strWhat[strWhat.length - 1] = strWith;
    strWhat = strWhat.join("-");
    return strWhat;
}

JSFiddle: http://jsfiddle.net/FF96g/
Answer: Using String functions:
var str1 = "New-New_Folder";
var newstr1 = str1.substring(0, str1.lastIndexOf("-")+1) + "Folder";


Acessar Site Por Loggin

Question: não estou conseguindo acessar este site abaixo porque não localizo pelo VBA uma forma de inserir o Login e senha. Alguém saberia como acessar estes campos

https://www.newspace.com.br/pan/
eu tentei acessar procurando por frames, mas ainda sim não consegui acessar
Answer: Tente o seguinte código:
<code>Private Sub AcessarSite()
    Dim driver As InternetExplorer
    Dim elem As HTMLBaseElement
    Dim url As String

    url = "https://www.newspace.com.br/pan/"

    Set driver = New InternetExplorer
    driver.Visible = True
    driver.Navigate url

 Set doc = driver.document.frames
 Set doc1 = doc.frames("Principal")

    doc1.document.getElementById("Usuario").innerText = "USUARIO CORRETO"
    doc1.document.getElementById("Senha").innerText = "SENHA CORRETA"
    doc1.document.getElementById("Ok").Click

    Set driver = Nothing
End Sub
</code>
Testei aqui e funcionou, o problemar era realmente com os frames.
Comment: Bom dia Marcelo, muito obrigado pela resposta e dedicação ao tema, infelizmente eu não estou conseguindo setar o login no site, ele me da um erro -> "Erro em tempo de execução '91': A variavel do objeto ou a variavel do bloco 'With' não foi definida". eu tentei utilizar o código com o Xpath "//*[@id='Usuario']" e com "html/body/form#f/table/tbody/tr/td/iframe/html/body/form#f/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/input#Usuario" mas ambos retornam o mesmo erro
Comment: também não roda, ele da como "Erro em tempo de execução '424': O objeto é obrigatório", parece que para acessar este campo eu teria que acessar alguns iframe, mas mesmo tentando acessar esses iframes ele ainda não localiza o campo de login
Comment: Em vez de ie, tente driver, as vezes ele está dando erro por assumir ie como internet explorer e não uma variável
Comment: Desculpe Marcelo, mas não entendi bem o que você disse.
Comment: veja a resposta editada
Comment: Perfeito Marcelo, muito obrigado meu amigo, eu ja estava ficando louco com isso. Bora para outros desafios agora... vlw

Acessar Site Por Loggin


Rendering a module's template contents in the page body

Question: I've been digging through the Drupal docs and haven't found a solution for this:
What I'm trying to do is to create a module with a URL using menu hooks. I've got that far. When this URL is viewed, I'd like to insert some HTML and JS code in the body but I haven't managed that. I've been trying to use templates.
This is what my module looks like:
<?php
  function hello_menu(){
    $items = array();

    $items['nodes'] = array(
      'title'            => t('My Nodes'),
      'page callback'    => 'helloworld_output',
      'access arguments' => array('access content'),
    );

    return $items;
  }

  function hello_theme($existing, $type, $theme, $path){
    return array(
      'timeline' => array(
        'variables' => array('content' => NULL),
        'file' => 'timeline.tpl.php',
        'path' => drupal_get_path('module', 'hello')
      )
    );
  }

  function helloworld_output() {
    header('Content-type: text/plain; charset=UTF-8');
    header('Content-Disposition: inline');
    return theme('timeline', array());
  }
?>

..and this is what I want rendered in the body.

If I place this code into my timeline.tpl.php, it doesn't get rendered in the page but before the whole content. Do I need to wrap this in PHP tags?
How can I get the onLoad() function to fire once my Drupal page is loaded. I a normal HTML page, I could use the body onload= callback.
(It looks really simple when you've worked with Drupal but for a first-timer, it's been a nightmare.)
Comment: Is the div getting added in your page ?
Comment: i Think you don't have to send the headers, It is set by Drupal core
Comment: @DineshKumar, Everything gets added to the page but before the HTML tag. It's right before Drupal spews out all the other content.
Comment: @DineshKumar, I removed those headers but the problem still exists. The `div` and `script` tags get printed at the beginning of the page before the `html` tag.
Answer: The best way to add the JavaScript in Drupal is to have an external JS file like helloworld.js in your module/theme and include it using the function,
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
   );
  drupal_add_js('http://example.com/example.js', 'external');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

For more info see drupal_add_js()

How can I get the onLoad() function to fire once my Drupal page is loaded. I a normal HTML page, I could use the body onload= callback

jQuery(document).ready is similar to your onload function that you are trying to call in your HTML body.
UPDATE:
Add the "template" instead of file in your  hook_theme for using templates like,
 function hello_theme($existing, $type, $theme, $path){
    return array(
      'timeline' => array(
        'variables' => array('content' => NULL),
        'template' => 'timeline',
        'path' => drupal_get_path('module', 'hello')
      )
    );
  }

Comment: @DinestKumar, would you know how I can output HTML from the template into my Drupal body? Do I need to `print` it from the template?
Comment: @MrFluff i have updated my answer
Comment: you have done it right, all you have to change the hook_theme. No need to print. You can use print to print the PHP variable


To determine probability

Question: A bag contains 1 white and 8 red balls. The probability for randonly drawing a red ball 8 successive time is 11.11%= $\frac{1}{9} (p = \frac{8}{9}\cdot \frac{7}{8}\cdot \frac{6}{7}\cdot \frac{5}{6}\cdot \frac{4}{5}\cdot \frac{3}{4}\cdot \frac{2}{3} \cdot \frac{1}{2})$. What is the 88.89% = $\frac{8}{9}$ probability against this signifies? Does it mean that there is 88.89% probability that the 1 white ball would be randomnly chosen before 8 successive red balls are drawn?
Comment: Is this a question from a course or textbook? If so, please add the `[self-study]` tag & read its [wiki](https://stats.stackexchange.com/tags/self-study/info).
Answer: I think you are assuming, when you say "drawing a red ball $8$ successive times", that "drawing a red ball in first $8$ draws". You are not considering the case when you get the white ball in the first draw and then 8 red balls successively.
Assuming that you want to say "drawing a red ball in first 8 draws", the answer should be: $8/9$ signifies that "you have not drawn only red balls in first 8 draws".

To determine probability


Let $z\in\mathbb{C}, z\ne0$, if $\left|z-\frac{1}{z}\right|=2$, then what is the maximum value of $|z| ?$(Solve preferably without using geometry)

Question: Let $z$ be a non-zero complex number such that $\left|z-\frac{1}{z}\right|=2$. What is the maximum value of $|z| ?$ (Solve preferably without using geometry.)
My attempt:
I tried to simplify things down by writing $\left|z-\frac{1}{z}\right|=2$ as $$\left(z-\frac 1z\right)\overline{\left(z-\frac 1z\right)}=\left(z-\frac 1z\right)\left(\overline z -\frac1{\overline z}\right)=4\implies |z|^2+\frac 1{|z|^2}+\frac{z}{\overline z}+\frac {\overline z}{z}=4.$$
But then, I am getting stuck at this step in the hope of proceeding with a breakthrough.
Then I tried using some standard inequalities:
$$|z|-\left|\frac 1z\right|\leq \left|z-\frac 1z\right|$$ and $$\left|z-\frac 1z\right|\leq |z|+\left|\frac 1z\right|$$
But this doesn't help much either.
Also, I tried writing $z=re^{i\theta}$ and neither does this make things easy. Till now, I am unable to find any major breakthrough. I am not interested in a geometric solution.
I think the link $|z-1/z|=2$ where $z$ is a complex number. How to find the greatest value of $|z|$ geometrically? asks for a geometrical solution specifically. But, I wanted a regular algebraic, approach to this problem. So, I am not sure if my post can be considered a duplicate or not as both of the posts, though focus on the same question, but the desired approach of the solution method (to the problem) , are different. (As, of now, I tried to make it specific in this post of mine to avoid further confusion)
Comment: Related: https://math.stackexchange.com/q/3173917/42969, https://math.stackexchange.com/q/1618068/42969
Comment: @MartinR Thanks! I indeed found a better approach to this problem on the linked page you suggested. But how did you locate the duplicate? Any special software you are using ?
Comment: @MartinR Though, I would add that the question specifically asked for a geometrical approach, while I wanted a regular, simple algebraic approach. So can it be called, a duplicate ?
Comment: I found those [with Approach0](https://math.meta.stackexchange.com/a/29267/42969). There are various answers in that Q&A (geometric and other approaches) to that it qualifies as a duplicate target IMO. Or [this](https://math.stackexchange.com/q/1618068/42969) which is the same task just with a slightly different parameter.
Comment: @MartinR I used Approach0 too, but couldn't find any. Maybe, the reason could be, that I typed out insufficient keywords. This happened to me a few days back as well. Yeah, there might be some which is a duplicate of this one. I am not sure, though.
Answer: Let $z=re^{i\theta}$, then you get
$$|r^2e^{2i\theta}-1|=2r$$
expand, we get
$$r^4-2r^2\cos2\theta+1=4r^2$$
Move terms,
$$\frac{1}{2}\left(r^2+\frac{1}{r^2}\right)=2+\cos2\theta$$
For LHS, the minimum value is $1$, when $r=1$, and we want $r$ to be as large as possible, apparently, $r_{max}=r_m>1$
For $r\in[1,\infty)$, the LHS is monotonic increasing, so the maximum value occures when the RHS reaches its maxima, so we get:
$$\frac{1}{2}\left(r_m^2+\frac{1}{r_m^2}\right)=2+1\Rightarrow r_m^2=3\pm2\sqrt2$$
Since $r_m>1$, we get
$$r_m=\sqrt{3+2\sqrt2}=\sqrt2+1$$
Comment: Let $f(r)=LHS$, If you start from the lowest point $r=1$, as $2+\cos\theta$ increases, $r$ can either increase or decrease, for example, $f(0.8)>f(1), f(1.2)>f(1)$, due to the fact $f$ is decreasing on $(0, 1)$ and increasing on $[1,\infty)$. So you need to first exclude the interval $(0, 1)$, so I said $r_m$ is obviously greater than $1$. So now you can only consider the interval $[1,\infty)$, and on this interval the function $f$ is increasing. So you just simply let the $RHS=3$ and solve for $r$
Comment: Certain parts of your answer still seems unclear to me. $(1)$ First of all, when you wrote, "For LHS, the minimum value is $1$, when $r=1$, and we want $r$ to be as large as possible, apparently, $r_{max}=r_m>1$", I understand, that the arithmetic mean of $(r^2,\frac 1{r^2}$ is minimum at $r=1,$ and for $|z|=r$ (when $z=re^{i\theta}$ to be maximum, the value of $r$ should be optimised (or better, be increased) so as to $|z|$ maximum. But I don't understand, why you claimed $r_{max}=r_m>1$, from the fact that "the arithmetic mean of $(r^2,\frac 1{r^2})$ is minimum at $r=1$ "? I think
Comment: it follows from the fact, that *As, the square root of a positive real is defined to be positive,* so, $r=\sqrt{r^2}\geq 0$. Now, $r\neq 0$ as then $|z|$ is minimum as $z$ is at origin. So, $r\gt 0$. The function $f(r)=\sqrt {r^2}$ is monotonically increasing when $r\in (0,\infty),$ $r$ variable cannot be particularly optimised to a fixed real number so that $r$ is maximum.
Comment: My question number $(2)$: The thing that $|z|$ depends only on $r$$\implies$ $\theta$ variable need not be optimised as $|z|$ does not depend on $\theta$. So, wouldn't the maximum value of $|z|\to\infty$ ?
Comment: when $r=1$, the LHS equals $1$, if you look at RHS, the range is $[1, 3]$, which means, as long as the LHS is within $[1, 3]$, you can always find an angle $\theta$ to make this equation hold. For example, if you move $r$ slightly larger than $1$, say $1+\delta$ due to the continuity of LHS, its value will be slightly larger than $1$, say $1.1$, and $1.1\in[1,3]$, so you can find $\theta$ to make this equation hold. Hence you find a candidate for $r_m$, which is $1+\delta$, so I say $r_m>1$.
Comment: Now, that's a nice logical argument you gave. So, what you did was you tried finding  a candidate so that RHS is $3$ ? But implicitly didn't you ise the fact, that as $2+\cos \theta$ increases $r$ increases as well ? If you used this implicitly, then I want to know, how did you know this fact was true ?
Comment: No, I just narrow down $r$ from $(0, \infty)$ into $[1, \infty)$, because on $[0, \infty)$, the LHS is not monotonic. But on $[1, \infty)$, the LHS is monotonic.
Comment: Did you comment this with reference to my previous comment? I am saying this, because I edited my earlier comment. I want to know, whether you used that fact, I stated. Because, it seems that it's used.
Comment: I write this again in hopes of avoiding unwanted confusions: It seems that you tried, finding a candidate for $r_m$ so that R.H.S becomes maximum,i.e when RHS is $3$. Now, as you suggest rightly, that L.H.S is monotonically increasing function in $[1,\infty)$ so, to make the range of L.H.S valid and maximum, the R.H.S should be optimised to maximum, isn't it? And R.H.S would be optimised only when , value of R.H.S is increased to the greatest possible value $3$ and hence, the maximum possible candidate for $r_m$ is when LHS increases to $3$ **because, as $r$ increases, LHS increases**
Comment: and the maximum possible $LHS$ is $3$ so, the permitted maximization of $r$ should be such that $LHS$ is $3$ and this is what you did ?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/145935/discussion-between-stephen-smith-and-mathfail).
Answer: As an alternative, following your first idea without exponential form
$$\left(z-\frac 1z\right)\overline{\left(z-\frac 1z\right)}=\left(z-\frac 1z\right)\left(\overline z -\frac1{\overline z}\right)=4\iff |z|^2+\frac 1{|z|^2}\color{red}-\frac{z}{\overline z}\color{red}-\frac {\overline z}{z}=4$$
we have
$$\iff |z|^2+\frac 1{|z|^2}-2=\frac{z}{\overline z}+\frac {\overline z}{z}+2\iff \left(|z|-\frac1{|z|}\right)^2=\frac{z^2}{|z|^2}+\frac {\overline z^2}{|z|^2}+2$$
$$\iff \left(|z|-\frac1{|z|}\right)^2=\left(\frac{z}{|z|}+\frac {\overline z}{|z|}\right)^2\iff \left(|z|-\frac1{|z|}\right)^2=\frac{(z+\bar z)^2}{|z|^2}$$
with $(z+\bar z)=2|z|\cos \theta$ then last identity is equivalent to
$$\left(|z|-\frac1{|z|}\right)^2 =4\cos^2 \theta$$
and $|z|$ is maximum for $\cos^2 \theta =1$ that is
$$\left(|z|-\frac1{|z|}\right)^2 =4\implies |z|_{\text{max}}=\sqrt 2 +1$$
Answer: Well here's a generalized formula for your question;
$$\left|z ± \frac{b}{z}\right|=a$$ where a and b are constants;
Maximum and minimum values of $|Z|$ are
$$max =  \frac{a+\sqrt{a^2+4|b|}}{2}$$
$$min =  \frac{-a+\sqrt{a^2+4|b|}}{2}$$
Comment: using triangular inequality


Some topological problem on open sets

Question: There is this statement in my topology notes, where it states that:
Denote $\mathbb{R}^n_{+}$ as the upper half surface in $\mathbb{R}^n,$ denoted by $\{(u_1,...,u_n)\in \mathbb{R}^n:u_n\ge0\}$. Then by the subspace topology, $\mathbb{R}^n_{+}$ is open if there exists a set $V^*$ such that $V=V^* \cap \mathbb{R}^n_{+}$, where $V^*\subset \mathbb{R}^n$. It is clear that if $V\subset \mathbb{R}^n_+,$ is a disjoint open subset from the subspace $\{u_n=0\},$ then $V$ is open $\mathbb{R}^n_+,$ iff V is open in $\mathbb{R}^n$
What I have trouble seeing here is I get the subspace topology part as it is directly following from the definition of subspace topology. However, I dont understand the last part where it mentions the iff part.
Could someone please explain why that is the case?
EDIT: Also what is the significance of the set being disjoint to $\{u_n=0\}$ in this case?
Comment: Let $V=\mathbb{R}^n_{+}$.  Then $V$ is certainly open in $\mathbb{R}^n_{+}$ but not in $\mathbb{R}^n$  Think about the upper half plane in  $\mathbb R^2$ if you you still don't see it.
Comment: Could you give me a numerical example? I think I get it, but still cant seem to be assured. For instance why is say $(1,2)$ open in $\mathbb{R}^2_{+}$, but not in $\mathbb{R}^2?$
Comment: What is the subspace $\{u_n=0\}$?.. I think you mean $\{(u_1,...,u_n):\exists j\;(u_j=0)\}.$ .. The letter $n$ is already in use, as the dimension.
Comment: I was not sure as I just took from the notes as written. Could you please clarify what would be the significance of being disjoint to that subspace?
Answer: Remember that in $\mathbb R^n$ a set is open if an only if it contains an $n$-dimensional open ball about each of its points.  Let's look at this in $\mathbb R^2$ and take $\mathbb R^2_+$ to be $\{(x,y)\in \mathbb R^2\mid y\ge0\},$ the upper half-plane.  Consider the square $S=\{(x,y)| 2>y>0, -1<x<1\}$  This is open, whether considered as a subset of $\mathbb R^2$ or as a subset of $\mathbb R^2_+.$
Now consider the square $\overline S=\{(x,y)| 2>y\ge0, -1<x<1\}.$  This is not an open subset of $\mathbb R^2,$ for it contains no neighborhoods of the points on the $x-$axis.  It is an open subset of $\mathbb R^2_+,$ however, because it is the intersection of $\mathbb R^2_+$ with $\{(x,y)| 2>y>-1, -1<x<1\}$ for instance.
Comment: Thank you for the help. But I am very confused with open sets atm, why doesn't it contain any neighbourhoods of the points on the $x$-axis?

Some topological problem on open sets


Login and get homepage content with a Bash script

Question: In some developments for drupal 7, I need connect with one user via a bash script then get the content of the connected homepage.
After several searches, my last try :
URL="https://www.mainsite.com/subsiteone/"

curl -s -f -o $output -H "Content-Type:application/xml" --insecure  $URL  -w "@formatsender.conf"  > ./test.txt

formid=$( grep 'input type="hidden" name="form_build_id"' $output | cut -d"=" -f4 | sed -e 's/"//g' | sed -e 's/\/>//g' )
echo $formid #show the good pofm id

curl --request POST ${URL} --data "name=usernameone%26pass=userpasswordone%26form_build_id=$formid%26form_id=user_login"

the last curl shows the content of the login page (not connected) without any error message.
I don't understand where is my mistake..
Answer: You might want to double checking your encoding or the headers that you're sending over that might cause the problem. I've found trying to do this with a pure Bash solution very fickle at times. Here's an example function I've used that will login into a D7 site on the /user page (an easier manner since every D7 install can be logged in from that path).
#!/bin/sh

# https://gist.github.com/cdown/1163649
#Usage: urlencode "string"
function urlencode() {
  old_lc_collate=$LC_COLLATE
  LC_COLLATE=C

  local length="${#1}"
  for (( i = 0; i < length; i++ )); do
    local c="${1:i:1}"
    case $c in
      [a-zA-Z0-9.~_-]) printf "$c" ;;
      *) printf '%%%02X' "'$c" ;;
    esac
  done

  LC_COLLATE=$old_lc_collate
}

#Usage: login "user" "pass"
function login() {
  URL=https://www.example.com/user
  name=$(urlencode "$1")
  pass=$(urlencode "$2")
  post_data="name=$name&pass=$pass"

  #Retrieve login page, login form, & input fields.
  login_page=$(curl -s -H "Content-Type:application/xml"  "$URL")
  login_form=$(echo $login_page | grep -o '<form[^>]*action="/user"[^>]*id="user-login"[^>]*>.*</form>')
  login_input=$(echo $login_form | grep -o '<input[^>]*/>')

  #Create Post Body
  while read -r input; do
    input_field=$(echo "$input" | sed -e 's/.*name="\([^"]*\)".*/\1/')
    if [[ $input_field != "name" && $input_field != "pass" ]]; then
      input_value=$(echo "$input" | sed -e 's/.*value="\([^"]*\)".*/\1/')
      input_field=$(urlencode "$input_field")
      input_value=$(urlencode "$input_value")
      post_data="$post_data&$input_field=$input_value"
    fi
  done <<< "$login_input"

  # Depending on your hosting environment you might need additional headers to make yourself not look like a bot
  user_agent="User-Agent:Mozilla/5.0 "
  referer="Referer:https://www.example.com/user"
  origin="Origin:https://www.example.com"
  content_type="Content-Type:application/x-www-form-urlencoded"

  # For further authenticated requests, you will need to parse output "Set-Cookie: ..." and set
  # the session cookie in a -H "Cookie: ..." option
  curl -s -L -H "$content_type" -H "$user_agent" -H "$referer" -H "$origin" --request POST "${URL}?destination=/" --data "$post_data"
}

login 'USER' 'PASS'

I've found logging into Drupal via Bash much easier with if you can work with a scripting language that has built in HTTP clients & parsers. Depending on your scenario, you might want to consider that if you need a more robust solution.
Comment: thanks you ! I tested this script and I replace the 'USER' 'PASS' and 'URL' variables. But the curl returns nothing :/
Comment: I print the curl command before his execution. I didn't notice any problem ... I have :   curl -s -L -H Content-Type:application/x-www-form-urlencoded -H User-Agent:Mozilla/5.0  -H Referer:https://www.mainsite.com/subsiteone/user -H Origin:https://www.mainsite.com/subsiteone --request POST https://www.mainsite.com/subsiteone?destination=/ --data "name=usernameone&pass=userpasswordone&="
Comment: When I remove the '-H Refere:..." parameter, curl return a page ! but this is (again..) the login page not connected
Comment: I don't want to turn this is to a long debug convo so I'll mention 2 things. 1: Adjust the curl options (e.g. `-v` `-s`) to ensure the request is being made. 2: Make sure that a new session is created; check the `sessions` table or set the `-v` flag to check for the `Set-Cookie:` header; you can parse out the session key and added it to subsequent curl requests (e.g. `-H 'Cookie: SSESS = ;`) to request any page as an authenticated user.
Answer: When you post the user credentials to Drupal, I am pretty sure you need to POST it to /user/login and not to the front page.
Then after loggin in, Drupal's default behavior is to redirect the user to /user, not the front page. You might succeed appending ?destination=<front> to the request path, use Rules to redirect the user after login, or use Login Destination to make sure the site will present you the front page.
You might want to try something like this for your last line:
curl --request POST ${URL}/user/login?destination=<front> --data "name=usernameone%26pass=userpasswordone%26form_id=user_login"

I believe form_build_id is not mandatory, but I am not really sure so you might have to add that. I omitted it in the example.
Comment: It might be due to that ${URL} ends with a slash (/) as well, so the url becomes `https://www.mainsite.com/subsiteone//user/login?destination=`. Try removing one slash. Also check if `https://www.mainsite.com/subsiteone/user/login` in fact shows the login page. Finally, perhaps the ampersands in the query string don't have to be URL-encoded and you can use `name=usernameone&pass=userpasswordone&form_id=user_login`. But these are just guesses.
Comment: This is correct: Maybe the front page contains the login block, but the correct page to submit the login form is not that. Also, I assume Drupal needs to know which submission button has been pressed.
Comment: Thanks for your answer ! I tested with "curl --request POST ${URL}/user/login?destination= --data "name=usernameone%26pass=userpasswordone%26form_id=user_login"" or with the form_build_id but the lhis curl always return me the login page without any error message :/


How do you predict probabilities for specific data in logistic regressions using R?

Question: Consider the Challenger-Disaster:
Temp <- c(66,67,68,70,72,75,76,79,53,58,70,75,67,67,69,70,73,76,78,81,57,63,70)
Fail <- factor(c(0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1))
shuttle <- data.frame(Temp, Fail)
colnames(shuttle) <- c("Temp", "Fail")

Now I can fit a logistic model which will explain the "Fail" of O-ring seals by Temperature:
fit <- glm(Fail~Temp,data=shuttle, family=binomial); fit

The R output looks like this:
 Call:  glm(formula = Ausfall ~ Temp, family = binomial, data =
 shuttle)

 Coefficients: (Intercept)         Temp
     15.0429      -0.2322

 Degrees of Freedom: 22 Total (i.e. Null);  21 Residual Null Deviance:
 28.27  Residual Deviance: 20.32    AIC: 24.32

Questions

In general, how do you predict probabilities for specific data in logistic regressions using R?
Or specifically, what is the command to calculate the probability of a "Fail" if temperature is at 37°? (which it was in the night before the Challenger disaster).

I thought it would be something like this:
predict(fit, Temp=37)

but it won't give me "0.9984243" (which I calculated myself with:
exp(15.0429 + (37*(-0.2322))) / 1+ exp(15.0429 + (37*(-0.2322)))

The method predict returns a matrix of numbers that makes no sense to me.
Answer: how about
?predict.glm

or, more specifically
predict(fit, data.frame(Temp=37), type="response")

Comment: thanks for your time and the url...
However, I started a new request on ordinal regression here http://stats.stackexchange.com/questions/65375/how-to-predict-rank-in-ordinal-regression-using-r providing my data...
Comment: ähh? this works! So, my fault was to just type "temp=37" and not "data.frame(Temp=37)" ?!
Stupid me...
Thx, dude! Do you know how to modify the command if the outcome is not binary (YES/NO) but ordinal (A/B/C/D/E/F) ?
Comment: I don't think `glm` can handle ordered regression, but you may have a look at http://www.ats.ucla.edu/stat/r/dae/ologit.htm or the web in general


How can I set a different color for text and background of canvas HTML?

Question: I'm using canvas to create a dynamic Wheel of fortune. Any time I add a new item, it recalculates the spaces evenly. I was able to make it happen using canvas.  I know that canvas.fillStyle = somecolor; sets the color I want to the slice that is being created.
I also wanted to put some text inside each slice. However, I can't figure a way to make canvas draw a text with a different color from the color of the slice. Is that even possible?
Here's what I'm doing
  const drawSlice = useCallback((deg: number, color: string, text:string) => {
    if (!canvasRef.current) {
        return;
      }
      const canvas: HTMLCanvasElement = canvasRef.current;
      const ctx = canvas.getContext("2d");

      const width = canvas.width;
      const center = width/2;
      const sliceDeg = 360 / wheelItems.length;

      if (ctx) {
        ctx.beginPath();
        ctx.fillStyle = color;
        ctx.fillText(text, center, deg2rad(deg));

        ctx.moveTo(center, center);
        ctx.arc(center, center, width / 2, deg2rad(deg), deg2rad(deg + sliceDeg));
        ctx.lineTo(center, center);
        ctx.fill();

      }
  },[wheelItems.length])

Answer: If I understand your problem correctly, you might want to change ctx.fillStyle between the moment you draw the text and the moment you draw the slice.
if (ctx) {
    ctx.beginPath();
    ctx.fillStyle = color;
    ctx.fillText(text, center, deg2rad(deg));

    // here :
    ctx.fillStyle = color2;
    ctx.moveTo(center, center);
    ctx.arc(center, center, width / 2, deg2rad(deg), deg2rad(deg + sliceDeg));
    ctx.lineTo(center, center);
    ctx.fill();
}

You can change ctx.fillStyle whenever you want, as many times as you want.
Comment: That worked! Thanks! I noticed that the text using 'fillText' is a little bit blurry, any idea what could be causing it?
Comment: If your text is blurry, it is probably too small; try using a bigger/bolder font using `ctx.font = "18px sans-serif";` or `ctx.font = "bold 14px sans-serif";` before calling fillText.