Recommended way to build ruby c-extension for testing

Question: I was building a rubygem by using
gem build $gemname.gemspec && gem install $gemname-0.0.1.gem

However, this doesn't seem to be the best way to test the gem, since it moves it out of the local environment and into the rubygems paths.
Is the recommendation to build the gem using
cd ext/$gemname && ruby extconf.rb && make

? Or is there a better practice?
Answer: I'm guessing a Rakefile like the below will also work (and is easier than the commands above). However, it's not obvious that this is necessary for testing.
require 'rake/testtask'
require 'rake/clean'

NAME = 'hola'

# rule to build the extension: this says
# that the extension should be rebuilt
# after any change to the files in ext
file "lib/#{NAME}/#{NAME}.so" =>
    Dir.glob("ext/#{NAME}/*{.rb,.c}") do
  Dir.chdir("ext/#{NAME}") do
    # this does essentially the same thing
    # as what RubyGems does
    ruby "extconf.rb"
    sh "make"
  end
  cp "ext/#{NAME}/#{NAME}.so", "lib/#{NAME}"
end

# make the :test task depend on the shared
# object, so it will be built automatically
# before running the tests
task :test => "lib/#{NAME}/#{NAME}.so"

# use 'rake clean' and 'rake clobber' to
# easily delete generated files
CLEAN.include('ext/**/*{.o,.log,.so}')
CLEAN.include('ext/**/Makefile')
CLOBBER.include('lib/**/*.so')

# the same as before
Rake::TestTask.new do |t|
  t.libs << 'test'
end

desc "Run tests"
task :default => :test


How to overlay only the needed image?

Question: I have two images.
Image 1:

Image 2:

Both the images have the same resolution. I want to overlay the second image on the first image.
This is what I tried:
from PIL import Image

img1 = Image.open("D:\\obj1__0.png")
img1 = img1.convert("RGBA")
img1 = img1.resize((640,360))

img2 = Image.open('D:\\Renderforest_Watermark.png')
img2 = img2.convert("RGBA")
img2 = img2.resize((640,360))

new_img = Image.blend(img1,img2,0.7)
new_img.save("D:\\Final.png")

Output:

My Question: How do I overlay image 2 on image 1 such that only the watermark is overlaid?
P.S: I already searched for this on Stack Overflow, but couldn't find any answers.
Comment: Does this answer your question? [PIL : PNG image as watermark for a JPG image](https://stackoverflow.com/questions/43708681/pil-png-image-as-watermark-for-a-jpg-image)
Comment: @RandomDavis Nope. It doesn't work for me.
Comment: Can you clarify what didn't work about it? Does your overlay image not have transparency? Did you try making the background transparent?
Answer: Your overlay image is incorrectly formed. It should be transparent where it is white. It has no transparency, so it isn't see-through. I can only suggest to make a synthetic alpha channel by guessing that it should be transparent where the overlay image is white:
#!/usr/bin/env python3

from PIL import Image

# Set a common size
size = (640, 360)

# Load background and overlay, removing the pointless alpha channel and resizing to a common size
bg = Image.open('background.png').convert('RGB').resize(size)
overlay = Image.open('overlay.png').convert('RGB').resize(size)

# Try and invent a mask by making white pixels transparent
mask = overlay.convert('L')
mask = mask.point(lambda p: 255 if p < 225 else 0)

# Paste overlay onto background only where the mask is, then save
bg.paste(overlay, None, mask)
bg.save('result.png')

If your image did have an alpha channel, you would avoid deleting the original alpha channel and open it like this instead:
overlay = Image.open('overlay.png').resize(size)

then delete these lines:
# Try and invent a mask by making white pixels transparent
mask = overlay.convert('L')
mask = mask.point(lambda p: 255 if p < 225 else 0)

then change the line after the above to:
# Paste overlay onto background only where the mask is, then save
bg.paste(overlay, None, overlay)

Keywords: Image processing, PIL, Pillow, overlay, watermark, transparent, alpha.
Comment: Thanks! It works! Could you pls explain in detail what do these two lines do:

```mask = overlay.convert('L')
mask = mask.point(lambda p: 255 if p < 225 else 0)```

How to overlay only the needed image?


Every continuous real valued function an be uniformly approximated by polynomial in these two functions

Question: Prove that every continuous real valued function on the square $[0,1] \times [0,1]$ can be uniformly approximated by polynomials in the functions $f(x,y)=x+e^y$ and $g(x,y)=x-e^y$.
To me, this looks like a Weierstrass approximation problem.
Let $f$ be a continuous real valued function on the square $[0,1] \times [0,1]$.
Basically we want to to find a polynomial in the functions $p(x)$ so that $|f(x)-p(x)|< \epsilon$.
But I'm not sure what it means by "polynomials in the functions".
Any help will be appreciated!
Comment: "Polynomials in $f$ and $g$" are linear combinations of $f^m g^n$ for nonnegative integers $m$ and $n$.  Hint: Stone-Weierstrass theorem.
Answer: As you write, we can apply the Stone-Weierstrass theorem. A polynomial in two variables $u,v$ has the form
$$p(u,v) = \sum_{i,j=0}^n a_{ij}u^iv^j$$
In your question we have to consider all polymials with $u = f(x,y)$ and $v = g(x,y)$, i.e. all functions in the two variables $x,y$ having the form
$$\phi(x,y) = p(f(x,y), g(x,y)) .$$
The set of these functions is clearly a subalgebra of $C([0,1] \times [0,1], \mathbb R)$. It contains all constant functions (take the constant polynomials $p(u,v) = a_{00}$). It is also separates points:
Let $(x,y), (x',y')$ be two distinct points of $[0,1]^2$. Then $(u,v) = (f(x,y), g(x,y))$ and $(u',v') =(f(x',y'), g(x',y'))$ are two distinct points of $\mathbb R^2$. In fact, $f(x,y) = f(x',y')$ and $g(x,y) = g(x',y')$ means that $x + e^y = x' + e^{y'}$ and $x - e^y = x' - e^{y'}$. Adding these equations gives $2x = 2x'$, i.e. $x = x'$. This implies $e^y = e^{y'}$, i.e. $y = y'$.
Therefore it remains to show that the polynomials $p(u,v)$ separate the points of $\mathbb R^2$. But if $(u,v) \ne (u',v')$, then $u \ne u'$ or $v \ne v'$. We only consider the case $u \ne u'$, the other case is treated similarly. Taking $p(u,v) = u$ gives $p(u,v) \ne p(u',v')$.


Growth rate of a function

Question: I am having some trouble determining the growth rate of the function $m(n)=\inf\{m: \frac{1}{2^m}\le \frac{1}{n} m^{3/2}\}$. This comes up in problem 2.2.8 in Durrett's probability book. Essentially, I'm having some very rough heuristics (and probably incorrect) that says $m(n)$ grows like $\log_2(n)$. If I can prove (or see) this, I can solve the problem in the book. A general method would be desirable since I'm interested learning the techniques. However, any insight would be helpful!
Comment: Set $n=2^m m^{3/2}=2^{m+\frac{3}{2}\log_2m}$. Solving for $m$ gives:$m+\frac{3}{2}\log_2m=\log_2 n$. Now, the $\log m$ term is dominated by the linear term $m$, for large values of $n$, thus can be neglected. Hence as you said, the growth rate is $\log_2 n$
Answer: Your heuristics are in fact correct.  One heuristic is to isolate the main term involving the unknown variable, which in this case is $2^m$.  Solving, we get $2^m \ge \frac{n}{m^{3/2}}$.
To solve for $m$, we take logarithms, which gives $m \ge \log_2 n - \frac32 \log_2 m$.  Since $\log_2 m$ is insignificant compared to $m$, we can ignore the $\log_2 m$ term, which shows $m \sim \log_2 n$, as you suspected.
For more accuracy, we can then feed this approximation into the $\log_2 m$ term we earlier ignored, finding $m \gtrapprox \log_2 n - \frac32 \log_2 \log_2 n$.
More formally, because $\log_2 n$ was only an approximation of $m$, we would incur a slight error when plugging that into $\log_2 m$.  We should instead substitute $m = (1 - o(1)) \log_2 n$ (it is easy to see we overestimate $m$ before), which gives $m \ge \log_2 n - \frac32 \log_2 \left( (1 - o(1)) \log_2 n \right) = \log_2 n - \frac32 \log_2 (1 - o(1)) - \frac32 \log_2 \log_2 n = \log_2 n - \frac32 \log_2 \log_2 n + o(1)$.
Once you have this estimate, you can always substitute it back into the original inequality to confirm its accuracy.
Answer: $m(n)
=\inf\{m: \frac{1}{2^m}\le \frac{1}{n} m^{3/2}\}
$
If
$\frac{1}{2^m}
\le \frac{1}{n} m^{3/2}
$,
taking the reciprocal gives us
$2^m
\ge n/ m^{3/2}
$,
and
taking logs gives
$m \log 2
\ge \log n-\frac32 \log m
$
or
$m \log 2+\frac32 \log m
\ge \log n
$.
So we want to see
what this tells us
about $m$
in terms of $n$.
If
$m \ge \dfrac{\log n}{\log 2}
=\log_2 n
$,
this is certainly true.
Therefore
$m(n)
\le \log_2 n
$.
Suppose $m$
is slightly less than
$\log_2 n$,
say
$m = \log_2 n -c$
where $c > 0$.
Then
$\begin{array}\\
m \log 2+\frac32 \log m
&=(\log_2 n -c) \log 2+\frac32 \log (\log_2 n -c)\\
&=\log n -c\log 2+\frac32 \log (\log_2 n -c)\\
&=\log n -c\log 2+\frac32 \log (\log_2 n -c)\\
\end{array}
$
and this will be
$> \log n$
for large enough $n$
for any $c$.
So we have to find a smaller $m$.
Suppose
$m = (1-c)\log_2 n $
where $c > 0$.
Then
$\begin{array}\\
m \log 2+\frac32 \log m
&=(1-c)\log_2 n  \log 2+\frac32 \log ((1-c)\log_2 n )\\
&=(1-c)\log n+\frac32 (\log(1-c)+\log (\log_2 n))\\
&=\log n+\frac32 \log(1-c)-c\log_2 n+\frac32\log (\log_2 n))\\
&< \log n
\qquad\text{for large enough }n\\
\end{array}
$
since
$\dfrac{\log \log n}{\log n}
\to 0
$
as
$n \to \infty
$.
Therefore
$m(n) > (1-c)\log_2 n
$
for any $c>0$
for large enough $n$
(i.e., $n > n(c)$).
The next step,
which I will not do,
would be to find a $f(n)$
such that
$m = \log_2 n -f(n)$
satisfies
$m \log 2+\frac32 \log m
< \log n
$
and
$\dfrac{f(n)}{\log n}
\to 0
$.
Based on the
$\log\log n$
term,
I would guess that
$f(n) = a \log\log n$
would do
for a large enough $a$.
The algebra would be
trickier,
so I will leave it this,
having showed that
$1-c
\lt \dfrac{m(n)}{\log_2 n}
\le 1
$
for any
$c > 0$.
Comment: If my calculation is correct, $f(n) = \frac{3}{2}\log_2(n)\log_2(n)$ would work fine. Thanks for the clear explanation!

Growth rate of a function


Let $n=4\cdot p^t+1.$ Is $r_k=4$ for some $1\le k<n$ for an arbitrary prime $p\ge 5$ and integer $t\ge1$

Question: Let $n=4\cdot p^t+1$, $t\ge1$ and $p\ge5$ prime.
Define sequence $R$ as follows;
$r_0=4,$ $r_{k+1}\equiv r_k^2-2\pmod n$, $0\le r_k<n$ for $k\ge1$.
It appears that whenever $n$ is prime,  $r_k=4$ for some  positive integer $k<n$. How does one go about proving this result for all primes $p\ge5$ and positive integers $t$? Are there any counter examples? (I have done a search for all $p<10^6$ with $t=1,2$. No counter examples.)
Answer: Your conjecture is true
Any time one sees recurrence sequences like $r_0=4,r_{k+1}=r_{k}^2-2$, along with something to do with primality, the first thing one should do is think that the recurrence sequence is representing some multiplication in some group mod the prime. In this case this is true:
Let $w=2+\sqrt{3}$ and $\overline{w}=2-\sqrt{3}$. Then using the fact that
$w^{2^0}+\overline{w}^{2^0}=2+\sqrt{3}+2-\sqrt{3}=4$
and
$w\overline{w}=1$
we can easily deduce that $r_n=w^{2^n}+\overline{w}^{2^n}$. This recurrence $r_n$ is actually the same one used in the Lucas Lehmer test.
Now for some group theory. If $n>3$ is prime (for any $n$), then $(\mathbb{Z}/n\mathbb{Z})[x]/(x^2-3)$ is a group (this is simply notation for the set of algebraic integers $a+b\sqrt{3},a,b\in\mathbb{Z}/N\mathbb{Z}$, with normal complex multiplication, all modulo $N$). In this case, $(n/3)=-1$, so we can note that
$(2+\sqrt{3})^n\equiv 2^n+\sqrt{3}^n\equiv 2-\sqrt{3}\mod n$ by the Binomial Theorem in finite fields.
Thus $(2+\sqrt{3})^{n+1}\equiv (2+\sqrt{3})(2-\sqrt{3})\equiv 1\mod n$. And we can similarly see that $\overline{w}^{n+1}\equiv 1\mod n$. This means that $w^{{n+2}}+\overline{w}^{n+2}\equiv w+\overline{w}\equiv 4\mod n$. For certain reasons that will soon become clear (even vs odd), we have to take this a step further.
Similar to the proof of LL in the link above, define $\sigma=(6+2\sqrt{3})$ and $\overline{\sigma}=(6-2\sqrt{3})$. Notice that $\sigma^2/24=w$. But then by the binomial theorem in finite fields,
$w^{\frac{n+1}{2}}=\sigma^{n+1}/24^{\frac{n+1}{2}}=\sigma\sigma^{n}/24^{\frac{n+1}{2}}=\sigma\overline{\sigma}/(24\cdot 24^{\frac{n-1}{2}})\mod n$
From @mode_er's answer, we see that $(24/n)=1$, and we can directly compute that $\sigma\overline{\sigma}=24$, and thus
$w^{\frac{n+1}{2}}\equiv 1\mod n$, and symmetrically $\overline{w}^{\frac{n+1}{2}}\equiv 1\mod n$.
But $n=4p^t+1$, $n+1=4p^t+2=2(2p^t+1)$ only has one factor of $2$. Thus $\frac{n+1}{2}$ is odd. This is important because since $(n+1)/2$ is odd, $(n+1)/2|2^{\phi((n+1)/2)}-1$ (with $\phi(\bullet)$ Euler's totient function), and noting that $0<\phi((n+1)/2)<n$, we have that $m(n+1)/2=2^{j}-1$ for some $0<j<n$.
Thus $w^{2^j-1}=\overline{w}^{2^j-1}\equiv w^{m(n+1)/2}\equiv \overline{w}^{m(n+1)/2}\equiv 1^m=1\mod n$ and arguing similarly to above,
$r_j=w^{2^j}+\overline{w}^{{2^j}}=w^{2^j-1}w+\overline{w}^{2^j-1}\overline{w}\equiv w+\overline{w}\equiv 4\mod n$, with $0<j<n$, as desired. In fact due to construction with $\phi(\bullet)$ we can say $0<j<(n+1)/2$, a tighter bound.

Note that we only used part of the fact that $n=4p^t+1$ (although this form was slightly more important than I expected), and in fact this holds for any prime $n$, $n>3$ such that $n+1\equiv 2\mod 4$ (only one factor of $2$) such that $(2/n)=(3/n)=-1$.
Answer: I can't seem to find a solution using only elementary number theory. From what I did find, it's obvious that we need
$$r_{k-1}^2-2\equiv 4 \text{ mod } n$$
$$r_{k-1}^2\equiv 6 \text{ mod } n$$
By the Law of Quadratic Reciprocity
$$\left( \frac{2}{n} \right) \equiv (-1)^\frac{n^2-1}{8}\equiv (-1)^{\frac{(4p^k)(4p^k+2)}{8}}\equiv (-1)^{(p^k)(2*p^k+1)}=-1 $$
Additionally,
$$\left( \frac{3}{n} \right) =-1 $$ since by the Law of Quadratic Reciprocity,
$$\left( \frac{3}{n} \right)\left( \frac{n}{3} \right) =(-1)^{\frac{n-1}{2}\frac{3-1}{2}} = (-1)^{2*p^k}=1$$ and
$p \text{ mod } 3 \equiv 1,2$
$p^k \text{ mod } 3 \equiv 1,2$
$n \equiv 4p^k+1 \text{ mod } 3 \equiv 2,0$
Since $2$ is a quadratic nonresidue mod $3$, and n is defined as a prime greater than or equal to 5, then n cannot be a multiple of 3. Therefore,
$$\left( \frac{n}{3} \right)=-1$$
Since the Legendre Function is multiplicative, we get
$$\left( \frac{6}{n} \right)=\left( \frac{3}{n} \right)\left( \frac{2}{n} \right)=1$$, and so 6 is a quadratic residue mod n. This implies that it is possible for the number 4 to be reached again in a sequence like that. From there however, I can't seem to find any literature on how to continue, other than references to the Pisano Period (which has a derivation referring to algebraic number theory) and a closed-form for the recursion $r_k=r_{k-1}^2-2$ in the page for "Proof of correctness" in the Wikipedia page for the Lucas Lehmer primality test, which introduces the same recursion.
Comment: I believe what you have shown is that $6$ is a quadratic residue modulo $n$ and so the congruence $x^2 \equiv 6 \pmod n$ has two distinct solutions $x_1$ and $x_2 = - x_1$. However this alone does not prove that the number 4 can be reached again in the sequence $R$. You need to further show that either $x_1$ or $x_2$ is part of  the sequence $R$. If you can reach $x_1$ or $x_2$ then you can reach 4. A re-statement of the question would then be;  Is $x_1$ or $x_2$ always part of sequence $R$?
Comment: @ASP that is what I originally sought out to prove, but I couldn't find the resources to prove it without dealing with algebraic number theory, a subject I am not comfortable with. Finding the closed form of the sequence (as shown in the Wikipedia page for the Lucas Lehmer test) and then applying a similar method to how they found the Pisano Period (since the Fibonacci sequence is very similarly structured to the sequence shown here) would likely help you find the period of the function, and that might lead to finding if 4 is in every repetition


Extract files from ploop disk image

Question: I have ploop disk image created by dumping an OpenVZ container. There are two files:
791     DiskDescriptor.xml
2.4G    root.hdd

Is there any way to extract the whole root file system from there on a non-OpenVZ machine?
Answer: You don't need to spin up the container, you can simply mount the filesystem image according the manual https://openvz.org/Man/ploop.8

ploop mount
  [-r] [-F] [-d device] [-m mount_point] [-o mount_options] [-t fstype] [-u uuid] DiskDescriptor.xml
Comment: Thanks, but it appears that `ploop` works on OpenVZ hosts only. On Ubuntu 15.10 I am getting `Error in ploop_getdevice (ploop.c:874): Can't open /proc/vz/ploop_minor`. I've edited the question so that it is clear no OpenVZ available.
Answer: You can use ploop_userspace.
./ploop_userspace root.hdd &
mount -r -o noload /dev/nbd0p1 /mnt

Comment: Open an issue here: https://github.com/FastVPSEestiOu/ploop_userspace/issues
Comment: I got this message  `Unexpected ploop version`

Extract files from ploop disk image


Trocar a cor do input color

Question: Eu preciso de uma ajuda muito importante, tenho um input color com uma cor e um campo text.
Como eu poderia trocar a cor do input(color) usando o campo text.
Answer: Esperando pelo evento input no campo de texto.
Basta pegar o valor da entrada de texto e aplicar como valor do campo de cor:

(function(){

  var text  = document.querySelector('input[type=text]'),
      color = document.querySelector('input[type=color]');

  text.addEventListener('input', function(){
    color.value = this.value;
  });

})();
<input type='text' placeholder='#RRGGBB'>
<input type='color'>
Comment: S mas n esta trocando o valor ?
Comment: Como ativaria a função para executar o codigo ?
Comment: @Victor A função já está sendo executada
Comment: @Victor Se você quiser que o valor do `"input[type=text]"` se atualize de acordo com o `"input[type=color]"` precisa adicionar um evento `"input"` para o `"input[type=color]"`, então atualizar o valor do `"input[type=text]"` com o valor do `"input[type=color]"` no escopo do evento. O evento `"input"` é, portanto, não suportado por navegadores velhos, mas cabe. Também é possível detectar se ele foi alterado com `requestAnimationFrame` e timers, algo serve de polyfill. Isso é como eu detectaria o evento `"input"`: `document.createElement('input').oninput === null`.
Answer: Uma resposta simples como a pergunta:
Nesse código o único que fiz foi atualizar o valor do "input[type=color]" usando os eventos oncut, onkeyup, ... do HTMLInputElement.
Eu adicionei algumas coisas extras.

var hexColorInput = document.getElementById('hex_input'),
    colorSelector = document.getElementById('color_selector');

var updateHex ;

(updateHex = function () {
    hexColorInput.value = colorSelector.value;
})();

colorSelector.addEventListener('input', updateHex);

function updateSelector() {
    var val = hexColorInput.value;
    // adiciona o '#'
    if (val.charAt(0) !== '#') val = '#' + val;

    // expande uma cor desse tamanho: fff
    if (val.length === 4) {
        var red = val.charAt(1);
        red += red;
        var green = val.charAt(2);
        green += green;
        var blue = val.charAt(3);
        blue += blue;

        val = '#' + red + green + blue;
    }

    colorSelector.value = val;
}

['cut', 'keyup', 'paste'].forEach(function(evt) {
    hexColorInput.addEventListener(evt, updateSelector);
});
<input id="color_selector" type="color"/>
<input id="hex_input" type="text">
Comment: Amigo....eu nunca pensaria nisso.......Estou trabalhando com funções simples baseadas no getElementById e value....
Comment:

////////JS:
function trocaCorUm(){document.getElementById("legendaCorUm").value=document.getElementById("corUm").value; }
////FIM JS
Esse trocar cor é para quando eu colocar a cor no input, exibir o cod #Hex no input text abaixo
Comment: @Victor Você está tentando me dizer algo?

Trocar a cor do input color


Use an existing EBS volume with the Docker REX-Ray plugin on ECS

Question: I'm using Terraform to create an ECS Cluster, a task definition and a service.
For task definition, the piece of code looks like this:
resource "aws_ecs_task_definition" "postgres" {
  container_definitions    = ...
  family                   = "Postgres"
  requires_compatibilities = ["EC2"]
  network_mode             = "bridge"

  volume {
    name = "PreCreatedEBSVolume"

    docker_volume_configuration {
      scope         = "task"
      autoprovision = false
      driver        = "rexray/ebs"
    }
  }
}

I specifically set autoprovision to false to make sure a new volume is not created. But still, when the service runs, a new volume is created with 16GiB (which I assume is the default size) and used instead of using the "PreCreatedEBSVolume".
I check the docker volume ls in the instance and sure enough, I see the EBS volumes listed. And if I run a new instance with this volume mounted, it's mounting as expected.
Is there a way I can make REX-Ray use existing block storage?
Comment: How do you make rexray use an existing volume? I tried several things ranging from putting in the volume id to the Name tag of the volume into `name` but none of it worked
Answer: I found the issue.
The problem is the "scope" property. The docs had the following to say:

The scope for the Docker volume that determines its lifecycle. Docker volumes that are scoped to a task are automatically provisioned when the task starts and destroyed when the task stops. Docker volumes that are scoped as shared persist after the task stops.

So, I just had to change it to "shared" from "task" to make it use the existing EBS volume.
Comment: Could you please share your config, as this is not working for me. How do you specify the existing EBS volume? I tried volumeID as well as naming the docker volume the same as the Name tag of the EBS volume. Neither worked.
Comment: I have the same problem.` Error: No such volume`
Answer: Problem with rexray/ebs is that it selects existing EBS volume only when it is in same AZ as instance. So in our case we needed to pin specific instances to specific AZ in order to use this driver properly.
Our setup was 6 instances in 3 different AZ for better availability and every instance had its own EBS, but after instance restart it went to random AZ and it was 2 out of 3 it failed to find the volume. Error message in syslogs was not very informative.
Other then that plugin does what it should.
Answer: Following is the task definition example that answers the question as well as gives extra details if you want to know how to create a gp3 volume with IOPS and encryption specified:
resource "aws_ecs_task_definition" "postgres" {
  container_definitions    = ...
  family                   = "Postgres"
  requires_compatibilities = ["EC2"]
  network_mode             = "bridge"

  volume {
    name = "PreCreatedEBSVolume"

    docker_volume_configuration {
      scope         = "shared"
      autoprovision = false
      driver        = "rexray/ebs"
      driver_opts = {
        volumetype    = "gp3"
        size          = 40
        iops          = 3000
        encrypted     = true
        encryptionkey = "arn:aws:kms:us-east-1:111111111111:key/11111111-1111-1111-1111-11111111"
      }
    }
  }
}


Solve $a \equiv b^c \pmod {d}$ for $c$

Question: I'm trying to solve the following equation for $c$.
$$a \equiv b^c \pmod {d}$$
I'm given arbitrarily large numbers ($a$, $b$, and $d$ to solve for c, examples below), but it's just not feasible to iterate through every possible $c$ and check (using the GNU Multiple Precision Arithmetic Library) the congruency. Is it possible to solve the equation for $c$ or limit my search space?
$a = 4.557304... \times 10^{308}$
$b = 201527$
$c = 1.9 \times 10^{38}$
$d = 1.569203... \times 10^{309}$
Comment: Looks a lot like double/single precision floating point. If you use multi-precision integers it is a [discrete_logarithm problem](https://en.wikipedia.org/wiki/Discrete_logarithm#Modular_arithmetic)
Comment: @gammatester I shortened the numbers to floating point, but I'm actually given the entire 308 digit integer. Unless I'm misunderstanding what you're trying to say.
Answer: This is called a discrete logarithm. Computationally, it isn't as easy as a standard logarithm, and is time-complexity wise likely similar to factorization. There's more information on the Wikipedia page about actually calculating it, but it's, generally speaking, computationally "hard".

Solve $a \equiv b^c \pmod {d}$ for $c$


C# if statement syntax with list of objects

Question: I have a list of objects, called Attributes, that, essentially, i need to do the following in C#
<pseudocode>
if (list.Contains(Attribute where getName() == "owner"))
{
   do stuff
}
</pseudocode>

the problem I'm having is the nested bracket bit of the if - "Attribute where getName() == "owner". This is my code - it doesn't work, obviously, but most of the if should be right, it's just getting that i need to do the bit in forward slashes and i don't know how.
if (attributes.Contains(Attribute /where/ attribute.getName() == "Owner"))
    {
        string value = attr.getValue();
        value = value.Replace(domain, "");
        user = value;
        UserExists(value);
    }

I'm probably being dense, but I had to restart 3 days development to change everything to using Attribute objects, so my brain is rather destroyed. Sorry.
Answer: If you are using a version of .NET that supports LINQ (3.5 or higher), try
if(attributes.Any(attribute=>attribute.getName()=="Owner"))
{
    do stuff
}

This has the nice advantage of being fairly readable by whoever has to maintain this code.
Answer: if(list.Exists(e=>e.getName() == "owner")) {
   //yup
}

Answer: You can use LINQ to objects
if (attributes.Count(a => a.getName() == "Owner") > 0)

Comment: Please use `attributes.Any` instead of `attributes.Count` because count loops through the whole collection and Any just returns true when one attribute is found -> increases performance
Comment: `Count()` shouldn't be used if you're testing if it has *at least one*. Instead, `Any()` should be used as this will move the enumerator to the first element (`Count()` will potentially iterate through all of them).
Answer: Without LINQ!:
if (list.Exists(delegate(Attribute a) { return a.GetName() == "Owner"; }))

Answer: are you using .NET 3.5 or above, if so and presuming that 'attributes' is derived from IEnumerable, you could do the following :
if (attributes.Any(attrib=>attrib.GetName() == "Owner"))
{
    //Do code here...
}

Answer: Please have a look:
var filteredAttributes = from attribute in Attributes
                         where string.Compare(attribute.getName() ,"Owner",true)==0
                         select attribute;

foreach(var attribute in filteredAttributes)
{
          string value = attr.getValue();
                value = value.Replace(domain, "");
                user = value;
                UserExists(value);

}

Answer: You can use LINQ to separate out the required attributes...
IEnumerable<TAttribute> ownerAttributes =
    attributes.Where(attribute => attribute.getName() == "Owner");

... and then iterate over those attributes, applying the relevant logic...
foreach(TAttribute attribute in ownerAttributes)
{
    // Do stuff...
}

Answer: Ok, i worked it out, I found a much better way to do it:
for (int i = 0; i < attributes.Count; i++)
{
    if (attributes[i].getName() == "Owner")
    {
       string value = attributes[i].getValue();
       value = value.Replace(domain, "");
       user = value;
       UserExists(value);
    }
}

which makes more sense, and actually works.
Comment: This is not doing what you originally stated, this will action every attribute in the list that matches "Owner", your original pseudo code only tested for the condtion, then actioned some code if that condition was met...
Comment: It just needs a break; after UserExists(value);
Comment: Even with the break, the code seems less clear with a loop than with an existance test in an if statement
Comment: I realise it's a rather awful way to do what I want, but I'm far too new to C#, and in honesty, programming in general, to know, well, anything. This gets me the result I want, and it works, and i understand it, while other methods on this page, which i have tried, I don't understand how to tie it in and get what i need. I hate being a noob. =(


I'm stuck at a fork in the road. Need ideas on how to grow my skill and passion as a guitar player

Question: I've been playing guitar for about 11 years now and i'm at the point where I need to start learning something new. I have a book of exercises (for building chops) which covers the major scale in every key and the minor pentatonic in every key. I also bought a DVD which is intermediate theory for guitar. I have played in pentatonics for a while and I am very proficent in this scale.
My question is, should I work on pentatonic exercises and get better at them or should I dive into intermediate theory? I want to get to the point where I am considered an advanced player. Thanks for any input in advance.
Comment: If I were in your shoes, I would pick some harder songs to learn and not worry too much about exercises. And by that I mean, when I was in your shoes, I picked some harder songs to learn and didn't worry too much about exercises. You can build scale mastery by learning solos note-for-note. And the more songs you know, the easier it is to jam with some other people and find a band.
Comment: Do you have a band? Play guitar with other people and learn the music that they are working on. Take any opportunity to learn to play music different than that which you are familiar, if you can play with other people. You will grow a lot as a musician.
Answer: This seems like opinion land, but here is my opinion: "Yes." In other words, the studies you suggest are not incompatable, in addition Todd Willcox'e suggestion is also good, and so is Chochos. It is likely that other answers will also be good. I figure "Advanced" is that same thing as having allot of skill and knowledge. To truely achieve your goals of being advanced, spend some time doing all of that, and a few more things. Everything you can handle, in parallel (Different parts of your practice time). When you learn a few different things at once, there is a tendancy for the learning of the differn't subjects to support each other. Your brain also learns faster, if subjects are varring back and fourth from one thing to another (changing say every 15 or 20 minutes) in each practice time.
My opinion in a nutshell: For the truely advanced, all music subjects and skills are seen by the user as part of the whole and interact with and support each other. (In this case the whole is the study of music and your instrument.)
PS: (I do not know a guitarist who is both advanced and does not know their Major and minor scales quite well.)
Edit: I like Wheat Williams' comment so much I am stealing it here:
Do not play in a vacuum. Perform for, and play with others.
Answer: One thing I love about playing guitar is - no matter how good I get, there is always room for improvement. It's a never ending journey and I enjoy every step.   I admire your desire to continue improving your skills.
I am not sure what your personal definition of "advanced" is - but it is clear that you want to become a better guitar player.  It is also apparent that you are willing to put in the time and effort to accomplish your goal of becoming an advanced player.
There are many paths to improvement.  All of the options you mentioned in your question and all of the options presented in the answers thus far, will help you improve. You did not mention lessons which can help tremendously if you have the right teacher, but I will assume that self study is your preference.
Everyone's path to improvement is different.  One method may work better for some, other methods may work better for others.  The common goal of study, exercises, drills, and practice - is to improve your skill at playing your instrument.
I don't want to discount the importance of practicing scales and learning theory and new techniques - but I would like to explain the method I prefer to utilize  to continually improve my playing ability.
First let's look at why one would want to even learn to play an instrument.  I learned to play the guitar because I wanted to be able to accompany my singing and perform without an external accompaniment source. When I started writing songs, my ability to play the guitar took on an even higher purpose - that of helping me to compose the music to go with the lyrics I write.   Other's learn because they want to perform for friends, play in a band, jam with other musicians, or perhaps simply for their own enjoyment.
In short - you learn to play an instrument (such as guitar) in order to be able to make or play music.  And making music involves more than just playing scales and playing notes and chords.  Nobody learns to play an instrument just so they can play scales. They want to be able to apply the skills and theory to the art of making or performing music.
More than anything else, I play guitar because I enjoy it.  I spend some time practicing scales so I can improve.  But for me personally, the more enjoyable way to improve my skills and master new techniques, is to continually learn to play new, more challenging songs, or play more challenging and more advanced arrangements of songs I already play.
I almost always have 4 or 5 songs I am working on and I like to spend most of my practice time working on mastering those new songs.  The songs or arrangements I work on will incorporate the skills I want to improve, whether it's picking hand accuracy, picking hand speed, fretting hand techniques, new chords, fast chord changes or whatever.
By learning to improve my skills by applying them to more complex arrangements of actual songs, I feel that I am learning by making music - which is why we play an instrument in the first place.  There is more to making music than being able to faithfully execute scales and techniques.  Making music involves, timing, rhythm, soul, feeling, touch and all the nuances that make our playing musical.  So when I focus on learning new songs to improve my playing ability, I am also learning to make my playing more musical!
Also, I find it far more enjoyable to learn a new song than to play scales and practice drills.  It gives me a measurable goal.  And I get a greater sense of accomplishment from mastering a new song that I previously could not play - than I do from getting faster and/or more accurate playing a scale.  I am working towards "look - now I can play this new song" instead of "look how fast I can now play the A minor pentatonic scale".
I play guitar for the joy of being able to play music (which to me means playing songs).  If I improve my skills by learning new songs, I have more fun and expand my musical repertoire at the same time as improving my playing ability.
Rote repetition has it's place, but it also has its limitations. Unless it gives you pleasure to play scales backwards and forwards - I would recommend that you challenge yourself to learn some new songs or new solos that you can play as part of the process of making music and make that a big part of what you do to improve your skill.
Then you will not only become a better guitarist, you will become a better musician.  And you will derive more enjoyment from the time you spend with your instrument.
Good luck on your journey.
Comment: I agree: I think after 11 years of playing, it is past time to stop focusing on scales. A scale is not a solo. I always struggle with metaphors for this concept, but its like a carpenter who only makes jigs, or a dance troupe that only talks about dancing.
Comment: @Yorik You are making an assumption that the OP ever focused on (non pentatonic, since that skill is claimed in the question) scales before. This assumption could in fact be wrong, taking the question at face value.
Comment: @amalgamate: I was focusing on the idea that scales are not solos. Running perfect scales is like making perfect color wheels or drawing a perfectly straight line: a useful exercise perhaps, but pragmatically useless in the wild.
Comment: @Yorik Yeah, I understood. I would disagree with useless. There is a reason why art classes have color wheels. I don't remember any straight line exercise though. You make it sound a bit like you are giving an excuse not to work hard. Most hard work is good, and open minded and balanced hard work is better.
Answer: You talk about scales and keys. How about some rhythm exercises? Syncopation, etc; it's not only for bass/drums, you can play some very interesting stuff in the guitar when you drift away from the usual rhythm patterns.
Answer: You didn't mention what DVD you bought, so I don't know if you do this already, but if you want to be recognized as an advanced player as you say, start thinking less about scale shapes and try to think more in terms of notes. In other words, force yourself to think musically.
I suggest you try approaching greek modes - and with them, comes a LOT of musicality, perception and knowledge that will be required from you: intervals, harmony, tonality, chords and whatnot. Because this may be boring for many people, you may try a lighter, generic approach through this material:

Creative Guitar 1 - Cutting-edge techniques, a book by Guthrie Govan. You can find it used for about 10 bucks in Amazon, just make sure you get the accompanying CD. This book explains all I've mentioned in a very easy to understand way, yet not skipping over any important parts. Also, if you're into exercises, it has a lot of pentatonic views and different approaches, as well as modes.
Modes, No More Mistery by Frank Gambale, this is a DVD that demonstrates all the modes, how they sound, why they sound like they do and how to use them. This is excellent stuff, also kinda funny because it was made in 1991, with mullets, leather pants and colourful shirts.
This video by Guthrie Govan, is not only enlightening, but also very informative. No boring repetition of what everyone says. Very, very interesting concepts that have changed the way I thought whenever I felt stuck.
Mimi Fox also has a few very cool videos on Youtube. I forced myself to watch those over and over until I understood what she was saying, and boy, was it worth it.

Of course, advice is relative, but it's what I took from experience in 24 years of guitar playing. Once I dived into notes, my world changed. It is hard at first, but keep going, it WILL come to you faster than you think. Also, improvise, improvise, improvise: get generic backing tracks from the web (there are thousands) and spend some time with each.
I hope this helped, best of luck.
Comment: Yes, I agreee strongly, but don't throw out your patern knowledge (scale shapes) I know, @Fractalizer did not say that but just to be clear. Enhance it that knowledge with the knowledge of notes, and also learn new patterns that can help you break out of ruts. Also, if you don't know major minor and pentatonic scale paterns, you should. Arpegios, modes, mode theory... the list goes on and on.
Comment: That's right, you can never let technique aside! I still struggle daily to improve my right hand. And I didn't mean to throw out your patterns, they're vital. You will not think note-by-note when playing fast, you'll visualize the patterns. I just assumed you nailed some of them and wanted to go beyond... @amalgamate 's comment is very valid: do not get stuck with the same patterns, there's always more than one way to play the same thing.  :-)
Answer: My advice;
Play what turns you on, and get out there and play live.
If you don't have a band, go to Open Mic Night at your local pub or coffee shop, and play in front of other musicians.
Visit one or two local Old Folks Homes, and arrange to go in and play and sing for them. Those old ladies and gentlemen will appreciate anything you have to offer, and they will inspire songwriting like you won't believe.
Set up on the corner at a local mall or shopping district, leave your guitar case open with a small amount of currency for seed money, and PLAY.
When guitar players get stuck in a rut, it's because they have narrowed their left and right limits of creativity.
You will fix that by getting out there and interacting with a lot of other people.
Try it, you'll like it.


How sensitive is a natural cubic spline?

Question: I am interested in using natural cubic splines to generate possible replacement values in the quality control of data.  I would like to do this as close to real-time as I can.  That is, I would like to use only one point (todays value) on the right of the value I wish to predict (yesterdays value) and more points (the past) on the left.  My question is: How far in the past should I go?  I know that a natural cubic spline does take into account every data point that you feed it.  I just wonder how sensitive it is to say, 40 points versus, maybe 15 or 20 when the point I am evaluating at is so far to the "right".
If anybody has knowledge of this or could at least point me to further reading, I would appreciate it.  Thanks.
Comment: Non-rigorous guess: Using more points to the left essentially replaces the spline's left boundary condition $y''(x_{n-1})=0$ with a more context-based value. But you still have the effect of the right boundary condition $y''(x_n)=0$, and that may be the greatest remaining source of distortion to your *latest* interpolation results relative to what you would get with more data points to the left AND right.
Answer: In general, the error of the natural spline
comes from the terminal points and is bounded by $O(h^2)$ where $h$ is a grid step. But also the real value of the second derivative of the function is important, i.e. how far it from from zero at the end points, after all the natural spline uses $S_0''(x_0)=0=S_n''(x_n)$ as boundary condition. Of course the closest you to the known data the better is extrapolation.
see also
Following is just an example and a piece of code to play with.
for i=1:5

    M(i)=fix((2^(i+3)));
    x=linspace(a,b,M(i));
    y=linspace(a,c,2000);
    %u=spline(x,f(x),y);
    pp=csape(x,f(x),'variational');
    u=ppval(pp,y);
    err(i)=norm(u-f(y),inf);
end

%plot(y,f(y),'b',y,u)
M
err

I runned the above code with the following
a=-pi;
b=0;
c=pi;
f=@(x) sin(m*x);

for $m=2$
M   = 16        32        64        128       256       512       1024

err = 34.4515   34.9169   35.0242   35.0501   35.0564   35.0580   35.0584

and $m=10$
M   = 16        32        64        128       256       512       1024

err =

   1.0e+03 *

    2.8969    4.6777    5.0283    5.1099    5.1298    5.1347    5.1359

Answer: To understand the sensitivity to far-away data points, you should look at the graphs of the cardinal basis functions for the space of natural cubic splines. See the second set of pictures in this question.
As you can see, these functions decay to almost zero quite rapidly, (though they are always non-zero, except at knots). So, in your kind of application, I would say that the difference between using 15 or 20 points would be negligible. In fact, if it were me, I'd probably choose 6 to 8 points.
Also, you might consider scrapping the spline idea altogether. I'd suggest just interpolating a few nearby points using a low-degree polynomial. You can write down a closed-form formula for the interpolant, and this will make it easy to do the computations in real time.


Why does December 8th, 2009 Patch Tuesday Kill IIS in Windows Server 2003?

Question: We installed the updates from Microsoft on our test server (minus the one that is struck through - IE8 isn't installed, and the IE patch didn't seem to get installed) and upon reboot, none of the IIS application pools would stay started. We uninstalled the updates, and IIS worked again - this same behavior was seen on three different test servers.
I haven't been able to locate any other documentation where people have had this problem.
Does anyone know of this problem occurring for other people, and if there is a workaround that will allow IIS to function after installing the security updates?
(below copied from http://www.myitforum.com/forums/m_211648/mpage_1/key_/tm.htm#211648)

Critical:
  MS09-071: Vulnerabilities in Internet
  Authentication Service Could Allow
  Remote Code Execution (974318)
  Affects: Windows 2000/XP (inc
  x64)/2003 Server (inc x64)/Vista (inc
  x64)/Server 2008 (inc x64) Link:
  http://www.microsoft.com/technet/security/bulletin/MS09-071.mspx
MS09-072: Cumulative Security Update
  for Internet Explorer (976325)
  Affects: Internet Explorer 6, 7 & 8
  Link:
  http://www.microsoft.com/technet/security/bulletin/MS09-072.mspx
MS09-074: Vulnerability in Microsoft
  Office Project Could Allow Remote Code
  Execution (967183) Affects: Project
  2000/2002/2003 Link:
  http://www.microsoft.com/technet/security/bulletin/MS09-074.mspx
Important:
MS09-069: Vulnerability in Local
  Security Authority Subsystem Service
  Could Allow Denial of Service (974392)
  Affects: Windows 2000/XP (inc
  x64)/Server 2003 (inc x64) Link:
  http://www.microsoft.com/technet/security/bulletin/MS09-069.mspx
MS09-070: Vulnerabilities in Active
  Directory Federation Services Could
  Allow Remote Code Execution (971726)
  Affects: Windows 2003 Server (inc
  x64)/2008 Server (inc x64) Link:
  http://www.microsoft.com/technet/security/bulletin/MS09-070.mspx
MS09-073: Vulnerability in WordPad and
  Office Text Converters Could Allow
  Remote Code Execution (975539)
  Affects: Windows 2000/XP (inc
  x64)/Server 2003 (inc x64)/Office
  XP/Office 2003/Works 8.5/Office
  Converter Pack Link:
  http://www.microsoft.com/technet/security/bulletin/MS09-073.mspx
Answer: http://support.microsoft.com/kb/2009746


rails - activerecord ... grab first result

Question: I want to grab the most recent entry from a table.  If I was just using sql, you could do
Select top 1 * from table ORDER BY EntryDate DESC

I'd like to know if there is a good active record way of doing this.
I could do something like:
table.find(:order => 'EntryDate DESC').first

But it seems like that would grab the entire result set, and then use ruby to select the first result.  I'd like ActiveRecord to create sql that only brings across one result.
Answer: You need something like:
Model.first(:order => 'EntryDate DESC')

which is shorthand for
Model.find(:first, :order => 'EntryDate DESC')

Take a look at the documentation for first and find for details.
Answer: The Rails documentation seems to be pretty subjective in this instance. Note that .first is the same as find(:first, blah...)
From:http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002263
"Find first - This will return the first record matched by the options used. These options can either be specific conditions or merely an order. If no record can be matched, nil is returned. Use Model.find(:first, *args) or its shortcut Model.first(*args)."
Digging into the ActiveRecord code, at line 1533 of base.rb (as of 9/5/2009), we find:
    def find_initial(options)
      options.update(:limit => 1)
      find_every(options).first
    end

This calls find_every which has the following definition:
    def find_every(options)
      include_associations = merge_includes(scope(:find, :include), options[:include])

      if include_associations.any? && references_eager_loaded_tables?(options)
        records = find_with_associations(options)
      else
        records = find_by_sql(construct_finder_sql(options))
        if include_associations.any?
          preload_associations(records, include_associations)
        end
      end

      records.each { |record| record.readonly! } if options[:readonly]

      records
    end

Since it's doing a records.each, I'm not sure if the :limit is just limiting how many records it's returning after the query is run, but it sure looks that way (without digging any further on my own). Seems you should probably just use raw SQL if you're worried about the performance hit on this.
Comment: The :limit option is passed through to SQL, so there's no performance hit from loading all the records into Rails and filtering there. The easiest way to see what a query is doing is to tail development.log while executing queries on the console.
Comment: After I read my answer again I figured that the :limit => 1 option was probably being passed all the way down into the raw SQL that was being build, but I didn't have the time to keep researching and didn't want to gamble by making an incorrect assertion on the behavior :)
Answer: Could just use find_by_sql http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002267
table.find_by_sql "Select top 1 * from table ORDER BY EntryDate DESC"

Comment: That doesn't actually work with mysql (you've got to use 'limit 1' at the end rather that 'top 1' at the beginning.)  I actually started using that before I asked the question because it seemed to me that ActiveRecord should have some native syntactical support for an operation like that.  If not, that's all I need to know :)


Class of all sets

Question: I am reading a book Axioms and Set Theory - A first course in Set Theory by Robert André.
Here the auther writes as follows.
Let L = { x : set(x) }, By axiom of class construction L is a class of all sets.
Later he proves that L is a Proper Class. That is also fine.
Then he stated that elements of L are pure sets and every element x of set that belongs to  L is a set.
I need a proof for above statement.
Also he stated that x is a pure set if and only if y belongs to x belongs to L implies that y belong to L.
I need a proof that why elements of L satisfies this property.
Also want to know if set C = { 1 , 2 } is an element of L.
C is a set so should be an element of L (Class of all sets). But then all elements of L are pure sets and C is not a pure set. So I am confused.
Comment: Until you say, within set theory, what "1" and "2" are, you can't assert that they are not sets. Traditionally,  $0=\varnothing$, $1 = \{0\} = \{\varnothing\}$, and $2=\{0,1\} = \{\varnothing,\{\varnothing\}\}$. But the key is: you can just say "set $C=\{1,2\}$". You need to explicitly say what each thing is. You don't define things into existence, you have to prove they exist within your theory.
Comment: How do you define "pure set"? Do you mean "set with no urelements"? Identify $0:=\emptyset,\,n+1:=n\cup\{n\}$.
Comment: Pure set is a set whose elements are also sets
Comment: If that's not synonymous with "set", what else could be elements of sets? Would it be urelements? What theory is Robert André using?
Answer: I've read this particular book before, and I think some clarification is required.
When discussing formal theories, it is important to state the language in which the theory is being presented. ZFC is a first-order theory, meaning that the language of ZFC is a type of first-order logic. The syntax of first-order logic, which is explained here, distinguishes between logical and nonlogical symbols, and identifies certain symbols as terms.
ZFC is a pure set theory, which means that all of its terms are sets, and there is one nonlogical symbol $(\in)$. You cannot prove that the class of sets contains only sets, or that the elements of every member of the class of sets is a set. Rather, the only objects in the language of ZFC are defined as sets.
In other set theories - KPU, for example - there are object called urelements which are not sets. These are not present in ZF set theory because such objects can be encoded as sets using a variety of techniques; the purely set-theoretic account of the natural numbers is explained in Chapter V. As explained there, the set $\{1,2\}$ is defined as $\{\{\emptyset\},\{\emptyset,\{\emptyset\}\}\}$.
I would also note that classes are not objects in ZFC set theory. André's use of classes extends the usual axioms of ZFC. In standard ZFC set theory, proper classes like the class of all sets are merely "implied" rather than stated.
Edit/Correction:
André's explanation does treat classes and sets as objects, and provides that any element of a set is a set. So the proof of $y\in x\in L\implies y\in L$ is $y\in x\implies set(y)$.
Comment: In the book the OP reads, the author treats *classes* as its objects and *set* as yet another primitive (and defines the concept of *element* for any class that can appear to the left of $\in$). The axioms of extension and construction are formulated for classes, pairing for sets, comprehension/power/union/replacement for sets, infinity grants a set, and regularity is only about sets. It is not directly obvious that every *element* must be a *set*
Comment: @HagenvonEitzen You're right, it is explained this way in the first chapter. Still, since the only other primitive object is "set," and a class cannot be an element, it stands to reason that any element of a set is again a set.
Answer: In this set's theory,C={1,2} also can be written as C={∅,{∅},{∅,{∅}}},or any sets with 2 elements.
You said C is not a pure set, because you consider number in $R$,but in fact there is no relation between this 1 and this 2,can you add 1 and 2?No,you even dont define "add".
Comment: Please can u give me an example of set which is not a pure set and also an example of set which is pure set.
Comment: In ZFC axiomatic set theory system,any set is pure set.Do you remember why we defined Class?
Comment: Yes for that Russell paradox, hope I got this right. I think I have miss understood a lot of basic concepts.
Comment: @xxxxxllllllllxxxxx This should make us ask: Why does the author define the concept of *pure* set when it does not differ from the concept of set? To the point the OP asks about, the author has shown "All sets are elements" (Thm 2.7), but not (what he would now need) "All elements of sets are sets"

Class of all sets


If the product of two numbers is positive and less than one, what can I conclude about the quotient?

Question: If I'm given that $0 < ab < 1$, how do I figure out what values $\frac ab$ can take on?
I have $0 < ab < 1$ and am asked if $\frac ab < 1$.
I can see that if I set $a = \frac 12$ and $b = \frac 14$, then $ab = 0.125$ but $\frac ab = 2$, so the answer is no, but I'm wondering if there is some systematic way to demonstrate this? Or if plugging in values is the best way to do this, is there some systematic way to choose the values to plug in?
I don't know everything I should be considering, and can easily see myself trying the few things that pop into my head, then drawing an erroneous conclusion because I wasn't considering some important class of options.
Comment: You can abstract plugging in values. For any $c > 0$, you have $(ca)\left(\frac{b}{c}\right) = ab$, but $\frac{ca}{b/c} = c^2\frac{a}{b}$.
Answer: In this case a little trial and error is quite likely to lead one rather quickly to an example like yours. Alternatively, one might quickly realize that if $0<b<a<1$, then $0<ab<1$ and $\frac{a}b>1$, thereby obviating the need for a specific example. The real insight there is that if $a,b>0$ and $a\ne b$, then one of $\frac{a}b$ and $\frac{b}a$ must be greater than $1$, regardless of what $ab$ is.
Comment: @dumbquestion: You can't conclude that $b1$ or that $\frac{a}b=1$; all of these are consistent with the hypothesis that $0<ab<1$, which therefore does not imply any of them.


Como consigo criar um Componente em react js para publicar no NPM

Question: Estou com uma duvida,
preciso criar um componente em react js é publicar ele no NPM.
eu consegui publicar ele,
porem ele fica dando erro para transpilar de js para jsx ou de jsx para js.
então quando eu importo ele para meu projeto ele não reconhece as classes no import
como eu faço esse procedimento de publicação no NPM ?
Comment: Coloque o processo de publicação e também o código desse componente!
Comment: Consegui resolver meu problema Virgilio Novic!
Muitissimo Obrigado!!
Answer: Conseguir obter o resultado esperado assim:

Esse foram os arquivos necessarios..
<code>/// Abaixo o código do .babelrc
{
  "presets": [
      "react",
      "env",
      "stage-0"
   ]
}

/// Abaixo segue o código do package.json
{
"name": "<nome do seu NPM>",
"version": "0.0.1",
"description": "React Validate Registro",
"keywords": [
    "validar",
    "CPF",
    "CNPJ"
],
"main": "./lib/index.js",
"license": "MIT",
"scripts": {
    "build": "webpack"
},
"peerDependencies": {
    "prop-types": "^15.6.0",
    "react": "^16.0.0",
    "react-dom": "^16.0.0"
},
"devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.24.1",
    "path": "^0.12.7",
    "prop-types": "^15.6.0",
    "react": "^16.11.0",
    "react-dom": "^16.0.0",
    "react-input-mask": "^2.0.4",
    "react-toastify": "^5.4.0",
    "reactstrap": "^8.1.1",
    "webpack": "^4.5.0",
    "webpack-cli": "^3.2.1"
}

/// Por ultimo o código referente ao webpack
var path = require('path');

module.exports = {
mode: 'production',
entry: './src/index.jsx',
output: {
    path: path.resolve('lib'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
},
module: {
    rules: [
        {
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            use: 'babel-loader'
        }
    ]
}
</code>
Após essas configuração,
basta colocar no console (npm run build)
Depois (npm adduser) que vai pedir seus dados de acesso do npm.
logo em seguida (npm publish)
Detalhe
Crie seu componente dentro da pasta src  com o nome index.js


How often do I need to invoke Parse.subscribeInBackground() in order to subscribe to Parse pushes?

Question: We're using Parse.com services to deliver push notifications to our Android app. These notifications are coming in some specific channel and we can assume that the channel remains the same from the app installation till its removal.
Now, there is a method Parse.subscribeInBackground(String, SaveCallback):

public static void subscribeInBackground(String channel,
                           SaveCallback callback)
  Adds 'channel' to the 'channels' list in the current ParseInstallation and saves it in a background thread.
  Parameters:
  channel - The channel to subscribe to.
  callback - The SaveCallback that is called after the Installation is saved.

The documentation is a little unclear because I don't understand how often do I need to invoke this method in our app? Do I need to

invoke it just once, make sure it was successful via the provided callback and don't invoke it again
or do I need to invoke it every time the app starts (because the process of subscription may require that some services are started, some broadcast receivers are registered, etc)?
Answer: You should call it each time the app starts...
In this tutorial (https://parse.com/tutorials/android-push-notifications) they call ParsePush.subscribeInBackground from the app's onCreate method.


Community Promotion Ads - 2015

Question: As your site is testing our new design-independent graduation process, we'll also be giving you guys the first run of design-independent Community Promotion Ads!
What are Community Promotion Ads?
Community Promotion Ads are community-vetted advertisements that will show up on the main site, in the right sidebar. The purpose of this question is the vetting process. Images of the advertisements are provided, and community voting will enable the advertisements to be shown.
Why do we have Community Promotion Ads?
This is a method for the community to control what gets promoted to visitors on the site. For example, you might promote the following things:

the site's twitter account
Magento-related blogs and websites
cool events or conferences
anything else your community would genuinely be interested in

The goal is for future visitors to find out about the stuff your community deems important. This also serves as a way to promote information and resources that are relevant to your own community's interests, both for those already in the community and those yet to join.
Why do we reset the ads every year?
Some services will maintain usefulness over the years, while other things will wane to allow for new faces to show up. Resetting the ads every year helps accommodate this, and allows old ads that have served their purpose to be cycled out for fresher ads for newer things. This helps keep the material in the ads relevant to not just the subject matter of the community, but to the current status of the community. We reset the ads once a year, every December.
The community promotion ads have no restrictions against reposting an ad from a previous cycle. If a particular service or ad is very valuable to the community and will continue to be so, it is a good idea to repost it. It may be helpful to give it a new face in the process, so as to prevent the imagery of the ad from getting stale after a year of exposure.
How does it work?
The answers you post to this question must conform to the following rules, or they will be ignored.

All answers should be in the exact form of:
<code>[![Tagline to show on mouseover][1]][2]

   [1]: http://image-url
   [2]: http://clickthrough-url
</code>
Please do not add anything else to the body of the post. If you want to discuss something, do it in the comments.
The question must always be tagged with the magic community-ads tag. In addition to enabling the functionality of the advertisements, this tag also pre-fills the answer form with the above required form.

Image requirements

The image that you create must be 220 x 250 pixels
Must be hosted through our standard image uploader (imgur)
Must be GIF or PNG
No animated GIFs
Absolute limit on file size of 150 KB

Score Threshold
There is a minimum score threshold an answer must meet (currently 6) before it will be shown on the main site.
You can check out the ads that have met the threshold with basic click stats here.
Answer:
Comment: I knew you'd be the first one in here, Daniel - nice touch on the Reddit Ad, sir!
Answer:
Answer:
Comment: For the many uninitiated people who find their way to Magento SE, this is a link to a resource which has a bit more leeway when it comes to questions and answers.
Answer:
Answer:
Comment: This is a demonstration post to indicate how this should look when an ad is posted. It also doubles as your twitter ad, but it's up to you if you wish to promote it by voting.
Answer:
Answer:
Answer:
Answer:

Community Promotion Ads - 2015


Proof of $BGl(n)\simeq Gr(n,\infty)$

Question:
What is a direct proof for the existence of a weak homotopy equivalence
  between the Grassmanian $Gr(n):=Gr(n,\infty)$ and the classifying space
  $BGL(n)$ of $GL(n)$?

They both represent the functor of isomorphism classes of rank $n$ vector bundles on some CW complex but perhaps there is a more direct proof to see this fact.
Comment: What is your definition of $BGL(n)$?
Comment: The bar construction, i.e. the realization of the simplicial space $...GL(n)\rightrightarrows *$.
Answer: One possible approach would be the following:
The bar construction gives you a principal $GL_n$ bundle
$$GL_n\rightarrow EGL_n\rightarrow BGL(n)$$ with $EGL_n$ being weakly contractible.
For the Grassmannian one has a similar principal bundle
$$GL_n\rightarrow V_n(\infty)\rightarrow G_n(\infty),$$ where $V_n(\infty)$ is the Stiefel manifold of $n$-frames and the map $V_n(\infty)\rightarrow Gr_n(\infty)$ is given by taking the span. The classifying map of this bundle gives you a commutative diagram
$$\require{AMScd}
\begin{CD}
GL_n @>{}>> V_n(\infty)@>{}>>G_n(\infty);\\
@VVV @VVV @VVV\\
GL(n) @>{}>> EGL(n)@>{}>>BGL_n;
\end{CD}$$ of fiber bundles. The ladder of long exact sequences in homotopy groups then yields the result as $V_n(\infty)$ is weakly contractible.
Sidenote: Maybe it would be cleaner to do this first unstably for the bundle involving $V_n(k)$ and $Gr_n(k)$ to get a highly connected map $Gr_n(k)\rightarrow BGL_n$ and then passing to the colimit.
However, this is not a real answer to your question since I used that $BGL_n$ classifies principal $GL_n$-bundles. All I have proven is that if you have a principal bundle with a weakly contractible total space and you know that there is a classifying bundle, then the base space of the bundle one has started with is weakly equivalent to the base space of the classifying bundle.

Proof of $BGl(n)\simeq Gr(n,\infty)$


Event tracking with Google Tag Manager

Question: Is the following setup of Google Tag Manager and Analytics correct regarding the variable use, naming etc.
Tag: GA tracking code
Tag: Goals w. macro below
Macro: (As specified in post) Event Action > eventAction; Event Category > eventCategory; Event Label > eventLabel etc.
Rules: GA Event > GAevent
Triggered by JS: dataLayer.push({ 'event':'GAevent', 'eventCategory':'Forms', 'eventAction':'Send', 'eventLabel':'Request' })
In Google Analytics:
1st Goal: Category > Forms; Action > Send; Label > Request Form
2nd Goal: Category > Forms; Action > Send; Label > Contact Form
Answer: Have you created a tag for Google Analytics Event?
You'll have to map the event category to eventCategory, etc. And then set the rule to GA Event equal to GAevent.(see attached)

Event tracking with Google Tag Manager


Why does the circle of fifths have to be symmetric

Question: I have studied music theory ever since I studied piano playing. So I know about things like accidentals and how white key accidentals like Cb or E# make sense.
But one thing I don't know about is this:
Why does Cb major even exist?
Some circle of fifths illustrations show Cb major to keep the symmetry of the circle of fifths. Others don't show it to make things easier. To me, calling B major Cb major is like calling C minor D double flat minor. It makes no sense, unlike the C#/Db and F#/Gb enharmonic pairs.
Here is a circle of fifths illustration that shows Cb major:

And here is another one that collapses Cb major into B major:

So why have B major and Cb major be different keys? Why does the circle of fifths have to have this symmetry to it?
Comment: Do you have a picture that illustrates what you mean?
Comment: @topomorto Now I have some images that show the circle of fifths. One of them shows Cb major as part of an enharmonic pair. The other one doesn't show Cb major at all.
Comment: It exists so that you can tell the composer to bugger off :) But, generally, it's because we have 7 "named" notes, and can therefore have up to 7 "proper" accidentals. Your question is a bit similar to the question I've always had: why do we have 7 letters when there are 12 notes to a (Western) octave (and 5 ledgers on the stave)? Those things are mostly historical and have no real logical explanation.
Comment: @Pyromonk - ignoring all 7 flats means it's probably a darned sight easier to play on most instruments. Just comes out being played in C! Unless it was written in Abm...
Comment: @Tim, that's what I meant about telling the composer to bugger off! :D
Comment: @Caters, one is complete, and the other one isn't. Generally, one could choose one of those "weird" keys, because of a need to modulate to a different key with the least amount of accidentals. That's the only reason I can personally come up with to use such an monstrocity. Other than that, perhaps they could make things easier for some transposing instruments (such as the saxophone).
Comment: Highly related: https://music.stackexchange.com/questions/5658/is-g-sharp-major-a-real-key
Answer: C♭ exists because it can! There are 7 flats in the key sig., and that's maximum - like there's 7 sharps in C♯. If it went on to the next, double sharps and flats would have to be used, and it would become too unwieldy.
Occasionally, a piece will be written in a key and modulate. There have been times (no example comes to mind) where it's actually easier to read when the piece modulates to C♭ rather than B.It could, of course, go the opposite way - but at least there's a choice!
The one before is F♯/G♭. That follows logically enough, and they're the same (in 12tet), and there's no real concern over that slight anomaly, so C♭ and C♯ just round things off.
Interestingly, while the relative minors of all the other keys are quoted in Wiki, those of C♯ and C♭ are not...
Comment: A couple of examples of pieces which modulate to C♭ major: a Contredanse by Chopin which starts in G♭ major and has a section in C♭ major. In some editions,  Schubert's song Das Fischermädchen is in A♭ major; its middle verse is in C♭ major. In each case writing the section in B major is possible but would involve a jolt from flats to sharps and back.
Comment: In vocal music keeping both keys in flats would make for an easier transition for the singer who has to "find" pitches. I have seen some piano pieces where the modulation included a transition from flats to an enharmonic sharp key, but that is easier to do when you get the pitch you need just by hitting the right key. It's much harder to make the adjustment from flat to sharp and vice-verse while singing.
Comment: @HeatherS. - I'd have thought taht once teh new key/root is established - probably in the first bar, it would be quite easy, with accompaniment.
Comment: @Tim, perhaps. But many singers also do not have the privilege of always practicing with accompaniment. I still think it harder for singers than instrumentalists, but that may just be a matter of opinion.
Answer: C♭ major is rarely but actually still used in music, often as the relative major of A♭ minor. It makes sense for music to be written in A♭ minor despite its 7-flat key signature--I've always preferred how its dominant chord is spelled as an E♭ major chord with a natural instead of a D♯ major chord with a double sharp, for example--so to keep the symmetry of the circle of fifths with a key that is still used in practice, C♭ major is often still on notated versions of the circle of fifths.
(I've seen a 21st-century composer actually use C♭ major as the home key of a piece, but that may be beside the point.)
Comment: Wasn't Janacek, was it, as a matter of interest? (Janacek was fond of A♭ minor.)
Comment: @RosieF - Nope, just a person composing ragtime in the 21st century who'd made the observation that ragtime strongly prefers keys with flats in their key signatures.
Answer: The "true" circle of fifths is not a circle at all, but more of a spiral. A fifth above an A# is not an F, it's an E# (an F would be a diminished 6th). Another fifth (up from E#) is not C, but B# (for the same reason as before). This, therefore, leads us to the following: C->G->D->A->E->B->F#->C#->G#->D#->A#->E#->B#->F##->C##->G##->D##->A##->E##->B##->F###->C### ad infinitum). To avoid diagramming an infinite spiral (in both directions), we went ahead and allowed a couple diminished 6ths to help connect up the ends and bring us full circle (#nailedit).
So why, then, do we have the enharmonic keys at the bottom at all? Couldn't we have just picked one or the other and moved our connecting diminished 6th accordingly? We are, after all, already completely ignoring Fb and showing only E, so why not ignore Cb, Gb and C# as well?
Let's think of it in a slightly different way. Instead of the letter name of the root, consider the number of sharps or flats in the key. Since we only have 7 notes to choose from, it makes sense (for completeness) to start with everything flat (Cb), remove one flat at a time until we get to C, then add one sharp at a time until everything is sharp (C#). Then we combine the enharmonic overlaps and we're left with the circle of fifths as we know it.
In the end, the circle of fifths is a reference tool, not a definition. Do you have to draw it symmetrically? No, you can draw it however you want. Is it a good idea? Yes, I think so. Does it completely and utterly drive me crazy if there is one flat unaccounted for and it's not perfectly symmetric? Absolutely! ;)
(One other interesting way to think about it is by the leading tone, or the major 7th above (and half step below) the root. All other chords in a major key are shared between several keys, but the diminished chord on the 7th degree is unique to its respective key. This is why it wants to resolve to the root chord so badly (it's all its got!). By finding the root for every leading tone we get the following: B -> C major, B#/C -> C#/Db major, C# -> D major, D -> Eb major, D# -> E major, E -> F major, E#/F -> F#/Gb major, F# -> G major, G -> Ab major, G# -> A major, A -> Bb major, A# -> B major and Bb -> Cb major. This gives us every key on the circle of fifths (in a different order of course), including Cb. Without Cb, the Bb leading tone has no key to resolve to )
Comment: The circle of fifths is only a spiral if you define "fifth" as Pythagoras did, a ratio of 3:2.  If you define it as 2^(7/12):1 then the circle closes, or at least overlaps on itself, cycling around in a circle infinitely.  It similarly closes in every other 12-tone temperament, where of course not all the fifths have the same size.
Comment: @phoog The *ratio* completes a full cycle, but the structural interval does not. A diminished 6th has the exact same ratio as a perfect 5th, but is completely separate in terms of theoretical structure. In order to complete the circle we need to use a diminished 6th from C# to Ab in one direction and from Cb to E in the other.
Comment: If you define "structural interval" without regard to ratio then there is no basis to call anything a circle or a spiral.  It might as well be a straight line.
Comment: @phoog That's actually I really good point, I didn't think of that! Straight line of non-enharmonic fifths it is! :)
Comment: I had second thoughts, though: the spiral and circle do represent the enharmonic relationship between the names and the 12-tone keyboard, namely that C and B♯ (and D♭♭♭, etc.) are the same key.
Comment: Nice points about the spiral and that the overlapping nodes on the sprial are for enharmonic key signatures.
Comment: But that would be impractical, because then you would have C minor, B sharp minor, and D double flat minor, all representing the same set of notes. I checked the supposed D double flat minor and it has 2 triple flats in it. And you would need a separate minor spiral and major spiral, whereas on the circle of fifths, major and minor keys are on opposite sides of the same circle.
Comment: @Caters Yes, it would be completely impractical. I'm not saying we should actually use those keys. Anything beyond the 7 sharps/flats we see on the circle is nonsensical. The spiral concept is to explain the 3 enharmonic overlaps (essentially the circle starts with Cb and goes around to C#, where it ends; going beyond these leads to nonsense). And could you clarify what you mean by the major and minor on opposite sides thing? The parallel minor is three steps to the left of it's major, which would continue along the spiral.
Comment: @WillRoss1 When I talk about the major and minor keys being on the opposite sides of the same circle, I'm not talking about the parallel major and minor relations, I am talking about the relative major and minor relations i.e those keys that share a key signature such as C major and A minor.
Comment: @Caters But those are on the same side of the circle. I'm still not following
Comment: @WillRoss1 Minor keys are shown on the inside of the circle. Major keys are shown on the outside of the circle. Inside and outside are opposites, therefore minor keys are on the opposite side of the circle from major keys.
Comment: @Caters Ah, you mean like flipping it over? Essentially top and bottom in 3 dimensions? I never thought of it that way, but I like it! (I was thinking across the circle, 180 degrees, sorry for the confusion!)
Answer: Those enharmonic keys are on the charts you included, because whoever made them decided to include them.
They don't have to be included.
They could have included additional keys with more and more sharps and flats, like putting G# major with A flat major.
The only real limit to what key signatures someone lists is the practical limit of symbols for double. triple, etc. sharps/flats and what someone wants to put in a chart.
https://en.wikipedia.org/wiki/Theoretical_key


Stop-gradient operator in VQ-VAE

Question: In the vector-quantized variational autoencoder (VQ-VAE), the objective function (Eq. (3) here)  contains
$$\left\lVert \mathrm{sg}[z_e(x)] - e \right\rVert^2 + \left\lVert z_e(x) - \mathrm{sg}[e] \right\rVert^2,$$
where $\mathrm{sg}$ is the stop-gradient operator.
(Note: The second term can have a weighting factor $\beta$, but "the results did not vary for values of $β$ ranging from $0.1$ to $2.0$. We use $β = 0.25$", so let's assume $\beta=1$.)
What are the advantages of this objective over directly optimizing
$$\left\lVert z_e(x) - e \right\rVert^2$$
instead?
Answer: I have been looking for the same question. I have finally deduced the following. I think it is a learning factor that balance the importance between terms (codebook loss and commitment loss).
If the Beta factor is smaller than 1, it means that the encoder is updated more faster than the codebook.
That is interesting for example if we think about it from a centroid perspective (codebook), we do not want them to update strongly in each iteration because we have to preserve some information of the previous batches (and more important if the batch is small).
In short, we want the centroids (codebook) to move slowly and the encoder samples can be updated faster. Probably this technique can minimize the noise produced by the mini-batch sampling in contrast than use all the dataset.
This is what I have deduced, if it is not correct please someone indicate it.
Comment: So is VQ-VAE equivalent to choosing different learning rates for different trainable parameters? (Like setting `lambda` from the so-called *gradient reversal layer* to `-beta` instead of to `1`?)
Comment: Nice, thanks! I guess setting `beta=1` has the same effect as not using `sg`. It's interesting that they actually don't need `sg` for their dataset (they use a `beta` value that yields similar results to `beta=1`), yet they (implicitly) let the reader know that a serious use of `sg` (by setting a very different `beta` value) might be beneficial in other cases.
Comment: Yes, exactly in the gradient reversal layer, that lambda regularizes the implication it has, it would be the same concept. Basically, to control the update weight in the codebook and encoder. Without the sg operator, this could not be done because both terms would have the same update weight.
Answer: If you take gradients, the two formulas you mentioned are the same.
However, if we write in the form of the first formula, fix $z_e$ (zero gradient), let $e$ approach $z_e$ and inversely.
I think it would be easier for training.
Comment: Is it easier for training just empirically without understanding why (in that case where do such ideas come from?), or is there some understanding why this is easier for training?

Stop-gradient operator in VQ-VAE


Javascript passes function and receives error: Uncaught TypeError, process is not a function

Question: This code runs fine.  My IDE (RubyMine) sees no problem with it.  But Chrome DevTools throws an error both in the Source and in the Console.  Is there some way to clean this up?
Uncaught TypeError: process is not a function

$(document).ready(function () {
    let buttonWatch = function (process) {
        $(this).off('click');
        alert(typeof(process)); // This alerts "function"
        process();              // The error is thrown here
        return $(this).on('click', buttonWatch);
    };
    $("#loginButton").on('click', function () {
        function process() {
            alert("Running a process.");
        }
        buttonWatch(process);
    });
});

Revised code as recommended shows same issues:
let myProcess;
let process;
$(document).ready(function () {

    let buttonWatch = function (process) {
        $(this).off('click');
        alert(typeof(process));  // alerts "function"
        process();               // Error thrown here
        return $(this).on('click', buttonWatch);
    };

    $("#loginButton").on('click', function () {
        function myProcess() {
            alert("Running a process.");
        }
        buttonWatch(myProcess);
    });

});

Comment: @AndreiGheorghiu  It actually does work as coded, only Chrome DevTools complains.  The return only reinstantiates the click listener and does not redefine the function at all.
Comment: I've played some more with it and re-revised my answer. I hope it helps.
Comment: @AndreiGheorghiu  I do appreciate your help and advice.  It helped me come to a solution.
Answer: You are getting error when you add on click event on button dynamically within event process itself. So you are trying to take off click event, do some processing and then add the event back. But problem is when you add event handler back to your button click, you are not passing the process function on this line.
return $(this).on('click', buttonWatch);

So you need to make couple of changes.

Make your function available outside of click event scope
Bind process function as parameter to buttonWatch method when you add on

$(document).ready(function () {

    let buttonWatch = function (process) {
        $(this).off('click');
        alert(typeof(process)); // This alerts "function"
        process();              // The error is thrown here
        return $(this).on('click', buttonWatch.bind(this,process));
    };

    $("#loginButton").on('click', function () {
        function process () {
            alert("Running a process.");
        }
        buttonWatch(process);
    });
});

    <link rel="stylesheet" href="style.css" />

Reference : bind function
Comment: The buttonWatch code is a generic function that prevents doubleclicks.  The process function is specific to each button.  So, that process function is created within the scope of the listener.  There is no problem with the code as written, as it operates correctly many times.  The only issue is DevTools false identification of an error.  I resolved that by making it an assignment.  Thanks.
Comment: Glad you were able to resolve it. If process function needs to be dynamic, you can bind the parameter function. Updating answer.
Answer: As I repeatedly stated, the code runs fine.  I only get the weird error from DevTools.  In any case, the error is eliminated by using an assignment and DevTools is happy.
$(document).ready(function () {
    let buttonWatch = function (process) {
        $(this).off('click');
        alert(typeof(process)); // This alerts "function"
        let result = process(); // No error is thrown
        return $(this).on('click', buttonWatch);
    };
    $("#loginButton").on('click', function () {
        function process() {
            alert("Running a process.");
        }
        buttonWatch(process);
    });
});

The issue here is that, because the click listener must be reinstantiated upon return, I cannot return the result of the process.  So, I coded a better solution using disabled instead of offing the listener at all.
$(document).ready(function () {

    let buttonWatch = function (button, process) {
        $(button).prop("disabled", true);
        let result = process();
        $(button).prop("disabled", false);
        return result;
    };
    $("#loginButton").on('click', function () {
        function buttonProcess() {
            alert("Running a process.");
        }
        buttonWatch(this, buttonProcess);
    });
});

Just for completeness, this set up can be used when passing parameters and requiring that return of the process's results:
$(document).ready(function () {

    // buttonWatch disables and enables clicks around a process
    let buttonWatch = function (button, process) {
        $(button).prop("disabled", true);
        let result = process();
        $(button).prop("disabled", false);
        return result;
    };
    $("#loginButton").on('click', function () {
        function buttonProcess(message) {
            alert(message);
            return false
        }
        buttonWatch(this, function(){return buttonProcess("Running a process.")});
    });
});

Comment: Not working for me in either Firefox or Chrome. https://jsfiddle.net/websiter/0xe01mgx/
Comment: If the purpose of your code is to prevent your function to be executed twice on double-clicks, you should probably look at `debounce`. And you might want to start giving hints about the functionality of your code in your questions, just in case there are better ways to do what you want to do.
Comment: @AndreiGheorghiu  I had incorrect coding on the prop disabled settings.  It's been revised.  I'll look at debounce.  Thanks.


plotly multiple lines chart with a varying dataframe

Question: I'm trying to make a function that plots all a Dataframe content.
DF Sample:
print(df2)
                               Close       Close       Close
Date
2018-12-12 00:00:00-05:00  53.183998   24.440001  104.500504
2018-12-13 00:00:00-05:00  53.095001   25.119333  104.854973
2018-12-14 00:00:00-05:00  52.105000   24.380667  101.578560
2018-12-17 00:00:00-05:00  50.826500   23.228001   98.570381
2018-12-18 00:00:00-05:00  51.435501   22.468666   99.605042

Python:
fig = px.line(df2, x=df2.index, y=df2.columns[1:])

I'm trying to plot it but get this error:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

My data frame may have various numbers of columns, so I need my code to plot all columns.
By the way:
print(df2.columns[1:])

Index(['Close', 'Close'], dtype='object')

Answer: Try changing the column names. I used the code above with unique column names for the above data and got the following:
Plot obtained.
Also, you can use the date column as your x-axis in the plot. Plotly will generate a timeseries chart for the same.


Looking for a control theory textbook for a friend

Question: I am looking for a textbook in control theory (for a friend) that covers topics such as Pontryagin's maximum principle. My friend is not a mathematician by trade, but holds a degree in applied mathematics (and is thus not math-shy, but prefers to skip detailed discussions on regularity and prefers intuition). Recent aspects of control theory (e.g., viscosity solutions) need not be present.
(I apologize for all the parameters)
Comment: I also liked  the more recent addition to the literature "Calculus of Variations and Optimal Control Theory: A Concise Introduction" by
Daniel Liberzon.
Comment: You might want to peruse Modern Control Theory (3rd Edition) by William L. Brogan, an amazing book.
Comment: How is this book different from any other control theory book?
Answer:
Lawrence C. Evans, An Introduction to Mathematical Optimal Control Theory, Department of Mathematics, University of California, Berkeley.
Eduardo D. Sontag, Mathematical Control Theory: Deterministic Finite Dimensional Systems, Second Edition, Springer, New York, 1998.
Answer: Although this isn't what your friend wants to hear, I suggest learning about classical control first.
Why?

Classical control preceded optimal control by a bit, and optimal control (at least implicitly) takes note of this. It's true that the most mathematically-oriented references may try to ignore classical control, but most engineering references (in an engineering subject) wont. Someone unfamiliar with the basics wont be able to understand a lot of that content in context.
Optimal control is rarely, if ever, used. There're good reasons for this. Most optimal controls are not feedback networks, but feedback is a must for a good controller. In cases like LQG, when the optimal control is  a feedback network, it often finds gains which are very aggressive and hard to implement. Also, in LQG, the problem assumes full-state feedback, which is rarely available in practice.

I will give you my go-to general reference, which is Astrom and Murray. This has a great exposition of the basics and does touch on modern concepts like optimal control and robust control. There are many other classical controls books out there which you can also look at. This IEEE article names quite a few.


3 camadas vs MVC

Question: 3 camadas:

DAL (Onde fica as classes (model) e as operações com o banco
BLL (Onde fica a regra de negócio)
Apresentação (Geralmente a WEB)

Um exemplo:
DAL
public class AlunoBanco
{
    public void InserirAluno(Aluno aluno){
        ...
        "INSERT INTO ALUNO (aluno)"
        ....
    }
}

public class Aluno
{
    public string ra {get;set;}
    public string nome {get;set;}
}

BLL
public void InserirAluno(Aluno aluno){
    DAL.InserirAluno(aluno);
}

Apresentação
protected void Salvar_Click(object sender, EventArgs e)
{
    var aluno = new Aluno();
    aluno.ra = ra.Text;
    aluno.nome = nome.Text;
    BLL.InserirAluno(aluno);
}

Seria isso um projeto de 3 camadas?
Posso considerar que em um projeto MVC, a única diferença seja a troca da BLL por um Controller?
MVC
Controller:
[HttpPost]
public ActionResult Create(Aluno aluno)
{
    DAL.InserirAluno(aluno);
    return View();
}

Então qual é a diferença entre MVC e 3 camadas?
Posso considerar esse projeto como 3 camadas?
Answer: Seria isso um projeto de 3 camadas?
Sim, você definiu 3 camadas: dados, negócio e apresentação.
Posso considerar que em um projeto MVC, a única diferença seja a troca da BLL por um Controller?
Não. É comum pensarem isso, mas vai um pouco mais além.
Em primeiro lugar, é preciso ver as coisas do ponto de vista de um Model. Um Model é uma classe que define não apenas os elementos de dados, mas quais valores eles podem receber, como são validados e as relações de um Model com outro, coisa que não existe no Modelo de 3 Camadas.
No 3 Camadas, você precisa colocar validações, relações e características de cada entidade  ou na camada de dados, ou na camada de negócio.
Um exemplo de Model:
public class Product
{
    [Key] // Aqui uso um atributo para definir que a propriedade a seguir é chave.
    public int ProductId { get; set; }
    public int CategoryId { get; set; }

    [Required(ErrorMessage = "O Nome é obrigatório.")] // Aqui defini que o campo não pode ser vazio, juntamente com a mensagem de erro que deve ser exibida caso a validação falhe.
    public String Name { get; set; }

    // Aqui defini que um produto pertence a uma, e apenas uma categoria.
    public virtual Category Category { get; set; }

    // Aqui defini que um produto pertence a várias compras.
    public virtual ICollection<Purchase> Purchases { get; set; }
}

Em segundo lugar, a responsabilidade de um Controller é a de harmonizar e arbitrar as relações entre Models. É ele que comanda a criação, modificação, exclusão e seleção dos dados da aplicação. Além disso, é ele que recebe a requisição e decide o que deve ser retornado como apresentação, como por exemplo o formato dos dados (HTML, JSON, e assim por diante).
Há abordagens que procuram colocar uma camada extra para trabalhar juntamente com o Controller, sob a alegação de que não é responsabilidade do Controller de cuidar de regras de negócio. Isto não é verdadeiro se for considerado como aspecto algo que ele é responsável por fazer, no caso, a harmonização de dados entre Models. Em um projeto que use Entity Framework, isto:
var user = context.Users.Find(userId);
var profile = new Profile { User = user };

context.Profiles.Add(profile);
context.SaveChanges();

Ou seja, a criação de um objeto, a atribuição de uma informação ao objeto e o comando de passar o objeto a um contexto de dados faz parte da harmonização entre Models, mas é regra de negócio.
Posso considerar este projeto como 3 camadas?

Grosso modo, sim. O que você fez foi inserir uma camada de "Modelo" (que não é bem "Modelo", mas sim uma camada de Domínio, que é outro conceito). Esta camada "Modelo" pode sim ser vista pela apresentação porque é só uma informação de como serão os objetos de transferência de dados que a aplicação irá usar. É como se fosse um contrato pré-estabelecido entre as 3 camadas. Não havendo regras de negócio nem comportamentos peculiares, vocês apenas estaria seguindo o padrão DDD.
Comment: No meu exemplo defino a classe alunos, na camada de dados. Então na camada de apresentação utilizo essa classe. Isto está errado não? Pois a camada de apresentação não pode ter comunicação com a de dados, certo?
Comment: Não entendi. Estou me referindo ao 3 camadas.
Comment: Vejo em alguns exemplos na internet, utilizarem uma camada chamada DTO.
Comment: Falei bobagem. Deixa eu comentar de novo.
Comment: Então, se você quer usar o objeto de Aluno na apresentação, precisa definir uma 4a camada chamada Domínio, contendo a representação de cada DTO, em outra DLL em separado.
Comment: Mas pelo **3 camadas**, eu não posso utilizar o Aluno na apresentação?
Comment: Sim, pode. Como eu disse, se estiver numa DLL em separado das outras 3 camadas.
Comment: Imaginando que tenho um select que traga todos os alunos, uma List, como a camada de apresentação trata isso, sendo que ela não "conhece" Aluno?
Comment: Adicionei uma imagem na pergunta...
Comment: @Felipe Vou complementar a resposta com essa sua imagem.

3 camadas vs MVC


How do i create complicated content type?

Question: My apologies for bad english.
I want to create educational website with user generated content. Sort of like wikipedia. The problem is content is a little bit complicated.
It must have 4 tabs, which represent 4 stages of learning. Each individual tab must have guide (a basic content page with a text), a f.a.q. page, and a forum for users to open topics related to subject of learning and current stage.
I draw a markup for better undearstanding:

I tried to make it myself by creating a content type with a Field Group module and ended up with this:

Current problems are: a) guide on each tab is just a text but needs to be a title, which leads to page with a guide; b) have comments instead of forum under the tabs and no idea how to make it.
I would absolutely appreciate any help.
Answer: Install Field Collection

Provides a field-collection field, to which any number of fields can
  be attached.
A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

and Field Collection Tab formatter

Field collection tabs provides a field formatter that allows you to
  output a multi value field collection field as a tabset, with one tab
  per field collection item.
You can optionally choose a field from the field collection item to be
  used as the tab title.

modules.
Your common elements, guide, faq, forum goes into the field collection. Also put the stage title as a field in the field collection. Then use the stage title field as the title for the tabs.
Answer: Some tips:

to create link to Guide page you can use Link module
consider use of taxonomy terms for stages
don't apologize for your English ;) It's very good IMO.

More info here: Filter category taxonomy with tabs


PHP rand but with a bigger chance of getting another number?

Question: I have a php file where i want to get a random number, but i want it to be a 80% chance to be 1. And then 20% to be either 2, 3 or 4. Usually you can do something like this:
rand(1, 4)

But i want to have a higher chance of getting 1,  as i explained.
Answer: You can use another rand :
$rand = rand(1, 10);

if ($rand <= 8)
  $value = 1;
else
  $value = rand(2,4);

Answer: Generate a number in [-10, 4] and transform:
$value = max(1, rand(-10, 4))

This will have the correct distribution and ought to perform well. It's not as tractable as a solution involving two draws but it will be faster.
Comment: I came out with this: `$value = abs(rand(-10, 4));`
Answer: Though the answers provided by @Bathsheba and @djidi are the best. Here is a different approach.
Since the 1 part should 80% and the 2,3,4 should be 20%, we multiply the number of random numbers generated so that 3 numbers equal 20% (ending up with 15 in this case):
<?php

$random = rand(1,15);

$result = 0;
switch($random) {
    case 2:
    case 3:
    case 4:
        $result = $random;
        break;
    default:
        $result = 1;
}

echo $result;

Chance to get 1 = 12/15 = 0.8
Chance to get either 2, 3 or 4 = 1/15 = 0.066666666667
In Bathsheba's answer:
Chance to get 1 = 12 * 1/15 = 12/15 = 0.8 (since there are 15 numbers between -10 and 4)
Chance to get either 2, 3 or 4 = 1/15 = 0.066666666667 (since only 3 numbers survive the max() unaltered)
In Djidi's answer:
Chance to get 1 = 8/10 = 0.8
Chance to get either 2, 3 or 4 = 2/10 * 1/3 = 2/30 = 1/15 = 0.066666666667
Math stays the same =)