Simplified Galois proof?

Question: I have learned about Galois epoch-making proof that any polynomial of the fifth degree has no solution representable in terms of its coefficients.
Can his proof be simplified and clarified in modern language? If yes, please show that.
Answer: More accurately, the result is that the general fifth degree equation
\begin{equation}
f(x) = x^5 + a_4 x^4 + \cdots + a_1x + a_0 = 0
\end{equation}with coefficients $a_i\in \mathbb{C}$ isn't solvable by radicals. (Some equations, like $x^5 - 1 = 0$ and the less obvious $x^5 + 20x^3 + 20x^2 + 30x + 10$, are easy to solve, and certain special functions can parametrize the solutions.) That is, there isn't a formula combining via coefficients $a_0, \dots, a_4$ by addition, multiplication, and rational powers that gives the zeros of the quintic $f$. Contrast this result to the quadratic formula or the more complicated results in degree $3$ and $4$.
More formally, the idea is as follows. For simplicity, I'm going to take $a_i\in \mathbb{Q}$. The quintic above is said to be solvable by radicals if there exists a tower of fields $K_0 = \mathbb{Q}\subset K_1 \subset \cdots \subset K_n$ such that $K_{i+1} = K_i(\theta_i^{1/{n_i}})$ for some $\theta_i\in K_i$ and integer $n_i > 0$. By standard Galois theory machinery, this condition is equivalent to $G = \text{Gal}(K_n/K_0) = \text{Gal}(L/\mathbb{Q})$ being a solvable group, where $L$ is the splitting field of $f$. The group $G$ acts faithfully by permuting the roots of $f$ and thus embeds in $S_d$ for $d = \deg f$. The groups $S_1, \dots, S_4$ are solvable, but $S_5$ is not. We thus only need to write down some $f$ with $G = S_5$, which can be done with a bit of computation; $f(x) = x^5 - x + 1$ works, I think.
The argument above is the basic proof you'd see in any first Galois theory class, although the original proof preceded Galois by a decade or so. Here's what looks like a description of that proof, though I've only skimmed it myself. There are more modern proofs; Arnol'd, for example, has one with a topological bent, but it boils down (in more concrete terms) to the fact that $S_5$ is not a solvable group.

Simplified Galois proof?


Disable the SQL powershell prompt

Question: I have just installed SQL Server 2014 Express Exition, and are now faced with a prompt whenever turning to a powershell.
The prompt looks like this: SQLSERVER:\>
How can I disable this behavior and get my good old powershell back?
Comment: a simple `cd C:` for example should take you back into "normal mode", other than the directory you start in there should be nothing keeping you from doing everything you did before. and if this bothers you so much you can change the profile like matt suggests
Comment: This should be in one of the PowerShell profiles i would imagine. Locations: http://technet.microsoft.com/en-us/magazine/2008.10.windowspowershell.aspx
Comment: I had been looking at the various profiles, but was not able to find the modules that were loading. I realized that the profile were setup to run Get-Module -ListAvailable | Import-Module to import a couple of modules that I am using - unfortunately a side-effect is that all possible modules are also loaded, which were the culprit. Thank you for your suggestions.
Comment: To elaborate, SQL Server Express adds to the environment path PSModulePath, which makes the modules load.
Answer: You can't necessarily disable the fact that loading SQLPS drops you in the SQLServer provider.  A workaround would be to push and pop your current location when loading the module:
#SQLPS drops you in SQLSERVER drive.
    Push-Location
    Import-Module SQLPS -DisableNameChecking
    Pop-Location

I would definitely recommend this.  While in the SQLServer provider, you get some wonky behavior (e.g. test-path \path\to\valid\share will fail).
Edit:  Just noticed your comment - you could place the push and pop around the Get-Module -ListAvailable | Import-Module line for the same effect.
Cheers!
Comment: I like it, best answer so far. Accepting it as an answer to my question.

Disable the SQL powershell prompt


How to deal with unbalanced input of reduce task?

Question: Recently I was asked how to deal with unbalanced input of reduce task. I thought for while and try to redistribute the data, but didn't come up with a good solution. Any advice?
Answer: Actually you have 2 ways.

Increase the number of reduces, so your data could possibly better spread along the tasks
Rewrite the partitioner to better distribute the keys over the tasks. [1]

[1] http://hadoop.apache.org/common/docs/r0.20.2/api/org/apache/hadoop/mapreduce/Partitioner.html


Spark Data frame search column starting with a string

Question: I have a requirement to filter a data frame based on a condition that a column value should starts with a predefined string.
I am trying following:
 val domainConfigJSON = sqlContext.read
    .jdbc(url, "CONFIG", prop)
    .select("DID", "CONF", "KEY").filter("key like 'config.*'")

And getting exception:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
  You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near 'KEY = 'config.*'' at line 1

Using spark: 1.6.1

Comment: `KEY` is also a reserved word in MariaDB.
Answer: You can use the startsWith function present in Column class.
myDataFrame.filter(col("columnName").startswith("PREFIX"))

Comment: I had to use `startswith` - all lower-case
Comment: `startsWith`  gives the error _column is not callable_.
Answer: I used the same function but I was getting errors then I checked what is the error?
actually, we need to use startsWith(literals: String) but the above function having lowercase startswith().
Ex :  df.filter(col("ACCOUNT_NUMBER").startsWith("9"))


Approximating the expected value of a random variable as a function of the prior mean of a parameter

Question: I have a parameterized statistical model and I am trying to calculate the expected value of a random variable. I know that the expected value is a function of the value of the unknown parameter. So I have a formula for the expected value as an integral over values of the parameter. But when the integral is complicated, I am looking for an approximation. Let's say I have a prior probability over the parameter values. So I have an expected value for the parameter. How good (or bad) an approximation is it to evaluate the function at the expected value for the parameter?
So I know that $E[X|\theta] = f(\theta)$ and thus $E[X] = \int f(\theta)p(\theta)$, how good an approximation is $E[X] \approx f(\overline \theta)$, where $\overline \theta$ is the expected value of $\theta$?
My suspicion is that if the function is linear (or close to linear) or the prior on the parameter is peaked about the expected value, then the approximation is reasonable.
Comment: I asked this question on math.stackexchange, but maybe it's better suited to this site?
Comment: Please remove questions duplicated on different sites.
Answer: If one follows a Bayesian approach, it should apply to all aspects of the model and not only to one particular parameter $\theta$. Hence I suggest considering the posterior distribution on $\mathbb E[X|\theta]$, which mathematically derives from the posterior distribution on $\theta$. Plug-in estimates contradict one of the reasons for adopting a Bayesian viewpoint, namely to convey uncertainty as well as point estimates.
Comment: I understand that what I'm suggesting is not theoretically very nice, but sometimes you want to take shortcuts, and it's helpful to know which shortcuts are somewhat theoretically legit...
Answer: It's priors all the way down.
How good $\hat{\theta}$ approximates $\theta$ is a conditional probability $p(\hat{\theta}=\theta|M)$ where $M$ is the model you've used to estimate it in the first place.
A good model approximates well, a bad one doesn't. If you have a spectacularly bad model, e.g. you accidentally flipped the sign on your loss function, your estimated parameters may actually drift further away from the true value the more you train them.


Find four digit $abcd$ such that $ab \cdot cd = abcd$

Question: I stumbled upon this problem and I can't seem to figure it out. It's an easy-looking problem and it goes like  this:

Find the $4$-digit number $abcd$ such that if you multiply the two
  $2$-digit numbers $ab$ and $cd$, you again get the $4$-digit number
  $abcd$.

I started like this:
Let $x = 10a + b$ and $y = 10 c + d$, with $a,b,c,d \in \{0,\ldots, 9\}$. The problem is then reduced to: $x\cdot y = (10a + b)(10c+d) = 1000a + 100b + 10c + d$, with the latter being the $4$-digit number $abcd$.
Or equivalently, $$100ac + 10 ad + 10bc + bd = 1000a + 100b + 10 c + d.$$ Unfortunately, this reasoning doesn't get me very far. Any ideas?
Comment: The computer says that the only solution is 0000.
Comment: so $bd + 10X = d + 10Y$ which means $(b-1)d \equiv 0 \pmod {10}$
Comment: My Excel agrees with @MJD
Comment: For proper two-digit numbers, $ab\cdot cd$ is always quite far apart in absolute value from $abcd$: the closest is $10\cdot99 = 990$, which is $109$ away from $1099$. If one-digit numbers are allowed, then $1\cdot1$ is $10$ away from $11$.
Answer: That's impossible!
For $ab * cd = abcd$, $cd$ would need to be at least $100$
Comment: Nice, real smooth!
Comment: @Riley This is assuming we're dealing with a 'proper' 4-digit number of course, i.e. $a > 0$.
Comment: If $ab >0$ and $cd \ge 0$ we get $cd \ge 100$.  Don't see any definition of 4 digit and 2 digit that allow that.  So $ab = 0$ and $0*cd = cd$ so $cd = 0$.  So $(00)(00) = 0000$ is only solution.  At any rate, I'd assume "proper" is a reasonable assumption, as would I assume a,b,c,d are distinct.
Comment: @Bram28, I'm afraid I can't follow, why has $cd$ to be at least 100? You can easily reach a four digit number with 2 digit numbers? E.g. $50 \cdot 50 = 2500  \geq  1000$
Answer: Take your equation
$$100ac + 10 ad + 10bc + bd = 1000a + 100b + 10 c + d$$
and solve for $d$:
$$d = -\frac{10\left(bc+10ac-c-10b-100a\right)}{b+10a-1}.$$
Dividing the numerator by the denominator leaves a remainder of $100$, so $(10a+b-1) \mid 100$. You can take it from there, I bet.
Answer: Hint: I'll use the line to indicate the base-10 representation of the number rather than the product. Consider the thousands digit: on the left-hand side, you know it is equal to the first digit of $\overline{ac}$, plus a possible carry. This should help with some of the case work.
Additionally, taking both sides modulo 5 tells you something helpful about $b$ as well.
Edit: Missed an easy one: $100(\overline{ab}) = \overline{ab00} \leq \overline{abcd}$. So $\frac{\overline{abcd}}{\overline{ab}}$ can't have 2 digits. In fact, we only have equality in the case where $\overline{cd} = 00$, which gives the trivial solution $0000$.
Comment: Sorry, I've read too fast :)
Comment: @Riley understandable, with the notation. I'll fix it real quick.
Answer: I don't think this problem has a solution:
consider the 2 positive integers  $x,y$ that satisfy:
$$
100x + y = xy \\
100x = y(x-1)
$$
looking at the above equation you can see that $x|y(x-1)$ but $x$ and $x-1$ are coprime so $x|y \Rightarrow y=kx \: k \in \mathbb{N}$ and I can rewrite the equations and get:
$$
100=k(x-1) \\
y=kx \\
\therefore y>100
$$
this is a contradiction since $y$ has 2 digits.
Answer: $ab*cd = abcd= 100ab + cd \implies$
$cd = 100 + \frac {cd}{ab} > 100$.
So $cd$ is not a two digit number.
No solution.
(I'm embarrassed to admit I spent an hour on the answer below:)
=========
$(10a +b)(10c + d) = 100ac + (bc+ad)10 + bd = 1000a + 100b + 10c + d$
So $bd \equiv d \mod 10$
So $bd \equiv d \mod 2$.
And $bd \equiv d \mod 5$.
So either $d \equiv 0 \mod 2,5$ and/or $b \equiv 1 \mod 2,5$.
Case 1:  $b \equiv 1 \mod 2$ and $b \equiv 1 \mod 5$. i.e. $b = 6$.
$100ac + (6c+ad)10 + 6d = 1000a + 600 + 10c + d$
$10ac + 6c + ad + d/2 = 100a + 60 + c$
So $d \equiv 0 \mod 2$. And $6c + ad + d/2 \equiv c \mod 10$
So $d/2 \equiv c \mod 2$  and $\frac d2(2a +1) \equiv 0 \mod 5$
So either $\frac d2\equiv 0 \mod 5$ which would mean $d = 0$. Or $2a+1$ is a multiple of $5$ which would mean $a = 2, 7$.
Case 1a) $b = 6; d=0; c$ is even.
$(10a +6)(10c ) = 100ac + 60c = 1000a + 600 + 10c$
$10ac + 5c = 100a + 30$
$c = \frac {20a + 6}{2a + 1}= 10 - \frac 4{2a+1}$.
$a \ne d = 0$ but that is the only possible solution.
Case 1b:$b = 6; d\ne 0;a = 2$
$26(10c + d) = 260c + 26d = 2600 + 10c + d$
$25(10c+d) = 2600$
$10c + d = 104$ which is impossible.
Case 1c) $b = 2; d\ne 0; a = 7$
$76(10c + d) = 760c +76d = 7600 + 10c + d$
$75(10c+d) = 7600$
$10c + d = 101 \frac 13$ which is impossible.
Case 2:  $d \equiv 0 \mod 5$ and $d \equiv 0 \mod 5$ i.e. $d = 0$.
Then
$10c(10a + b) = 100ac + 10bc = 1000a + 100b + 10c$
$c(10a + b - 1) = 100a + 10b = 10*(10a +b -1) +10$
$c = 10 + \frac 1{10a + b -1}$ which is impossible.
Case 3:  $d = 0\mod 5; d\equiv 1 \mod 2$ and $b \equiv 1 \mod 2$.  i.e $d =1$ and $b = 2k+1$
$(10c +1)(10a + b) = 100ac + (a+bc)10 + b = 1000a + 100b + 10c + 1$ so $b =1 = d$ which is impossible.
So Case 4: $d \equiv 0 \mod 2; d\not \equiv 0 \mod 5$ and $b \equiv 1 \mod 5; b \ne 6$.  ie $b = 1$ and $d \ne 0$.
$(10c + d)(10a + 1) = 100ac + 10(ad +c) + d = 1000a + 100 + 10c + d$
$10ac + ad + c = 100a + 10 +c$
$10ac + ad = 100a +10$
$a = 0, 5$ but $a$ cannot be $0$ as $abcd$ and $ab$ are proper 4 and two digit numbers.
So $a = 5$ and $50c + 5d = 510$ so $10c + d = 102$.
There is no solution where $a,b,c,d$ are distinct.


KVM copy contents of image into raw smaller LVM2 partition

Question: I have a KVM guest, running on a KVM host...both Gentoo Linux.
The guest is called webserver.img. It is 21 gigs large, but I am only using 5 gigs inside the image.
I want to make a logical volume with NO filesystem(raw) and have the size about 10gigs, place the contents of webserver.img on it, and boot from the raw logical volume.
How could I get the contents of webserver.img onto ....for example.../dev/mapper/logical_volume1?
I thought about dd if=webserver.img of=/dev/mapper/logical_volume1 but I am worried that will copy over the filesystem or there might be some corruption.
Comment: Does your `webserver.img` have a partition table? Could you check output of `fdisk -l webserver.img` or `file webserver.img`
Comment: Why not use a proper filesystem rather than a disk image?
Answer: You can use image files (as you do now) and you can export block devices (as such). I am not sure whether you can safely write an image file to a block device and use the block device as an image file then. Probably wouldn't make much sense anyway.
You should stay with image files.

make a file system on the LV (e.g. mke2fs -t ext4 /dev/mapper/logical_volume1
mount the volume (mount -t ext4 /dev/mapper/logical_volume1 /mnt/logical_volume1)
shutdown the VM
copy the image file (cp -p /path/to/webserver.img /mnt/logical_volume1)
adapt the VM configuration to the new path (rename the old image file to be sure)
restart the VM


flutter print value of variable by passing variable

Question: I am trying get value of variable.
sample is below.
var X=10 ;
var Y="X" ;
//print(Y) ;
//how i can get print value of Y as 10

Answer: var X= 10;
var Y= X;
// print(Y) ;
// just remove the quote, this will now print 10

Comment: thats ok.  but when i am using visual foxpro, in that we can get value of Y by using    &Y     Is there any facility like this ?
Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.


Invert shipping rate position with VAT field

Question: As described in this post I'd like to invert the row between shipping service and VAT calculation.
I don't know how to use that hook... Can someone tells me more?
Thanks!
EDIT:
I followed the example.
I created the module, it's active and running but I see that nothing happens.
I tell you what I did (it's all in italian):
 - Created posizione_iva.info file with this content
core = "7.x"
description = "Modulo che sposta la riga dell'IVA dopo tutti i valori imponibili."
name = "Posizione IVA"

Created posizione_iva.module and copied the function

I have a doubt about this condition  if (substr($name, 0, 3) == 'iva')
Where can I find the right component name? I tried vat, VAT, iva, tax...
I use the default Drupal Commerce Kickstart installation and the "tax" module.
Answer: I assume that you know how to create a module and what a hook is, you can use hook_commerce_price_component_type_info_alter like this:
<?php
function mymodule_checkout_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  if (isset($components['commerce_price_formatted_amount']['weight'])){

    // Get the row weight of total sum.
    $last_weight = $components['commerce_price_formatted_amount']['weight'];

    // Increase the row weight of the total row, so we can place the vat directly before.
    $last_weight = $last_weight + 100;
    $components['commerce_price_formatted_amount']['weight'] = $last_weight;
  }

  if (is_array($components) && count($components)>0){
    foreach ($components as $name => &$component){

      // Set the weight of the VAT row to the last position before the total sum.
      if (substr($name, 0, 3) == 'vat'){
        $component['weight'] = ($last_weight-1);
      }
    }
  }

  return;
}

Comment: Thank you for your reply, I don't know how to create a module but I see that there's  a lot of documentations about that, so I try to use your code to make my own module, thank you very much!!!


Showing the existence of the $\omega_\omega$-th power set of $\omega$

Question: Can you tell me if my answer is correct:
Show that the set $P^{\omega_\omega}(\omega)$ exists.
My answer:
Let $P^0 (\omega) = \omega$, $P^{\alpha + 1}(\omega) = P(P^\alpha (\omega))$ and for a limit ordinal $\lambda$ let $P^\lambda (\omega)  =\bigcup_{\beta < \lambda} P^\beta (\omega)$.
The transfinite recursion theorem tells us that if $G: V \to V$ is a class function from the class of all sets to the class of all sets then there exists a unique function $F: ON \to V$ with $F(\alpha) = G(F\mid_\alpha)$.
Hence to show the existence of $P^{\omega_\omega}(\omega)$ we need to define a $G: V \to V$ with $G(F\mid_{\omega_\omega}) = P^{\omega_\omega}(\omega) = F(\omega_\omega)$.
Also we know that for successor ordinals $\alpha$ we want $F\mid_{\beta + 1} = F(\beta) = P^{\beta}(\omega)$. So for successor ordinals $\alpha = \beta + 1$ we define $G(F\mid_{\alpha})= G(F\mid_{\beta + 1}) = G( P^{\beta}(\omega)) := P( P^{\beta}(\omega))$.
We also know that $F\mid_\varnothing = \varnothing$ so $G(F\mid_\varnothing) = G(\varnothing) := P^0 (\omega)$.
Finally, if $\lambda$ is a limit ordinal we want $G(F\mid_\lambda) := \bigcup_{\alpha < \lambda} P^\alpha (\omega)$.
For all other sets we define $G$ to map to the empty set.
Thanks for your help.
Answer: Yes, your formalization of this instance of the transfinite recursion is correct.
One quibble is that when defining $G$, you shouldn't refer to $P^\beta(\omega)$ at all, since this makes your definition circular. Similarly, you shouldn't think of $G$ as defined on the unique $F$ you are trying to build, since you don't have it yet when defining $G$. Thus, you should define $G(f)$ to be $P(f(\beta))$, when $f$ is a $\beta+1$-sequence, and in the limit case, $F(f)=\bigcup_{\alpha\lt\lambda}f(\alpha)$, when $f$ is a $\lambda$-sequence for limit ordinal $\lambda$.
But I would add that I don't find it necessary to give a laborious definition of $G$ as you do in the latter part of your post. Your initial definition of $P^\beta(\omega)$ in the fourth line of your post already contains a complete definition of $P^\beta(\omega)$ from earlier instances of $P^\alpha(\omega)$, and thus serves as a complete account of the recursion. The detailed definition of $G$ that you give amounts basically to rewriting that initial definition in more detail. But the recursion is perhaps clearer without the extra detail (provided that one is clear on why recursion works).
Comment: Thanks. So I'll write $G(\langle f_0, f_1, \dots, f_{\alpha}\rangle) := P(f_{\alpha})$ if $\alpha$ is a limit ordinal and $G(\langle f_0, f_1, \dots\rangle) := \bigcup_{\alpha < \lambda}P(f_{\alpha})$ if $\lambda$ is a limit ordinal.


Find a process by name and kill it

Question: So, I want to send a kill to a process, I know it's name
ps -ef | grep '_rails master'
root      2388     1  0 19:46 ?        00:00:04 unicorn_rails master -c /web/hero/config/unicorn.rb -E production -D
root      2582  2172  0 20:28 pts/0    00:00:00 grep --color=auto _rails master

It is unicorn_rails master [..] how do I kill it?
I tried so far: sed and expr. But cant pass it as param to kill
Comment: Note that system services often come with start/stop scripts that do this work for you.  I have no idea but maybe this unicorn_rails might have something like that under /etc/init.d for example.
Answer: There exists a more direct command called pkill. Usage is as follows:
$ pkill "process name here"

Comment: also do `pkill -f 'unicorn_rails master'` if theres going to be multiple instances of the program running and you only want to kill that one
Answer: You can the command:
$ sudo kill `pidof process_name`.

You can use also:
$ sudo killall process_name

If you want to use grep, you can try:
$ ps -ef | grep '_rails master' | grep -v grep | awk '{print $3}' | sudo kill

Answer: You can use the following:
ps -ef | grep [u]nicorn_rails | awk '{print $2}' | sudo xargs kill

Note, the [] in 'grep [u]nicorn_rails' keeps you from matching on the grep command in the ps tree.

Find a process by name and kill it


Atribuir a vários elementos valores diferentes usando mesma função

Question: Veja, tenho 5 IDS(5 elementos DOM) e preciso, usando a função text() do JQuery, adicionar a cada um deles um texto diferente, posso fazer assim..
$("#ID1").text("bla");

$("#ID2").text("blabla");

....
Existe uma maneira, menor, simplificada, de fazer isso, se os textos fossem iguais, poderia separar por vírgula os seletores, mas não são..
Pensei em algo como:
.text(function() {
$("#ID1") = "bla";
$("#ID2") = "blabla";
});

Enfim, alguma sugestão, até mesmo para boa prática e para manter o código simplificado e limpo.
Comment: De onde vem esse texto? dá para ter esse texto numa array para fazer o código mais auto-mágico? Outra pergunta:  as ID diferem somente pelo numero?
Comment: veja esse exemplo utilizando uma funçãozinha básica: http://jsfiddle.net/z7Leskqb/
Comment: Alexandre viste o meu comment em cima?
Comment: @Sergio, o texto é estático, ele não é gerado randomicamente, ou de qualquer forma, mas são 5 textos diferentes. Dá para coloca-lo em um array. As IDS não se diferem por números, elas são totalmente diferentes.
Comment: Interessante @WallaceMaxters, vou ver melhor como funciona!
Answer:

  var addText = function(array, element){

        $(element).each(function(i){
            $(this).text(array[i]);
        });
    };

    $(function(){
      var array = [
          "meu primeiro texto",
          "Meu segundo Texto",
          "Meu terceiro texto",
          "E assim por diante",
       ];

        addText(array, '.CLASS');
    });

    addText(array, '[id^=ID]');
.CLASS{
  border:1px solid red;
  height:50px;
}

Comment: Olha só uma outra maneira quase igual, mas que me parece mais idiomática em jQuery: http://jsfiddle.net/nLxn4wpk/
Answer: Você pode criar um objeto formato dicionário, onde as chaves são os IDs das divs, e os valores são os respectivos textos. Depois basta percorrer o dicionário para preencher as divs:

var textos = {
    "id1" : "bla",
    "id2" : "blabla",
    "foo" : "bar" // , etc
};
$.each(textos, function(chave, valor) {
   $('#' + chave).text(valor);
});

Comment: A diferença é que, com `Arrays`, você pode depende da posição dos elementos dentro do `DOM` e, com `Object`, você especifica qual texto quer em qual lugar, dinamicamente!.
Comment: @Wallace Maxters, deu uma solução perfeita.
Comment: Se as classes fizerem sentido, a solução dele é boa sim. Mas a minha tem algum problema para merecer o voto contra?
Comment: Tem sim. Existem muitas soluções boas e mais recomendadas que esta, no caso a do amigo, @Wallace Maxters. Também já passei por isso. Criei uma solução, mas deram-me negativo, NÃO PORQUE ESTAVA ERRADA, mas sim por que não era a melhor solução. Você é moderador, vai entender: http://pt.stackoverflow.com/questions/45287/criptografar-senha-e-se-logar-php-e-pdo/45304#45304
Comment: Eu não concordo, mas ok. Sobre a sua outra resposta, aqui não é o lugar para discutirmos. Se quiser, pode abrir uma discussão sobre o assunto no [meta].
Comment: A solução do @bfavaretto também foi legal sim. Eu utilizaria a ideia dele e lançaria dentro de uma `function` (pois a ideia que expressei na resposta foi pensando que a operação seria reutilizada, e não apenas ser usada uma vez). Pois, se a operação fosse realizada uma só vez, não tem por que colocar numa função - e, portanto, o exemplo dele é totalmente válido.
Comment: Certo e quando você pretende marcar como solução do seu problema? Ou Nenhuma dessas respostas resolve o seu problema?


Javascript for/in loops through properties, not indexes and returns strings

Question: Ok, I have this code:
var room = [ { time: 0, people: 0 } ];

and then:
time = 5;
for( var i in room ) {
  if( room[i].time < time ){
    spliceIndex = i + 1;
  }
}
console.log(spliceIndex);

And the console reads: 01 - Which means the 1 is concatenated which further means that i is a string, and not an integer as expected. Casting the index to integer fixed the problems, but I was banging my head for hours.... Can anyone explain why is this happening? I get this on Firefox 3.5 and Safari 4.
Comment: Not an answer to your question, but you may want to use hasOwnPropertyin your for...in loops: http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object
Answer: Because for-in lists object properties, not array indexes. Object properties are strings, and array indexes show up as properties, only they are numeric strings.
Comment: That's why it's not a good idea to use a "for in" loop on arrays. They iterate over *all* the array's properties (except the built-in ones, which are non-enumerable), including string properties and properties inherited from Array.prototype.


Perfect 4th as a starting note of a phrase. What does it do?

Question: I was listening to Eric Clapton's guitar playing on All Along the Watchtower. The chord progression is very simple, which is I-VII-VI-VII in a key of C minor. Most of the time, he played based on root note and 5th. But some occasions, he chose perfect 4th for the starting note or the ending note of the phrase. For example, he played perfect 4th as the opening of his 2nd solo. I find this very unusual because I always thought I should start with root, 5th, or 3rd. Can someone explain this to me? How does it work? What does it do?
Comment: Do you mean a fourth above the root of the chord?
Answer: There are no rules.
What the fourth degree of the scale "does" as the starting note of a phrase is too general a question. It depends on what happens next, on style, and whether the idea of function is even relevant. I had a listen to one of the solos you mentioned starting on the fourth degree. There, it is eventually bent down to the third. In common practice, functional, terms, this would be an appoggiatura. Applying the term to what Clapton is doing feels out of place. Other members more familiar with this style will have more to offer.
As for finishing a phrase with this degree, note that this is happening against the chord you have labeled VII, in which context it is the fifth degree.
Answer: The notes of the chord are a framework, not a restriction.
I expect you're familiar with the idea of there being a scale that corresponds to a chord? (That's another framework rather than a restriction by the way!)  If you want permission for the 4th, think of it as being part of that scale.  Probably the phrase will eventually settle on one of the chord notes.
Trouble is, he could have just as well have started on a note that wasn't even in the 'scale of the chord'.  Then we'd have had to find another bit of 'theory' to justify it!  Sorry, 'rules' aren't all that useful.  I'd stick to descriptions if I were you.  You've discovered another 'thing that sounds good' for your musical kit-bag.  Good!
Answer:
Perfect 4th as a starting note of a phrase. What does it do?

I assume this means a P4 above the chord root.
Almost always you need at least two events to understand what is happening with a music device. In this case the obvious question is where does the note forming the P4 move? As a non-chord tone it creates a dissonant tension. Does it resolve? Does it move without resolution? Only after you know what happens next can you say what that tone is doing.
If it does resolve, you might say the note was an appoggiatura or suspension etc. providing tension and it resolved into a chord tone.
If it did not resolve, you might say some kind of extended chord harmony is being used where the P4 above a root isn't considered a dissonance but is a bona fide chord tone (like quartal harmony, but this isn't likely in this case.)

I always thought I should start with root, 5th, or 3rd

You can think of this as a 'rule' or 'convention', but then you need exceptions and justifications for breaking so-called rules. That approach to music feels tedious. I think it's better to know the underlying musical principles.
Starting on the root, 5th, or 3rd is another way of saying start on a chord tone. But, why start on a chord tone? Because, that will provide harmonic clarity and stability. Is there a reason to not start on a chord tone? Yes, if all notes are chord tones, a melody can become bland. Using non-chord tones adds tension and interest to a melody.
Instead of a rule about permissible starting points we now have an understanding of the musical principles about tension and stability and how to make music expressive and interesting. It doesn't really matter whether a starting note is this or that. It matters how tension is handled for expressive purposes.
At the heart of every so-called "rule" is some musical principle to explore and understand. When you encounter a "rule" try to understand the underlying principles.
Answer: 'I always thought I should start...' Who told you that? Of course chord tones are more usual than any other notes to match to the chord, but since there are no rules, anything goes. (What a great title for a song...).
If a phrase starts on 4 (or 2) it could be conceived that it's a suspension, which generally resolves to - a chord tone! Clapton also used b7 as a start note to a phrase, bending up to the root note as he went. It's a common blues trick, just as playing b5 and bending up to P5, or even b5 and letting down to - that P4 again!
Answer: The chord progression is as you say I - VII - VI - VI (C -  Bb - Ab - Bb)
The  4th is an up-beat and actually the 5th of the previous chord (F in Bb)
(In the first solo Clapton plays even a chromatic approach (F# ->G) and the solo starts with the 5th.)


Most groups are noncommutative

Question: From page 41 of Evan Chen's napkin it states that most groups are noncommutative. This led me to think about an unconventional question: let
$$C_n:=\text{number of nonisomorphic abelian groups of order }n$$
$$G_n:=\text{number of nonisomorphic groups of order }n.$$
Are there any known results on $\limsup_{n\rightarrow\infty}\frac{C_n}{G_n}$ or $\liminf_{n\rightarrow\infty}\frac{C_n}{G_n}$? Notice from here, for $p$ prime we have $C_{p^3}/G_{p^3}=3/5$, so we can deduce
$$\liminf_{n\rightarrow \infty}\frac{C_n}{G_n}\leq\frac{3}{5}$$
and also since $C_{p^2}/G_{p^2}=1$, we have
$$1\leq \limsup_{n\rightarrow \infty}\frac{C_n}{G_n}.$$
My question is, can these bounds be improved, and is determining the exact value possible?
Edit: I realize that since $C_n/G_n\leq 1$ for all $n$, we obviously have $\limsup_{n\rightarrow\infty}C_n/G_n=1$. So forget about that.
Comment: Since the limsup can't be $>1$ you can change the second "$\le$" to just "$=$" - also, it's easier to consider $p$ rather than $p^2$ there, but that's a side point.
Answer: If $n=2^k$, $k\gg 1$, then $C_n\ll G_n$, so the $\liminf=0$.
Comment: Proving the lower bound on the number of groups of order $2^n$ (a result of Graham Higman) is not exactly routine, but it is not seriously difficult, and it is worthwhile and instructive  to try and read and understand the proof. The bound is derived by considering 2-groups $G$ in which $G$ and $G/Z(G)$ are both elementary abelian.
Comment: To make this precise: there are $2^{\frac{2}{27}n^3+O(n^{8/3})}$ groups of order $2^n$, and there are only $p(n) \sim \frac{1}{4n\sqrt{3}} e^{\pi \sqrt{2n/3}}$ abelian groups of order $2^n$. From this you can easily show that $\lim_{n \to \infty} C_{2^n}/G_{2^n} = 0$.
Comment: See this MO question: https://mathoverflow.net/questions/30358/number-of-non-abelian-groups-of-order-2n
Comment: Thanks all. The length of the answer made me think that $C_n\ll G_n$ is obvious, but turns out that there are deeper results involved.
Comment: What result are you using to argue $C_n\ll G_n$?
Comment: Right. The first estimate is in the first (highest upvoted) answer to the question in my link. The second follows because every abelian group is a direct product of cyclic groups (so $p(n)$ is the partition function),
Comment: It is not obvious. It is just "well known to specialists". "Almost all finite groups are non-Abelian 2-groups" - is what most people dealing with finite groups believe is true.

Most groups are noncommutative


C# Threading - All threads are calculating same random value , why is that?

Question: program is asking 10 threads and launching it on a function which is printing random value , but all those threads are printing the same Random value .
My friends says that it is due to thread are using rand calculation at same CPU clock so that is why. Is he right
And if there is a solution for it ?
      private DateTime randomNum()
    {

         Random r = new Random();
        int rInt = r.Next();
    }

button_click1
         for (int i = 0; i < numofThreads; i++)
        {

            res[i] = delcall.BeginInvoke(null, null);
        }
        //int[] num = new int[numofThreads];
        for (int i = 0; i < numofThreads; i++) {
            DateTime dt = delcall.EndInvoke(res[i]);
            richTextBox1.AppendText(dt + "\n ");
        }

Comment: This has been asked heaps of times, you need to put `private Random r = new Random();` outside the function, declaring it each time will make non-random. I'l l find the duplicate
Answer: Don't create a new instance of Random every time. If multiple Random instances are created at the same time, their seed is the same. This means they all behave equal. Just use one Random instance multiple times. Therefore declare it outside of the method.
private readonly Random r = new Random();
private DateTime randomNum()
{
    int rInt = r.Next();
}


Infinitely Generated Slides but Not Looping

Question: I want to create a date picker that is in the form of a slider. It displays five dates and you click the next button to see more future dates. I used slick slider as my base and I have JQuery populating the DIVs with dates.
HTML

JQuery
var value = moment().subtract(2,'days');

$(".slider").each(function() {
    var dayFormatted = moment(value).format("DD" + "
" + "MMMM");
    $(this).html(dayFormatted);
    value = value.add(1,'days');
});

$('.carousel-items').slick({
        dots: false,
        infinite: true,
        slidesToShow: 5,
        slidesToScroll: 1,
        accessibility:true,
        arrows:true,
        lazyLoad: "progressive",
        prevArrow: '<button class="slick-prev date-carousel-back"></button>',
        nextArrow: '<button class="slick-next date-carousel-forward"></button>',
    });

My problem is, I can't figure out how to generate the future dates on the fly (most likely with the button click). Slick has attributes that if you set
infinite: false; then the slider stops at the last DIV you manually created on the HTML page. However, if infinite: true; then the slider loops.
My attempt to append DIVs within the slider:
$('.slick-next').click(function(){

   $(".carousel-times").append('"
test
"');
        });

A theory I had to solve this problem was to set the DIV text values as variable and then edit the variables on the fly in order to give the appearance that you're cycling through.
Does anyone have any other suggestions? Or tactics to solve this problem?
Thanks in advance!
Answer: You probably need read some documentation. http://kenwheeler.github.io/slick/ <- Add and remove section. Here is example of dynamic adding slides.
So you should use something like
$('.slick-next').on('click', function() {
    $(".carousel-times").slick('slickAdd','
test
');
});

Cause function .slick('slickAdd'), will properly update your slider instead just add one more element.


Timer in Java that doesn't pause the program?

Question: I was wondering if there was a form of timer that I can use that doesn't pause all of my code Thread.sleep(ms) is not what I need because it pauses all of my code.
EDIT: Okay, I think I misworded that. Here's my edit:
Is there a way to measure a certain amount of time in Java without pausing my main method?
Comment: see http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html and http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
Comment: What are you trying to do???
Answer: I like to using Executors class. It have a nice method that is newScheduledThreadPool. It gives you an ScheduledExecutorService instance, which have a lot of scheduling methods.
Check it out here here:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(threadToExecute, 10, TimeUnit.SECONDS);

This code will start threadToExecute thread after 10 seconds, without pausing your main thread.
Comment: TimeUnit is not a class that can be imported.
Comment: I didn't get it. `import java.util.concurrent.TimeUnit;`
Comment: Thanks. Control + Shift + O wasn't working. Also, what is threadToExecute? Could you please provide an example.
Comment: One more thing: It says that the first parameter is a Runnable or a Callable. How do I use these?
Comment: It is the effective thread to execute. Most of the times it is a class that extends `Thread`. Please take a look at: http://docs.oracle.com/javase/tutorial/essential/concurrency/
Answer: Depends on which Frameworks you use. A pretty generic way would be to start a new Thread, pause that Thread via Thread.sleep(ms) and then do whatever you want to do after that delay, but of course that requires a little bit of care because of concurrency issues.
Comment: I am sure java has some builtin timer api
Comment: You are right, of course, there is, java.util.Timer, for example.
Comment: But, is there like a something that can measure time without pausing the program?
Comment: Neither an extra Thread not Timer (which does something similar) will pause your main Thread and thus not the program...
Answer: You might want to look into the Timer class. You can attach it to a thread, schedule events, and add delays. What you could do with this is you could create a thread to run along side your main thread and have it run from there. Because they will be on two completely different threads, you don't need to worry about them interfering with each other. To run the other thread, you could create a class that extends Thread and run it. Then use the Timer(String name) constructor to create a Timer for the thread.


Derivative with Reparameterisation Trick

Question: Below is some steps for differentiating a function wrt a set of parameters $\phi$ using the "reparameterisation trick" (Kingma & Welling 2013).
However after applying the derivative as follows I cannot follow how the underlined portion of the derivative came about. Could someone simplify or explain the origin of this term?
Comment: Do you understand where the second term on that line comes from?
Comment: Yes. That is chain rule. To be honest I only would have ended up with the second term and not included the first term
Answer: While you are right on the second term and the use of the chain rule, your distribution $q$ also directly depends on $\phi$ as made explicit by the subscript $q_\mathbf{\phi}$. That's why I prefer the notation $q(\cdot \, ;\phi)$, everything is more clear.
Denoting from the beginning: $\theta = f(\epsilon \, ; \phi)$ and $g = \log q(\theta \, ; \phi)$, we have using Leibniz's notation:
\begin{align*}
  \frac{\partial g(\phi, \theta)}{\partial \phi} = \left. \frac{\partial g(\phi, \theta)}{\partial \phi} \right|_{\theta = f(\epsilon \, ; \phi)} + \frac{\partial g(\phi, \theta)}{\partial \theta} \frac{\partial f(\epsilon \, ; \phi)}{\partial \phi} \; \textrm{,}
\end{align*}
where the derivative of the first term on the right-hand side is computed with $\theta$ fixed


access database cannot execute SQL LIKE

Question: I am not able to query records from my database, and getting "UCAExc:::4.0.2 Invalid argument in JDBC call: parameter index out of range: 1" error message
How is this caused and how can I solve it?
    public void  query(){
    String name = name_tt.getText();
    DefaultTableModel model= new DefaultTableModel();
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(0, 283, 555, 212);
    contentPane.add(scrollPane);

    table = new JTable(model);
    scrollPane.setViewportView(table);
    model.addColumn("ID");
    model.addColumn("IDs");
    model.addColumn("Name");
    try
    {
        PreparedStatement pst = con.prepareStatement("SELECT * FROM TEST
        WHERE IDs LIKE '?*' ");
        pst.setString(1, name);
        ResultSet rs = pst.executeQuery();
        while(rs.next())
        {
            model.addRow(new Object[]{rs.getInt(1),rs.getString(2),rs.getInt(3)});
        }

    }
    catch(Exception e){
        System.out.println(e.getMessage());

    };

}

Answer: You need to do
PreparedStatement pst = con.prepareStatement("SELECT * FROM TEST WHERE IDs LIKE ?");
pst.setString(1, name + "*");
ResultSet rs = pst.executeQuery();

That way the parameter placeholder ? is part of the basic SQL statement, instead of being part of a string literal within the SQL statement.

access database cannot execute SQL LIKE


Help with tonicization, modulation and modal interchange

Question: I'm currently writing a short piece of music for a university assessment, and there are a number of conditions in place as far as what it must contain. About half of them I'm confident I can implement, but these I'm a little confused by:

Tonicization by secondary dominant
Modulation by direct, pivot chord, dominant chord or transitional
Modal Interchange

I've started writing chords and melody in the key of D minor, any advice for me as far as adding in those techniques? Apologies if this is basic knowledge, theoretical songwriting is not at all my strong point - always been a by ear kind of musician.
Comment: Please do not hesitate to ask your instructor and/or TA.  The particular assignment may have some specific things in mind that folks here might have trouble anticipating.
Answer: These concepts are concepts that you should have learned in class. It's an assignment, so no one expects it to be genius stuff.  Here's my advice:
1.) Talk to your professor - ask to meet and get some 1-on-1 clarification.
2.) If they are too busy, try to schedule a time with your TA/GA. Chances are likely that they are masters candidates in composition and shouldn't have any problems helping you.
3.) If they are both busy, talk to your classmates - your colleagues who are either very confident in theory or the composition majors, who will also obviously be confident in music theory.
4.) Study your textbook - it will have definitions for all of these things and will provide examples for how they are used.  For the part where you need to use these things, just copy the gesture out of the textbook (of course transposing) and then fill in the rest of your "piece" with original material.
5.) I will clarify one thing for you, something which theory books are not always clear about. With tonicization, the tonal shift is very temporary (1-2 beats). With modulation, the tonal shift is more permanent, such as a new movement, a new section in the music, an "answer" in a fugue, or extended phrases / periods.
Comment: I am very shy, unfortunately I have never fared well in asking for teachers help and as such I have found myself in this predicament with a lot of poor marks and a lot of building blocks missing. I appreciate the advice though. I am reading up as much as I possibly can to try and understand this.
Comment: At some point you're going to need to learn to ask someone for something; better learn to do it now before you get to a job and could be fired because you didn't do something correctly and never asked. A professor is not going to fail you for asking questions. Teaching college myself, I always wish students would stop by my office during office hours - especially the ones who need it.
Answer: Although I agree with JJM you should be comfortable with this if you are writing assignments on it. I will like to add some thoughts on point two.

Modulation by direct, pivot chord, dominant chord or transitional

This simply puts mean they want you to modulate to the dominant and the modulation has to be clear. You say you are in d minor so a modulation to the dominant would entail you going to a minor key.
The pivot chord is a chord that may belong to both the keys. I think a good pivot chord would in this case D/F/A It is the Tonic chord in the root key and the Sub dominant chord in the key you are modulating to.
So you can have a modulation to the Dominant by having lets say an interrupted cadence at the end of a phrase( V-vi) then in the first bar of the new phrase you can go to the pivot chord and then you can make your modulation clear by go to the dominant chord of the new key and making the modulation clear by using the leading tone of the key (G#).
You should also consider using the melodic minor form as this makes the modulation crystal clear.
Comment: Hi Neil, thank you so much for your advice - one question I have is why does the fact that I am in D minor to start off with mean modulating to a minor key - the impression I've been getting is that modulating to your keys relative major (F in this case) is the way to do it. I'm very confused though, so any explanation would help. I'm pouring over my textbook and websites but it's not changing a lot.


Showing that composition can be represented by a map

Question: I want to prove proposition 5.6 in Lawvere and Rosebrugh.
The proposition goes like this.
Suppose $g:B \to Y_1$ and $\phi: Y_1 \to Y_2$ are arbitrary.
There exists a $\ulcorner c \urcorner: Y_2^{Y_1} \times Y_1^B \rightarrow Y_2^B$, such that $\ulcorner c\urcorner (\ulcorner \phi \urcorner,\ulcorner g \urcorner) = \ulcorner \phi g \urcorner$.
Now to start define $c: Y_2^{Y_1} \times Y_1^B \times B \to Y_2^B$ as the composite of $1 \times \text{eval}_1: Y_2^{Y_1} \times Y_1^B \times B \to Y_2^{Y_1} \times Y_1$ and $\text{eval}_2: Y_2^{Y_1} \times Y_1 \to Y_2$, where $1: Y_2^{Y_1} \rightarrow Y_2^{Y_1}$ is the identity. Then I wan't to invoke the universal property of one of the exponentials, in order to get $\ulcorner c \urcorner$ and then prove the equality in question, but I can't find the right one to use.
Answer: Since I don't know the book and since I can only guess what the notation is supposed to mean, I'll assume that this takes place in a cartesian closed category with terminal object $1$. If I interpret the question correctly, what we're trying to prove is the existence of the so-called internal composition. That is, the morphism $c\colon Y_2^{Y_1}\times Y_1^{B}\to Y_2^{B}$ which makes the diagram
$$\require{AMScd}
\begin{CD}
Y_2^{Y_1}\times Y_1^{B}\times B @>{c\times \mathrm{id}_B}>> Y_2^{B}\times B\\
@V{\mathrm{id}\times\mathrm{ev}_{B,Y_1}}VV @VV{\mathrm{ev}_{B,Y_2}}V \\
Y_2^{Y_1}\times Y_1 @>{\mathrm{ev}_{Y_1,Y_2}}>> Y_2
\end{CD}$$
commute.
Since the adjunction map $\mathrm{hom}(Y_2^{Y_1}\times Y_1^{B},Y_2^{B})\to \mathrm{hom}(Y_2^{Y_1}\times Y_1^{B}\times B,Y_2)$ maps an arbitrary morphism $f\colon Y_2^{Y_1}\times Y_1^{B}\to Y_2^{B}$ to the composition
$$Y_2^{Y_1}\times Y_1^{B}\times B\xrightarrow{f\times\mathrm{id}_B}Y_2^{B}\times B\xrightarrow{\mathrm{ev}_{B,Y_2}}Y_2,$$
we see that $c$ is just the unique element corresponding to $\mathrm{ev}_{Y_1,Y_2}\circ(\mathrm{id}_{Y_2^{Y_1}}\times\mathrm{ev}_{B,Y_1})$.
Finally, precompose the diagram with $1\times 1\times B\xrightarrow{([\phi],[g])\times\mathrm{id}_B}Y_2^{Y_1}\times Y_1^B\times B$ and combine all the present adjunctions to conclude that $c([\phi],[g]) = [\phi\circ g]$.
Addendum: After having a look at the book in question and reading the question again, I realised that the above is not much more than the OP already knew. Here we go again, but using different words.
The universal (exponential) property of $Y^B\times B\xrightarrow{\mathrm{ev}_{B,Y}}Y$ is this: For every $X$ and each map $f\colon X\times B\to Y$ there exists a unique $[f]\colon X\to Y^B$ such that the composition
$$X\times B\xrightarrow{[f]\times\mathrm{id}_B}Y^B\times B\xrightarrow{\mathrm{ev}_{B,Y}}Y$$
equals $f$.
I'd rather conflict with the OP's notation than with mine above. Therefore, we define $f := \mathrm{ev}_{Y_1,Y_2}\circ(\mathrm{id}_{Y_2^{Y_1}}\times\mathrm{ev}_{B,Y_1})\colon Y_2^{Y_1}\times Y_1^{B}\times B\to Y_2$ and from the exponential property (where $X = Y_2^{Y_1}\times Y_1^{B}$ and $Y = Y_2$) we get $c := [f]$, the unique map $c\colon Y_2^{Y_1}\times Y_1^{B}\to Y_2^{B}$ making the above square diagram commute.
It remains to show that $c([h],[g]) = [h\circ g]$ for every pair of maps $g\colon B\to Y_1$ and $h\colon Y_1\to Y_2$ where $[g]\colon 1\to Y_1^B$ and $[h]\colon 1\to Y_2^{Y_1}$ are the unique maps such that
$$B \xrightarrow{[g]\times \mathrm{id}_B}Y_1^B\times B\xrightarrow{\mathrm{ev}_{B,Y_1}}Y_1$$
equals $g$ and
$${Y_1} \xrightarrow{[h]\times\mathrm{id}_{Y_1}} Y_2^{Y_1}\times Y_1\xrightarrow{\mathrm{ev}_{{Y_1},Y_2}}Y_2$$
equals $h$. Thus, $h\circ g\colon B\to Y_2$ equals
$$
B\to 1\times 1\times B
\xrightarrow{1\times [g]\times \mathrm{id}_B}1\times Y_1^B\times B
\xrightarrow{1\times \mathrm{ev}_{B,Y_1}}1\times Y_1
\xrightarrow{[h]\times \mathrm{id}_{Y_1}}Y_2^{Y_1}\times Y_1\xrightarrow{\mathrm{ev}_{{Y_1},Y_2}}Y_2
$$
and substituting identities gives
\begin{align*}
h\circ g &= (B\to  1\times 1\times B
\xrightarrow{[h]\times [g]\times \mathrm{id}_B}Y_2^{Y_1}\times Y_1^B\times B
\xrightarrow{\mathrm{id}_{Y_2^{Y_1}}\times \mathrm{ev}_{B,Y_1}}Y_2^{Y_1}\times Y_1
\xrightarrow{\mathrm{ev}_{{Y_1},Y_2}}Y_2)
\\&=
(B\to  1\times 1\times B
\xrightarrow{[h]\times [g]\times \mathrm{id}_B}Y_2^{Y_1}\times Y_1^B\times B
\xrightarrow{c\times\mathrm{id}_B}Y_2^{B}\times B
\xrightarrow{\mathrm{ev}_{B,Y_2}}Y_2)
\\&=
(B\to 1\times B
\xrightarrow{c([h]\times [g])\times \mathrm{id}_B}Y_2^{B}\times B
\xrightarrow{\mathrm{ev}_{B,Y_2}}Y_2).
\end{align*}
But this implies $c([h], [g]) = [h\circ g]$.
Comment: By the $\ulcorner g \urcorner$ for a morphism $g$ is just mean it's exponential transpose. I am not entirely comfortable with adjunctions yet, so, I am a little weary in using it. Is it possible to prove purely equationally, by using the fact that $\ulcorner g \urcorner$ has the exponential property uniquely? Many thanks!
Comment: Let me first get straight what the *exponential property* says; is it this: given $g\colon B\to Y_1$ there is a unique $[g]\in \mathrm{hom}(1,Y_1^B)$ such that the composition $$B \xrightarrow{\mathrm{id}_B\times 1} B\times 1 \xrightarrow{\mathrm{id}_B\times [g]}B\times Y_1^B\xrightarrow{\mathrm{ev}}Y_1$$ equals $g$? Note that this defines a bijection $\mathrm{hom}(B,Y_1)\to \mathrm{hom}(1,Y_1^B)$. Do you also have an exponential property at hand which says that there is a similar bijection $\mathrm{hom}(Y_2^{Y_1}\times Y_1^{B}\times B,Y_2)\to \mathrm{hom}(Y_2^{Y_1}\times Y_1^{B},Y_2^{B})$?
Comment: I have at hand, the general universal property of exponentials, since I am in the category of sets, and have this as an axiom, so I can do all that, yes.
Comment: I had a look at this book. You can replace each of my 'adjunction's by 'exponential property'. Take $f := \mathrm{ev}_{Y_1,Y_2}\circ(\mathrm{id}_{Y_2^{Y_1}}\times\mathrm{ev}_{B,Y_1})\colon Y_2^{Y_1}\times Y_1^{B}\times B\to Y_2$ and use the exponential property to get $\ulcorner f \urcorner$ such that $\mathrm{ev}(\ulcorner f \urcorner\times\mathrm{id}_B) = f$. This $\ulcorner f\urcorner$ is my $c$ above.
Comment: Okay, so if I do the last composition you mention, i get $ ([c] \times 1_B)( ([\phi],[g]) \times 1_B ) = [c]([\phi],[g])\times 1_B$ using the functoriality of products. But when I do the other side of the equation, I get $(id \times eval) (([\phi],[g]) \times 1_B)  = (id ([\phi],[g])) \times (eval 1_B)$ again by product functoriality, but that last bit seem to not make any sense to me, since $eval 1_B$ is not even defined?
Comment: Dear @Bartuc, I added the details.
Comment: Thank you very much! One last question, the $B \to 1 \times 1 \times B$ is that the unique arrow to from $B$ into $1$ or what?
Comment: You're welcome. The map is $1\times 1\times \mathrm{id}_B$; abstractly, it's the inverse to the projection map $1\times 1\times B\to B$.
Comment: Ah yes thank you!
Comment: Actually, why is it even needed? The morphisms for $h$ and $g$ already compose as is?
Comment: I don't understand the question. Why is what even needed?
Comment: That is, why, for the composite $h \circ g$, do I have to compose the expressions for $h$ and $g$ via the evaluation maps with the map $B \to 1 \times 1 \times B$?, since the codomain of the expression for $g$ coincides with the domain for $h$?
Comment: Still, I'm not sure I understand. The ones can be dropped from the notation but this has nothing to do with the composability of $g$ and $h$. I put them there so that it is easier to see that the manipulations of the compositions are valid. If that's obvious for you then go ahead and ignore the map $B\to 1\times 1\times B$.
Comment: Ah, I see now, it makes sense to me now. Many Thanks!


Mongoose deleting (pull) a document within an array, does not work with ObjectID

Question: I have the following mongoose schema:
user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567891,
        "isActive": true
    }, {
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

I would like to delete the second item in the connections array, to get the following:
user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

The following code does the job as expected:
userAccounts.update(
    { 'connections.isActive': false },
    { $pull: { 'connections.isActive':false }},
    function (err, val) {
        console.log(val)
    }
);

But, I need to delete based on ObjectId.  And the following goes does not work:
userAccounts.update(
    { 'connections._id': '1234-someId-6789' },
    { $pull: { 'connections._id': '1234-someId-6789' } },
    function (err, val) {
        console.log(val)
    }
);

Any suggestions? I have been banging my head against the screen (aka Google, Stackoverflow, ...) for hours and have had no luck.
Comment: Can someone help me here: https://stackoverflow.com/questions/49124014/removing-object-with-objectid-from-array-in-mongoose-mongodb/49126608#49126608 Similar problem :(
Answer: It seems that the above code would not work.  It should not even have worked for the first example I gave.
In the end I was supported by this answer here: MongoDB, remove object from array
Here is my working code:
userAccounts.update(
    { userId: usr.userId },
    {
        $pull: {
            connections: { _id : connId }
        }
    },
    { safe: true },
    function removeConnectionsCB(err, obj) {
        // ...
    }
);

Comment: and `connId` and `usr.userId` is an instanceof `ObjectId`?
Comment: I thought `safe: true` was set by default?
Answer: I have a document like

I have to delete address from address array
After searching lots on internet I found the solution
Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, (err, data) => {
    if (err) {
        return res.status(500).json({ error: 'error in deleting address' });
    }
    res.json(data);
});

Comment: Exactly same problem but doesn't work for me. What version of mongodb is this?
Comment: What was your query and route url ? What if it is dynamic in `addressId`
Comment: you should do the update query like this
`Customer.findOneAndUpdate(query, {$pull: {address:  mongoose.Type.ObjectId(addressId)}}, (err, data) => {
    if (err) {
        return res.status(500).json({ error: 'error in deleting address' });
    }
    res.json(data);
});`
Answer: user: {
 _id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
 name: 'Test',
 posts: [
  ObjectId("5cd07ee05c08f51af8d23b64"),
  ObjectId("5cd07ee05c08f51af8d23c52")
 ]
}

Remove a single post from posts array
user.posts.pull("5cd07ee05c08f51af8d23b64");
 user.save();
Comment: **The best specially if you're updating a found document.**
Comment: same thing didn't work for me, no err, just didn't work, any clue??
Answer: To use update with ObjectId, you should use ObjectId object instead of string representation :
var ObjectId = require('mongoose').Types.ObjectId;

userAccounts.update(
    { 'connections._id': new ObjectId('1234-someId-6789') },
    { $pull: { 'connections._id': new ObjectId('1234-someId-6789') } },
    function (err,val) {
        console.log(val)
    }
);

Comment: I think your code is a little bit misleading.  For instance in line 3, you wrote `connections_.id` when in fact the original question clearly shows that `connections` is an array of objects with no `_id` property attached to it.
Comment: Thanks for your answer.  Technically, I think you are right.  But I was actually referencing my code using the valid ObjectId JSON format.  I have posted my own answer.
Answer: use findByIdAndUpdate to remove an item from an array
You can do it in mongoose 5.4.x and above
const result = await User.findByIdAndUpdate(user_id, {
    $pull: {
        someArrayName: { _id: array_item_id }
    }
}, { new: true });

The item from array will be removed based on provided property _id value
Answer: If you are using mongoose, no need to use the MongoDB stuff, I mean that's why we're using mongoose in the first place, right?
userAccounts.connections.pull({ _id: '1234-someId-6789'});
await userAccounts.save();

Answer: mongoose: 4.11.11
What have worked for me is the following syntax:
const removeTansactionFromUser = (userId, connectionId) => {
    return User.findByIdAndUpdate(userId, { $pull: { "connections": connectionId} }, {'new': true} );
};

Mongoose support id in string format or ObjectId format.
Tip: new ObjectId(stringId) to switch from string to ObjectId
Answer: In mongoose 5.8.11, this $pull: { ... } didn't work for me, so far not sure why. So I overcame it in my controller this way:
exports.removePost = async (req, res, next) => {
  const postId = req.params.postId;
  try {
    const foundPost = await Post.findById(postId);
    const foundUser = await User.findById(req.userId);
    if (!foundPost || !foundUser) {
      const err = new Error(
        'Could not find post / user.',
      );
      err.statusCode = 404;
      throw err;
    }
    // delete post from posts collection:
    await Post.findByIdAndRemove(postId);
    // also delete that post from posts array of id's in user's collection:
    foundUser.posts.pull({ _id: postId });
    await foundUser.save();
    res.status(200).json({ message: 'Deleted post.' });
  } catch (err) {
    // ...
  }
};

Answer: Note: If you use the pull method with syntax: $pull: {propertyId: _id} with  _id can be found from a document, ensure that _id is string type if not using the method toString() to convert to string type. Let's check it!


parametrized surface are isometric if all corresponding curves have same length

Question: A pair of parametrized surface are isometric if and only if  all corresponding curves have same length.
I have proved one direction, unable to prove the direction a pair of parametrized surface are isometric if all corresponding curves have same length.
Comment: Your question could be made clearer - introduce notation for the surfaces and the "correspondence" between them. The idea of the proof here should be to differentiate: if $\gamma_s$ denotes the restriction of some curve $\gamma$ to the interval $[0,s]$, then you can differentiate $s \mapsto L(\gamma_s)$ to find $|\dot \gamma(0)|.$
Answer: Presumably you have a diffeomorphism between the two spaces (otherwise what does corresponding mean).
It would be true if the distance from $p $ to $q $ is the infimum of the distances of all curves from  $p $ to $q $...  but I believe this is true. ..


How to terminate a particular Azure worker role instance

Question: Background
I am trying to work out the best structure for an Azure application.  Each of my worker roles will spin up multiple long-running jobs.  Over time I can transfer jobs from one instance to another by switching them to a readonly mode on the source instance, spinning them up on the target instance, and then spinning the original down on the source instance.
If I have too many jobs then I can tell Azure to spin up extra role instance, and use them for new jobs.  Conversely if my load drops (e.g. during the night) then I can consolidate outstanding jobs to a few machines and tell Azure to give me fewer instances.
The trouble is that (as I understand it) Azure provides no mechanism to allow me to decide which instance to stop.  Thus I cannot know which servers to consolidate onto, and some of my jobs will die when their instance stops, causing delays for users while I restart those jobs on surviving instances.
Idea 1: I decide which instance to stop, and return from its Run().  I then tell Azure to reduce my instance count by one, and hope it concludes that the broken instance is a good candidate.  Has anyone tried anything like this?
Idea 2: I predefine a whole bunch of different worker roles, with identical contents.  I can individually stop and start them by switching their instance count from zero to one, and back again.  I think this idea would work, but I don't like it because it seems to go against the natural Azure way of doing things, and because it involves me in a lot of extra bookkeeping to manage the extra worker roles.
Idea 3: Live with it.
Any better ideas?
Answer: You're right - you cannot choose which instance to stop. In general, you'd run the same jobs on each worker role instance, where each instance watches the same queue (or maybe multiple threads or jobs watching multiple queues).
If you really need to run a job on one instance (such as a scheduler), consider using blob leases as the way to constrain this. Create a blob as a mutex. Then, as each instance spins up, the scheduler job attempts to obtain a write lease on that blob. If it succeeds, it runs. If it fails, it simply sleeps (maybe for a minute) and tries again. At some point in the future, as you scale down in instance count, let's say the instance running the scheduler is killed. A minute later (or whatever time span you choose), another instance tries to acquire the lease, succeeds, and now runs the scheduler code.
Comment: I should have explained that each "job" (a simplification - it is actually loading a large data file and querying it for users) takes minutes to start and uses about 50MB of RAM, but answers multiple job-related requests very quickly.  Therefore I want to start each job on a single role instance, but squeeze as many jobs onto each instance as I can.  I have one message queue per job, so if a job is restarted nothing will be lost, but it gives the user an undesirable delay.  Knowing in advance which jobs to move to another host lets me minimize disruption (see original question).
Answer: In response to your ideas
Idea 1:  I haven't tried doing exactly what you're describing, but in my experience your first instance has a name that ends with _0,  the next _1 and I'm sure you can guess the rest.  When you decrease the instance count it drops off the instance with the highest number suffix.  I would be surprised if it took into account the state of any particular instance.
Idea 2:  As I think you hint at, this will create management problems.  You can only have 5 different workers per hosted service, so you'll need a service for each group of 5 roles that you want to be able to scale to.  Also when you deploy updates you'll have to upload X times more services where X is the maximum number of instances you currently support.
Idea 3:  Technically the easiest.  Pending some clarification, this is probably what I'd be doing for now.  To reduce the downsides of this option it may pay to investigate ways of loading the data faster.  There is usually a Goldilocks level (not too much, not too little) of parallelism that helps with this.
Comment: You cannot count on idea #1 - there is absolutely no guarantee which instance will be terminated when scaling from, say, 3 instances to 2.

Regarding idea #3 - if your jobs are triggered by a queue message, and if your queue-processing output is idempotent, you don't have to worry about an instance being shut down - the in-progress queue items will simply be made visible in the queue again (after your preset timeout value) and another instance will reprocess it.
Comment: re Idea 1: That is very useful information.  Being able to predict which will go is almost as good as being able to specify.
Comment: re Idea 3: I hope to improve load times eventually, but it is a complicated, pre-existing program so I cannot rely on this for the first rollout.


Getting NegativeArraySizeException while JSON parsing from openweathermap

Question: I am trying to fetch the data using Async class but instead of getting the data I am getting a NegativeArraySizeException. While all the other things are right and I don't know what mistake I have made.
Below is the code I am using to fetch the data:
private class FetchData extends AsyncTask<Object, Void, String>
{

    @Override
    protected String doInBackground(Object... arg0) {

        int responseCode = -1;
        try
        {
            URL apiURL = new URL("http://api.openweathermap.org/data/2.5/weather?q=london&mode=json&units=metric");
            HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
            connection.connect();

            responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK)
            {
                InputStream inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream);
                int contentLength = connection.getContentLength();
                char[] charArray = new char[contentLength];
                reader.read(charArray);
                String responseData = new String(charArray);

                JSONObject jsonResponse = new JSONObject(responseData);

                JSONArray weather_icon  = jsonResponse.getJSONArray("weather");
                 JSONObject obj_icon = weather_icon.getJSONObject(0);
                 String icon = obj_icon.getString("icon");
                 String status = obj_icon.getString("description");

                 String location = jsonResponse.getString("name");

                 JSONObject main  = jsonResponse.getJSONObject("main");
                 String tempreature = main.getString("temp");

                 String humidity = main.getString("humidity");
                 String pressure = main.getString("pressure");

                 pTempreature = tempreature;
                 pHumidity = humidity;
                 pPressure = pressure;
                 pLocation = location;
                 pStatus = status;
                 pIcon = icon;

                 Intent i = new Intent(MainActivity.this, DisplayData.class);
                 i.putExtra("tem", tempreature);
                 i.putExtra("ico", icon);
                 i.putExtra("hum", humidity);
                 i.putExtra("pre", pressure);
                 i.putExtra("stat", status);
                 i.putExtra("loc", location);
                 startActivity(i);

            }

        }
        catch (MalformedURLException e)
        {
            Log.e("log_tag","Error In URL"+e.toString());
        }
        catch (IOException e)
        {
            Log.e("log_tag","Error In URL"+e.toString());
        }
        catch (Exception e)
        {
            Log.e("log_tag","Error In URL"+e.toString());
        }

        return "Code :"+responseCode;
    }
}

Answer: I was not running your code, but probably you have issue with:
char[] charArray = new char[contentLength];

As I checked by this page content-lengtth is not set for your url, so you are getting -1 in contentLength. Try this code to get your content:
StringBuffer buffer = new StringBuffer();

            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();


Como alinhar um elemento de rodapé sempre na base da página?

Question: Tenho uma página na qual há uma div com vários conteúdos dentro, que se modificam de acordo com o desejo do usuário. Logo abaixo existe um outro div que é o Rodapé.
Caso eu coloque um position: relative, o rodapé irá adequar sua posição de acordo com o tamanho da página, porém ele não fica "preso" em baixo (sem nenhum espaço até o fim da página) quando a janela do navegador é redimensionada para um tamanho menor.
Já se eu colocar um position: absolute, o rodapé irá ficar fixo no fim da página, mas não se adequará ao tamanho da janela.
Mas gostaria de fixar um bottom: 0px, semelhante ao que acontece caso eu aplique um position: absolute, mas de forma que se o conteúdo da página for maior, o rodapé não sobreponha a página.
Alguém sabe como seria possível fazer isso?
Meu exemplo está aqui no JsFiddle.
Comment: Caso já tenha resolvido favor marcar a como resolvido
Comment: Se eu realmente entendi o seu problema, creio que isto resolverá, pelo menos vai eliminar o espaço entre o footer e a borda da página: `*{margin: 0;}`. Coloque no começo do seu css, isto interferirá em todos os elementos da sua página em que o `margin` não estiver especificado.
Answer: Solução com FLEXBOX e VH
Fiz um jsfiddle com a solução perfeita pra seu problema com apenas 4 propriedades css no container de sua aplicação usando flexbox e vh como unidade relativa, entenda melhor com o código abaixo:

.container{
  height: 100vh;
  display: flex;
  flex-direction: column:
  justify-content: space-between;
}

Isso garante que o .container possua sempre a altura exata da viewport e que o  esteja sempre no começo do .container e o .footer esteja sempre no final, e quando o conteúdo dentro do  ultrapassar as dimensões da viweport, o .footer acompanhe o conteúdo sem se sobrepor.
Veja mais aqui nesse JSFIDDLE
E neste link um guia sobre FLEXBOX
Answer: Manter o rodapé sempre na base, quando o conteúdo é menor que a página, e de modo que ajuste sua posição conforme o conteúdo fique maior, pode ser feito usando um elemento div como wrapper do conteúdo.
Estrutura HTML de exemplo:

        Conteúdo aqui

        Footer

E o seguinte CSS:
* { margin:0; padding:0; }
html, body {height:100%;}
.main {
    min-height:100%;
    position:relative;
    width:1200px;
    margin: 0 auto;
}
.content{
    width: 100%;
    background: #cccccc;
}
#footer{
    background: #3C948B;
    position:absolute;
    bottom:0;
    width:100%;
    margin-top: 10px;
}

Exemplo no Jsfiddle
Nota: créditos a meu colega de trabalho Marcos Souza, que aceitou o desafio.
Comment: A última linha do texto fica escondida atrás do rodapé. "ipsum ac felis(...)".
Comment: Essa era uma boa solução em 2014, mas hj em 2016, suponho que a melhor solução seja FLEXBOX com VH
Answer: Solução em jquery onde não há necessidade de alterar parâmetros em outras div ou body, somente na div onde será o footer.
Uso o jquery para calcular a largura do browser, posição e largura do footer, assim sabendo quanto adicionar margin-top a div footer.

function footer_botom() {
var footer_position = $('#footer').offset().top;
var footer_height = $('#footer').height();
var tela_height = $(window).height();
var margin = tela_height-footer_position-footer_height;
$('#footer').css({"margin-top": margin+'px'});}

footer_botom();
$(window).resize(function() {
$('#footer').css({"margin-top": '0px'});
footer_botom();});
#footer {background-color:#ccc; width:100%}

        Conteúdo aqui

        Footer

Answer: De uma olhada : Jsfiddle
Passei para position : fixed e z-index : 10
O menu permanece junto ao bottom 0px, agora é só ajustar a margin.
Comment: Sua resposta não soluciona o problema, pois apesar do rodapé manter se ao bottom da viewport, quando o conteúdo principal ultrapassa a altura da viewport o rodapé fica sobreposto, não é essa a proposta.
Answer: Tente colocar uma altura mínima no conteúdo acima do footer.
Exemplo:
min-height: 100px

Comment: Leonardo, bem-vindo ao [pt.so]! O problema de colocar um `min-height` é que você teria que saber de antemão qual o tamanho da página. Além disso, a pergunta é como manter corretamente o `footer` na base do site com a janela pequena.


Using a Naive Bayes Classifier

Question:
Hi, I'm really unsure of how to do this problem. Does anyone with expertise in Machine Learning know how to do this problem?
Comment: Is this a homework problem?
Answer: This explains the concept of Naive Bayes classifier.
A "naiveness" in NBC is an assumption of independence of variables. For example, you can assume that Study outcome does not depend on Neighbor being home. This post explains it. So for the first question
$P(Happy) = P(W=Good) \cdot P(S=Pass) \cdot P(N=Out)$
For the second this assumption does not hold, and
$P(Happy) = P(W=Good) \cdot P(S=Pass|N=Out)$
Of course, relationships might be more complicated, as Neighbor can go out only when it is good weather.

Using a Naive Bayes Classifier


SQL query SUM syntax (classic ASP project)

Question:
I have 3 tables: MONTHS, STORES, REPORTS (attached image sample).
I want to write a SQL query that will SUM the records (day_amount) from the table REPORTS but only the records having the same store and the same month.
I need something like that:
SELECT SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
WHERE MONTHS.month_id = REPORTS.month_id
  AND STORES.store_id = REPORTS.store_id

Is that correct? I have to use the GROUP BY?
Comment: Yes that is correct. You don't need grouping. Your query is fine.
Comment: You have not referenced the other tables in your SQL Statement. You may need to look up and perform JOIN statements here if you want to use them.
Answer: You need to make sure you're joining the other tables (if you need to do this).
SELECT
     MONTHS.month_id
    ,STORES.store_id
    ,SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
INNER JOIN MONTHS ON MONTHS.month_id = REPORTS.month_id
INNER JOIN STORES ON STORES.store_id = REPORTS.store_id
GROUP BY MONTHS.month_id, STORES.store_id

Although, it doesn't appear you actually need the other tables at all, you could try something like this;
SELECT
     REPORTS.month_id
    ,REPORTS.store_id
    ,SUM(REPORTS.day_amount) AS GRAND_TOTAL
FROM REPORTS
GROUP BY REPORTS.month_id, REPORTS.store_id


Can not convert from element type Object to Session

Question: private static final Set sessions = Collections.synchronizedSet(new HashSet());

I am storing sessions in a Set type reference variable called sessions  s shown above.
Now, I want to iterate over these:
for(Session s : sessions){}

However, I get a Type Mismatch error at it that says
Can not convert from element type Object to Session

How do I fix this ?
Comment: you can do this too. `for(Session s : (Set)sessions){}`
Answer: TL;DR: DON'T USE RAWTYPES
You are using a raw Set, this means that the compiler can only know that your Set contains Object.
You need to specify the generic type of your collection:
Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());

For more information, read this.


Vectors: Two lines that intersect, one vector that is perpendicular to both

Question: So I have this maths question that I can't seem to wrap my head around.
I have two lines:
Line 1 $= r = 3i+2j+7k + X(i-j+3)$
Line 2 $= r = 6i+5j+2k + Y(2i+j-k)$
I have found the point of intersection when $X=-1$ and $Y=-2$, and thus the point of intersection to be $2i+3j+4k$
Now I have been told that a vector $(i+aj+bk)$ is perpendicular to both, and to find $a$ and $b$. I understand how this is, but can't seem to find the answer. I can't use dot product with two unknowns, so I would really appreciate some help.
P.S I'm not sure how you're properly supposed to structure these questions with the fancy format so if anyone could link me to how I am supposed to lay questions out please do.
Comment: Hello @Harvey Stanfield, [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is the link that explains how to use MathJax.
Answer: Found out the answer, I was just calculating the wrong thing over and over.
I used the dot product with each of the directional vectors of my two lines and equated them to 0, thus making two simultaneous equations both with terms of a and b.
Then the process is simple.
Comment: Your method works. My idea was the desired vector should be some scalar multiple of the cross product of the direction vectors. Then adjust to match first component $i$. [should give same answer, but either way OK.] (+1 on your answer)
Comment: Please write out all of your work, so that others may see the solution. Otherwise, this isn't an answer.


Unable to go to selected URL IEDriver

Question: I used facebook php-webdriver and downloaded the IE Driver to run the IE, I managed to run the IE but the url wasn't submitted. All other browser was working fine, chrome and firefox only IE is the only problem I have right now. This is error code:
Fatal error: Uncaught exception 'WebDriverCurlException' with message 'Curl error thrown for http POST to http://localhost:5555/session with params: {"desiredCapabilities":{"browserName":"internet explorer","platform":"WINDOWS"}} Recv failure: Connection was reset' in C:\xampp\htdocs\facebook\lib\WebDriverExceptions.php:39 Stack trace: #0 C:\xampp\htdocs\facebook\lib\remote\HttpCommandExecutor.php(256): WebDriverException::throwException(-1, 'Curl error thro...', Array) #1 C:\xampp\htdocs\facebook\lib\remote\HttpCommandExecutor.php(177): HttpCommandExecutor::curl('POST', 'http://localhos...', Array, Array) #2 C:\xampp\htdocs\facebook\lib\remote\RemoteWebDriver.php(117): HttpCommandExecutor::remoteExecute(Array, Array) #3 C:\xampp\htdocs\facebook\lib\remote\RemoteWebDriver.php(63): RemoteWebDriver::remoteExecuteHttpCommand(5000, Array) #4 C:\xampp\htdocs\facebook\example.php(7): RemoteWebDriver::create('http://localhos...', Object(DesiredCapabilities), 5000) #5 {main} thrown in C:\xampp\htdocs\facebook\lib\WebDriverExceptions.php on line 39

and here is my coding.
<?php
require_once('lib/__init__.php');
$host = 'http://localhost:5555/';

$driver = RemoteWebDriver::create($host, DesiredCapabilities::internetExplorer(), 5000);

$driver->get('http://google.com/');
$driver->wait(5);
$driver->quit();

?>

Answer: btw , for me the following initialization works, but I'm working on phantomJs:
public function __construct($selenium_node_ip)
    {
        $host = 'http://'.$selenium_node_ip.':8080';
        $this->driver = RemoteWebDriver::create($host,DesiredCapabilities::phantomjs(),5000);
    }

================
heh , I'm using the folloinwg stack:
selenium  hub + selenim nodes.
I'm connecting to hub and executing test on a separate noed.
When phantomJs get 'overloaded' it throws the following exception:
Fatal error: Uncaught exception 'WebDriverCurlException' with message ' in /var/www/releases/5/application/lib/FB-WebDriver/lib/WebDriverExceptions.php on line 39 WebDriverCurlException: Curl error thrown for http POST to http://22.214.171.124:8080/session with params: {"desiredCapabilities":{"browserName":"phantomjs","platform":"ANY"}} couldn't connect to host in /var/www/releases/5/application/lib/FB-WebDriver/lib/WebDriverExceptions.php on line 39 Call Stack: 0.0003 638008 1. {main}() /var/www/releases/5/public_html/api/index.php:0 0.0006 664328 2. include('/var/www/releases/5/application/script/api/index.php') /var/www/releases/5/public_html/api/index.php:1 0.0491 6994280 3. FacabookCrawler->__construct() /var/www/releases/5/application/script/api/index.php:20 0.0491 6995920 4. RemoteWebDriver::create() /var/www/releases/5/application/lib/facebookCrawler.class.php:9 0.0492 6997296 5. HttpCommandExecutor->execute() /var/www/releases/5/application/lib/FB-WebDriver/lib/remote/RemoteWebDriver.php:78 0.0492 6997664 6. HttpCommandExecutor::curl() /var/www/releases/5/application/lib/FB-WebDriver/lib/remote/HttpCommandExecutor.php:130 0.0500 7000832 7. WebDriverException::throwException() /var/www/releases/5/application/lib/FB-WebDriver/lib/remote/HttpCommandExecutor.php:208

http://gyazo.com/ac32123059b95483dd53ec9e373f460b
As for now I still didn't find good solution to resolve it, but
when on the node I   make phantom js restarted using
sudo service phantomjs restart

http://gyazo.com/ae48dcf945010c28cf41d31c43a08c40
It  works then  OK for me:
http://gyazo.com/646bf26a48d367bb9e793a847a49de5c
Hope it  somehow helps you to find out the root cause of you problem

Unable to go to selected URL IEDriver


Why was $i$ introduced to satisfy this $\sqrt{-1}$?

Question: Can someone explain to me why $$\sqrt{-1} = i$$ I love math and I'm looking at doing it to higher levels. I know that we can NEVER have a square root of a negative number as per my reading hence if I was given $$\sqrt{-4}$$ the answer would be $$2i$$
and if I was given
$$\sqrt{4}$$
the answer would be $\pm2$, can I get sources explaining why $i$ was introduced?
Thanks.
Comment: Are you looking for an explanation here (as in your first sentence) or a source (as in your next-to-last sentence)?
Comment: Yes that is what i want
Answer: Technically, $i \neq \sqrt{-1}$. $i$ is simply a symbol that we use to denote a solution to the equation $z^2 + 1 = 0 \iff z^2 = -1$. This symbol is called the imaginary unit and there isn't really a reason why it represents a solution to $z^2 = -1$, it's more that it was defined to be that way. This imaginary unit is quite important in the field of mathematics. It extends the real numbers and generates the complex number system that has quite a significant impact on mathematics. Examples include a whole branch of analysis termed complex analysis or provides algebraic closure for polynomials in $\mathbb{C}$.
Secondly, $\sqrt{4} \neq \pm 2$. The square root function denoted by the radical sign refers to only the positive value, which is why technically $i \neq \sqrt{-1}$ and why $\sqrt{4} = 2$ and not $-2$.
As for why the imaginary number was introduced, there are a multitude of reasons. For example, the introduction of such a number means that the field of real numbers is algebraically closed. Specifically, the algebraic closure of the real numbers is the field of complex numbers that are generated by including $i$. A lot about the usage and technicalities of the imaginary unit $i$ can be gleaned from its Wikipedia page here, that I would encourage you to read.
Comment: This is wonderful info. Thanks
Answer: on the history, my impression is that people were fairly happy having quadratic equations without (realnumber) roots. Then for cubic equations, Cardano, about 1545, introduced a rudimentary version of complex numbers, because his method lead directly to using cube roots of one of these objects.  https://en.wikipedia.org/wiki/Complex_number
good book: http://www.maa.org/publications/periodicals/convergence/an-imaginary-tale-the-story-of-1
from the book description:

The solution of cubic equations in the sixteenth century forced
  mathematicians to deal with the square root of -1, and in the first
  major chapter of the book, the author handles this episode judiciously
  and leisurely.
Comment: From my recollection of the history, part of the issue was that algebra was not exactly well-developed in Italian mathematics at that point. Instead they typically framed things geometrically; for example, the quadratic equation $x^2-3x+2=0$ might have instead been interpreted as the equality in area of different combinations of squares. That makes it easy enough to dismiss equations like $x^2+1=0$, since one would simply say "no such arrangement exists." (cont).
Comment: What forced the issue re: imaginary numbers was that, when one tackles the cubic case, there are cases which 1) Cardan's formula introduces square roots of negative numbers, and yet 2) if one treats $\sqrt{-1}$ seriously, then once one carries out all the algebraic manipulations then one ends up with _real_ solutions. And that's not so easily dismissed, since these would amount to genuine geometric solutions. So imaginary numbers, even as they seemed nonsensical, were nevertheless quite _useful_. [This link](http://www.ms.uky.edu/~sohum/ma330/files/eqns_2.pdf) nicely discusses the history.
Comment: The _casus irreducibilis_ shows up in section 4.3 of the linked pdf, though only in passing. But it plays the central role in the [third part](http://www.ms.uky.edu/~sohum/ma330/files/eqns_3.pdf) of that same set of notes.
Comment: I am Fascinated by mathematics and i really want complex numbers not to give me hard time. Hence i decided to look into this. Thanks for the link
Comment: @Semiclassical, I thought you were leading up to https://en.wikipedia.org/wiki/Casus_irreducibilis which the chapter does not mention, or I did  not recognize it there.


Piping Email with Postfix

Question: I'm trying to set up a pipe for a specific email address.  I'm following what I see here, but after newaliases I get the following:
postalias: warning: /etc/postfix/aliases, line 1: name must be local

My /etc/postfix/aliases:
firstname.lastname@example.com: "| /usr/bin/php -q /home/path/to/file/pipe.php"

When I try sending an email it returns deliverable. What am I doing wrong?
Comment: example.com probably does not match your local domain.
Comment: Is example.com in your local hostnames list?
Answer: From the Postfix aliases(5) man page:

  o    An alias definition has the form
            name: value1, value2, ...

The  name  is a local address (no domain part).  Use double quotes when
  the name contains any special characters such as whitespace, #',:',
  or  `@'.  The  name  is  folded to lowercase, in order to make database
  lookups case insensitive.

To forward email for arbitrary domain addresses, read about virtual(5) instead.

Piping Email with Postfix


Why was Brahms's music considered 'too academic'?

Question: I posted on here before about learning to compose, after hearing some classical music that moved me enormously.
I have been researching many of the famous composers from all over the world; Brahms has particularly enlightened me.
Whilst researching and listening to Johannes Brahms, his Wikipedia page states the following:

While many contemporaries found his music too academic, his contribution and craftsmanship have been admired by subsequent figures

What does 'too academic' mean in this circumstance? Initially (after taking piano lessons for just over a month now) I would have said this was a good thing, was it not?
Thank you
Comment: I feel like this could be a better fit at music fans or even ELU. It's possible that "academic" in this case means "of the academy", implying Brahms sounds like he's still in school, in terms of his composing.
Comment: Or his Academic Festival Overture :-0
Comment: "Academic" as applied to composition could mean a number of things: (1) over-concerned with following the conventional rules of composition, or (2) appealing to musicologists rather than to the general public. It could mean too innovative, or not innovative enough. It's unclear to me what the cited passage is intended to mean.
Comment: Brahms was well versed in the music of his forebears, having spent many years as a conductor in addition to his work as a composer. His works show signs of that education—and thus may seem somewhat "rigid" in architecture and style.
Comment: That sentence on Wikipedia should be marked [citation needed].
Answer: The famous critic Hanslick put it like this concerning the first movement of the fourth symphony:

Den ganzen Satz über hatte ich die Empfindung, als ob ich von zwei schrecklich geistreichen Leuten durchgeprügelt würde.

My translation:

For the whole movement I had the impression of getting a good thrashing by two awfully intellectually stimulating guys.

I interpret it as: There is no doubt that Brahms is a master of composition well versed in numerous subjects. But it often requires some intellectual effort on the listener's side to appreciate that quality, while the works of other composers may simply catch you, whether you like it or not.
Comment: @cmp Society changes. The Wikipedia quote more-or-less implies that he wasn't mainstream *in his own time;* and that "popular" sentiment has since changed.
Comment: @jpaugh -  He was not only appreciated by later generations - that's utter nonsense. His name was engraved on the ceiling of  a great concert hall together with Bach and Beethoven - (thus the 3 B's) **during his own lifetime** and he was one the most important musical leaders (perhaps the most important) of his time. Brahms merely had to say a good word about a young composer and his career was virtually "made". His most important  "discovery" was Dvorák. Brahms recommended him for an endowment and that launched his career.   **The wiki entry is rubbish.**
Comment: @cmp - Brahms was enormously popular in his time. _. If his work didn't catch a majority of people why is he so highly regarded_ - where did you get that notion? He had stern critics and also **_artistic_ enemies** (_The Wagnerians_ ) But also countless advocates and 'fans' - he was immensely successful, in great demand as a composer, teacher and conductor. He was born to poor parents but he died a very rich man, although he never took money from patrons and never held a "real job" except for a short period of time. He lived entirely on the proceeds of his music in its various forms.
Comment: Thanks. This is very helpful. What I can't understand though, he is regarded as one of the greats. He belongs to the 3 Bs. If his work didn't catch a majority of people why is he so highly regarded? Was it his high level of academia that I guess people just admired enormously?
Comment: @ToddWilcox I think it was a misspelling of "thrashing." I've seen ["a good thrashing"](http://www.wordreference.com/es/translation.asp?tranword=give%20a%20thrashing) before, essentially in the sense of to be beaten/whipped or (metaphorically) bested. OTOH, just about anything can have a sexual connotation, so I don't know why you'd bother to mention that.
Comment: I'm sure the beatles had no shortage of critics in their time, but nevertheless the consensus is that they are probably the most important/influential band of the 20th century. The fourth B perhaps...?
Comment: I think it's the phrase, not the word. Does this mean physically beaten up or intellectually assaulted? I can't tell if it's a good thing or a bad thing. "Intellectually stimulating" has very positive connotations. "Trash", "whack", "maul", and "belt" are much more negative. I can't tell if the quote is complimenting Brahms or critiquing him. I wonder if your dictionaries are more British English than American. I've never heard "get a good swishing" before. To me, "swish" is the sound a long, flowing skirt makes when its wearer walks.
Comment: If I heard someone in a bar say they "got a good trashing by two awfully intellectually stimulating guys", I would assume they had sex. So it's pretty confusing to me. "Whack" and "maul" also have sexual connotations. Normally "to get trashed" means "to get very drunk" where I come from.
Answer: Brahms was interested in counterpoint which many considered to be rooted in traditions of the past (think species counterpoint and Fux) and other formal aspects of composition. Other composers like Liszt wanted to explore new frontiers in music, were less concerned about conforming to the ways of the past, and interested in the emotional impact of music.
This is broad overview. Take a look at this wiki page for a more detailed overview.
https://en.wikipedia.org/wiki/War_of_the_Romantics
A far as the phrase 'too academic' is concerned, consider that mastering the techniques of the past requires lots of study. Brahms could be considered academic in that sense. Liszt was not learning from past treatises. He invented his own new style. His creativity was not such a studied approach. Study the past, invent the future.
Comment: +1 for "Brahms could be considered academic in that sense" -But _Other composers...wanted to explore new frontiers in music, were less concerned_    :contention about  _Musical structure, the limits of chromatic harmony, and program music versus absolute music_ (from your wiki source) is IMO a more accurate. To imply that Brahms was more concerned with form than creativity and content  (to paraphrase your contention) is a misunderstanding/mis-characterization.  Brahms, like Bach and Beethoven before him, was a **great innovator** within the traditional forms which he generally dealt with.
Comment: @cmp - If you are just a beginner, I'd advise not to pay much attention to what critics have to say. (And perhaps never to pay much attention...) and particularly not to wikipedia, which can be grossly inaccurate or extremely biased to the POV that particular writer wants to advance.  Feel free to enjoy Brahms, as millions of others have, for the last 150 years or so.
Comment: @cmp :  If you want a good book to get started with, try this one: It's a broad survey - an easy read, not very technical at all, and he says nice things about everyone. Listen to the samples he suggests (they're all online free of charge) and discover what you yourself **enjoy** - that's what it's all about: [_**Language of the Spirit: An Introduction to Classical Music**_](https://www.amazon.com/dp/B01K3WN5J2)
Comment: @cmp Most Western music is made up of several separate *parts* that play at the same time.  For example, the left hand and right hand parts of a simple piano piece.  In a *homophonic* piece (many hymn tunes, for example), one part is the tune and the others are accompanying parts that make chords with the tune in order to harmonize it.  In counterpoint (e.g., a Palestrina motet or some of the Bach chorales), each one of the parts is *a tune in its own right*, and these tunes are cleverly set off against one another to make a musically pleasing whole.
Comment: What is counterpoint? I have just looked online but being a beginner most of the content just went over my head.
Comment: @Stinkfoot: Brahms was an innovator, but a conservative one — his innovation was pretty much within the established aesthetics and forms of the classical tradition, while others like Liszt were breaking out of that tradition entirely.  Just like how, say, Ravel was hugely innovative, but within a conservative tradition compared to the jazz pioneers of the same period.
Comment: +1 This is pretty much right. The context for Brahms being considered academic (despite not coming across that way to most modern listeners) was that musical fashion at the time was being set by the tone poems of Liszt and the epic opera of Wagner whereas Brahms still preferred the large-scale "classical" forms, i.e. sonata, symphony, string quartet, and so on. I'd agree with @Stinkfoot that the criticism stems more from Brahm's use of form than counterpoint.
Answer: Contrived.  Missing the forest for the trees.  Following all the rules but not appealing in its overall æsthetics.
Frankly, this is the kind of verdict I easily arrive at looking at, say, "Faust" part 2 by Goethe.  Ugh.
Where Brahms tries diving into mythology, he likewise can become a bit arbitrary and tedious.  And his concerti aren't really impressing me all that much (I think I read someone declare that his violin concerto as not being written for but against the violin).  But that's not the bulk of his work, and much of his vocal work is simply stunning and really a class of its own.
Comment: +1 _But that's not the bulk of his work_  - Brahms covered all the traditional forms as matter of course, but IMO his chamber music, songs and short pieces - the Hungarian dances, the waltzes are where he excelled. Most people are unaware of how much/many of Brahms's songs and dances have become so well known and popular to be the point of being symbolic and even cliché.
Answer: The criticism was that Brahms wrote rather stolid music, as if he was crafting a harmony exercise or constructing a fugue for a Doctorate qualification.   Other descriptions could include 'heavy', 'Germanic'...
Bach can be criticised for writing 'sewing machine' music.  It just keeps going on (and on)...
Plenty of modern (at the time) composers have been described as 'just making noise'.
Can you see what aspects of Bach, Brahms, Stravinsky etc. may have attracted such opinions?   Can you also see many positive aspects in their music?  Yes?  Good!


What is the solution to the following Cauchy problem?

Question:
What I have tried to do was to separate variables and integrate both sides but what I got was y+ln|y-3|=ln|t-3| + c
which is undefined for y=3 and t=3. but I don't understand how to get the range for the solution.
Answer: The function $f(t) = \dfrac{1}{t-3}$ has a vertical asymptote at $t=3$ which divides the graph of $f(t)$ into two separate parts. Since the initial condition is at time $t=0$, the solution $y(t)=3$ is defined on the interval $(-\infty,3)$.
Comment: can you please point to some of the resources to understand this?
Comment: @M.HamzaAli I don't really know of any specific resources, but you can try dynamical system textbook?