Como pegar um dado de um item selecionado do combobox html

Question: Boa dia Pessoal.
Galera é o seguinte, são duas perguntas a seguir.
tenho 2 combobox!
No 1º combobox tenho todas as empresas do sistema. aqui tudo ok.
No 2º combobox tenho todas as filias da empresa selecionada pelo 1º combobox. segue a funcao do 2 combo box:

reparem que eu preciso do valor da segunda combobox e também do texto da segunda combobox.  e onde surge o 1º problema...
Nessa parte do código var tensao = $('#Unidades option:selected').text();
esse text() me retorna o seguinte:
e no alert que eu peço para exibir  me retorna o seguite:
reparem que no alert ele me exibe dois  valores o "mt" e o 429....
agora intendam por favor  como eu faço pra pegar apenas o valor "mt" no código seguinte var tensao = $('#Unidades option:selected').text("eu queria o apenas o mt  e não tudo mt-429");
se tiver como?  eu gostaria de saber por favor ...
já na segunda duvida... que eu só vou continuar porque e relativa a mesma questão e o seguinte
na segunda combobox pode existir uma ou mais filiais cadastradas...  como na imagem a seguir:
quando tem só uma filial gera um erro no retorno. que eu faço no seguinte select via pagina php segue o código:
<?php
session_start();
    include("conexao.php");

            $unidade = filter_input(INPUT_GET, 'au', FILTER_VALIDATE_INT);
            $_SESSION['ulala'] = $_GET['au'];

            $comandoSql = "SELECT a,  b, c, Tensao
                            FROM Tab_UC where cod='".$ugauga."'" ;

            $dados = mysql_db_query($bancoDados, $comandoSql) or die (mysql_error());

            //$a='<option value="Selecione">Selecione sua Unidade: </option> ' ;
            while ($linha = mysql_fetch_array($dados))
            {
               // $a.= '<option value="Selecione">Selecione sua Unidade: </option> ' ;

                $a.='<option value= "'.$linha["a"].'">'.$linha["Tensao"].'-'.$linha["b"].'</option>';
            }
            echo $a;

?>

esse erro faz com que as empresas que só tenham uma unica filial, não consigam ver um  resultado de um outro select via outra pagina php que não vem ai caso..
e as empresas que tem mais de uma filial eu escolho  segunda filial e mostra corretamente...
eu preciso que essa linha de código.// $a.= '<option value="Selecione">Selecione sua Unidade: </option> ' ;
seja apresentada no 1º lugar da combobox
se intenderam me ajude pf.
Comment: @Diego, não entendi sua edição...
Comment: @Victor Gomes a edição conflitou com a sua, tentei identar o código, que tava dificil de entender.
Answer: Para pegar somente os dois primeiros caracteres, use assim:

var tensao = $('#Unidades option:selected').text().substr(0, 2);
Comment: exatamente isso!!!! parabéns  muito agradecido


Evaluating $\int_{-a}^{a}\sqrt{a^2-x^2}dx$

Question:
Question:
How to evaluate
$$\int_{-a}^{a} \sqrt{a^2 - x^2} dx$$

This came up while trying to prove that the area of an ellipse is give by $\pi a b$ where $a$ and $b $are the major and minor axes respectively.
I'm curious as to how one could evaluate this. It should be $$\frac{\pi a^2}{2}$$ but I have no idea how to get that result.
Could someone show me?
Comment: Notice that this represents the area under the top half of the circle $x^2+y^2=a^2$, so it is half of the area inside this circle.
Comment: $\int_{-a}^{a}\sqrt{a^2-x^2}dx=a \int_{-a}^{a}\sqrt{1-\left(\frac{x}{a}\right)^2}dx=a^2\int_{-1}^{1}\sqrt{1-y^2}dy$...
Answer: If $y=\sqrt{a^2-x^2}$ then $y \geq 0$ and
$$x^2+y^2=a^2$$
This shows that your integral represents the area between the $x$-axis and the upper half circle $x^2+y^2=a^2$.
The area of this half disk is $\frac{\pi a^2}{2}$.
Answer: Hint: Use this substitution.
 $$x = a\sin(\theta)$$
Answer: Hint: Let $x = a \sin t $ then $dx = a \cos t\, dt$ and $$\int_{-\pi/2}^{\pi/2} \sqrt{a^2 - a^2 \sin^2 t}\,\, a\cos t \, dt =\int_{- \pi/2}^{ \pi/2}  a^2\cos^2 t \, dt$$
Answer: Write $I = \int \sqrt{a^2 - x^2} \ dx$. Then integrating by parts,
$$I = x\sqrt{a^2 - x^2} + \int \frac{x^2}{\sqrt{a^2-x^2}} \ dx = x\sqrt{a^2 - x^2} - I + \int \frac{a^2}{\sqrt{a^2 - x^2}} \ dx $$
This last integral should look standard. Thus
$$I = \frac{1}{2} \left( x\sqrt{a^2 - x^2} + a^2 \arcsin(x/a) \right) $$
Hence
$$\int_{-a}^a \sqrt{a^2 - x^2}  dx = \ \frac{a^2}{2} \left[ \arcsin(x/a) \right]_{-a}^a = \frac{a^2}{2} ( \pi/2 - (-\pi/2)) = \frac{\pi a^2}{2}$$
Comment: Fresh alternative.


In a Poisson process measured with some efficiency, is the measured count still Poisson?

Question: Situation:
Say I have a Poisson process, like radioactive decay, producing R particles per second. I measure with a detector. There is a probability P that a particle will be detected by the detector.
Things I think I know:

The inter-arrival time of the particle emission is exponentially
distributed with parameters based on R.
The number of particles emitted before detection is given by a
negative binomial based on P.
If a number N is sampled from (2), a single sample of inter-arrival time for detected particles can be given by the sum of N samples from (1). This sum can be obtained by sampling from a gamma distribution with parameters based on N and R.

My question:
If a single inter-arrival time can be calculated by sampling from a gamma based on N and R, how does the number of detector counts in an interval end up being Poisson again? (To be Poisson, the inter-arrival time for the detector must be exponential, not distributed according to some weird gamma thing.) Of course N is fluctuating, but I can't see how this works out.
However, I am almost completely sure detector counts are in fact Poisson distributed. Could somebody show me the math?
Thanks for the help!
EDIT:
I found this paper:
Fried, D. L. "Noise in photoemission current." Applied Optics 4.1 (1965): 79-80.
Which shows the result that a binomially selected poisson random variable is also Poisson with a rate given by PR. This confirms the comment by jbowman. Still, I would be interested in seeing the explanation of how my process of generating the inter-arrival time at the detector using the negative binomial and gamma distribution is incorrect. This is my major mental hiccup. Thank you.
EDIT 2:
I wrote this matlab script to test whether what I was trying with the gamma distribution worked. Turns out that somehow the gamma inter-arrival times generated with a geometrically distributed N are exponential and agree with the inter-arrival times suggested by Poisson(PR). (ia2 and ia3 are identically distributed). Any idea how this works out analytically? It was not intuitively obvious to me!
<code>close all
n = 100000;
ia1 = exprnd(1,n,1); % create exponentially distributed inter-arrival times
t1 = cumsum(ia1); % running sum (the real experiment time)

mask = (rand(n,1) > 0.5); % flip a coin
t2 = t1(mask); % get only the events for which "the coin landed on heads"
ia2 = diff(t2); % calculate the inter-arrival times at the detector.

% plot the distributions
figure; hist(ia1,100); title('exponential inter-arrival times');
figure; hist(ia2,100); title('binomial sampled inter-arrival times');

%%
spacing = geornd(0.5,n,1) + 1; % how many events before we get heads
ia3 = gamrnd(spacing,ones(n,1)); % generate the interarrival times with gamma
figure; hist(ia3,100); title('geom/gamma inter-arrival times');
</code>
Comment: It'll be much later today (Pacific Std Time), I'm afraid; I can do it the straightforward way too, which will be less opaque.
Comment: #2 is actually not correct; if each particle has a probability $P$ of being detected, the distribution of detected particles per second is Poisson($RP$) (assuming detections are independent etc.)  For #3, if $N$ is sampled from 2, then you don't have a single sample of inter-arrival times; you have a single observation of the sum of $N$ interarrival times, which is indeed distributed Gamma with shape parameter $N$.  Consequently, the premise of your question ("If a single interarrival time...") isn't true.
Comment: I don't understand how you know the rate is Poisson(RP). Could you show me? That is the very heart of this question I think. In #2, I suppose that I have if I have a P chance to hit the detector, the number of particles emitted before hitting the detector is Geometrically distributed with a mean of 1/P. Thus, I can calculate can sample from this Geometric distribution to get N, then sum up N inter-arrival times to get a single inter-arrival time at the detector. Can you explain the flaw in this logic? I think your statement about the rate being Poisson(RP) is important. Thank you!
Comment: Are you somewhat familiar with moment generating / characteristic functions?  I'd write it out using that approach, as it's simple, unless it's also unhelpful.
Comment: No I have not worked with moment generating functions. Do you have some idea of how to show that Poisson + some fixed probability of acceptance just scales the poisson rate? I am willing to learn the moment generating function approach based if you could show how this works out.
Comment: I found some math showing how the distribution is still Poisson. But this seems to conflict in my mind with what I have "shown" using the negative binomial and the gamma distribution. Could you show me where I have gone wrong in that logic? I greatly appreciate your help.
Comment: To repeat:  "If a single inter-arrival time can be calculated by sampling from a gamma based on N and R"... is wrong.  What you have done is calculated the total arrival time between the $0^{th}$ and the $N^{th}$ arrivals.  This does indeed have a Gamma dist'n with shape parameter $N$, but the interarrival time between any two consecutive arrivals is still exponential (also known as a Gamma dist'n with shape parameter = 1.)
Comment: But I think that it is not wrong, based on the output of my code. It's just that the shape parameter happens to also be a random variable. Somehow a gamma with a geometrically distributed shape parameter is equivalent to an exponential distribution. So while you are right about the distribution being exponential, sampling from a gamma distribution in the way I have done *does* sample the inter-arrival time of radiation events on the detector. It would be much simpler (but seemingly equivalent) to sample from an exponential(PR) though.
Comment: It cannot be that a gamma with a geometrically distributed shape parameter is equivalent to an exponential, as a gamma with a shape parameter = 1 is an exponential, and a geometric distribution doesn't equal a degenerate distribution with $p(x=1) = 1$.
Comment: You can run the code I posted in Matlab or Octave if you like and see. A gamma(N,R) where N is distributed as geom(P) looks pretty identical to exp(PR). The distribution of p(x=1) does not need to be 1 if the exponential has a higher mean parameter than the one used in the gamma.
Answer: A quick non-technical argument might use Jackson networks. In your case total external arrivals is rate $R$, and there are no internal transitions (observed particles don't switch to the unobserved queue). The splitting proportion between the observed and unobserved nodes $p_{0i}$ is $P$, so the
$\lambda_{obs}=RP$
If you're looking for first principles, call $O(t)$ the observed counting process, and $N(t)\sim PP(r)$ the total counting process. Where each arrival in $N(t)$ gets logged in $O(t)$ with probability $p$. So that if for some $s$ we have $N(s)=n$ then $O(s)$ has a binomial($n,p$) distribution.
This approach uses probability generating functions:
$E[z^{O(t)}|N(t)=n]=\sum_{j=0}^{n}z^{j} {n \choose j}p^j(1-p)^{n-j}=(1-p+pz)^{n}$
Last equality by the binomial theorem. Then, unconditionally, since $N(t)\sim Poisson(rt)$:
$E[z^{O(t)}]=E[E[z^{O(t)}|N(t)=n]]=\sum_{n=0}^{\infty}(1-p+pz)^{n}\frac{rt^n}{n!}e^{-rt}=e^{-rt}e^{rt(1-p+pz)}=e^{rpt(z-1)}$
Which is the probability generating function of a Poisson($rpt$) random variable.


Get yesterday's content with contextual filter in views block

Question: I have a view and I try to show only yesterday's content.
I add a contextual filter "Content: Created date".
If I select "Current Date" from "Provide default value" its works perfectly.
But I select "PHP Code" its not working whatever I write. I try a lot of format.
In this topic there is a solution but its not work either;
return date("d", strtotime("-1 day"));

How can I do that?
Comment: how you use php filter code
Answer: Try this one
Content: Post date (>= -1days)

Instead of this
return date("d", strtotime("-1 day"));

Answer: Do you really need a contextual filter, or did you read you need one?
It can be done with a regular Views filter on the Content: Post date. (I am not sure if this requires the date module).
Comment: I know, but this is built in behavior and does not require custom php, which is usually better.
Comment: Its not working i tried. Actually the second answer in other topic (link is inside my question) works. Thanks anyway :)
Comment: he can do using php filter read it
Comment: Obviously, 'is equal' to would require the date to be exactly 24 hours in the past. My bad, I should have selected 'Is between'. But glad you sorted this out.


Laravel REST API and frontend

Question: I created a project in Laravel, small database and added REST API in laravel to connect mobile app with database. What should I use to get data from database in web application? Using laravel models is easy but is that a good way to create another controllers to handle forms etc instead using rest api controllers? Thanks
Answer: Laravel also support for Restful API in own way.
for this

you create your controller in Api folder: php artisan make:controller Api/TestController
define your routes in routes/api.php :
Route::group(['namespace' => 'Api'], function (){
  Route::group(['prefix' => '/test'], function () {
    Route::get('/', 'TestController@list);
    Route::get('/single', 'TestController@single');
  });
});

create a resource collection for data that is an array of collection
php artisan make:resource Api/Collections TestCollection this command create a collection in folder app/Http/Resources/Api/Collections
open in and change toArray($request) function and add a function with($request) like following code :
public function toArray($request)
{
  return $this->collection->map(function ($item){
    return [
        'id' => $item->id, // $item is instance of Test model
        'name' => $item->name,
        'description' => $item->description,
    ];
  });

}

public function with($request) // optional : this method return with of response
 {
   return [
    'status' => true
   ];
 }

so go to TestController and create a method for get all tests:
public function list()
{
   $tests = Test::all(); // your Test Model
   return new TestCollection($test); // TestCollection you created above
}

this is return a json object that contains array of tests.

for get a single test :
php artisan make:resource Api/Resources TestResource
then go to TestResource in app/Http/Resources/Api/Collections and change code like following:
public function toArray($request)
{
 return [
    'id' => $this->id,
    'name' => $this->name, // $this is instance of Test model
    'description' => $this->description,
    'body' => $this->body,
    'diff_name' => $this->name_in_table  // you can change the name differ from name in model instance
 ];
}

so go to TestController and create a method for single test
public function single(Request $request)
{
    $test = Test::findOrFail($request->id);
    return new TestResource($test);
}

this a summary of Rest API in laravel. Hope you find it useful
Answer: With laravel, you can reuse your api endpoints by taking advantage of the CreateFreshApiToken middleware.
Then you will only need to create new controllers and methods to display views. All of the CRUD stuff can be reused.

Laravel REST API and frontend


Uncaught Error: Template parse errors: Can't bind to 'users' since it isn't a known property of 'app-user'

Question: Estou tentando consumir os dados de uma api teste baseada em Laravel, mas estou  obtendo o seguinte erro:
Can't bind to 'users' since it isn't a known property of 'app-user'.

USERCOMPONENT
import { Component, OnInit, Input } from '@angular/core';
import { User} from './user';
import { UserService } from './user.service';
@Component({
selector: 'app-user',
   templateUrl: './user.component.html',
   styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
   users: User[]
constructor(private userService: UserService) {
}
ngOnInit() {
   this.listarUsuarios();
}
   listarUsuarios(): void{
   this.userService.listaUsararios().subscribe(users => this.users = users);
}
}

USERSERVICE
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { User } from "./user";
const API = 'http://localhost:8000/api/user/users';
@Injectable({ providedIn: 'root' })
   export class UserService {
   constructor(private http: HttpClient) {
   }

   listaUsararios(): Observable<User[]> {
      return this.http.get<User[]>(API);
   }
}

USERMODULE
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule} from '@angular/common/http';

import { UserComponent} from './user.component';
import { UserServices } from './user.services';

@NgModule({
  declarations: [
    UserComponent,
  ],
  imports: [
    CommonModule,
    HttpClientModule

  ],
  exports:[
    UserComponent,
  ],

  providers:[
   UserServices
  ]
})

export class UserModule { }

USERINTERFACE
export interface User {
   id: number,
   name:string,
   email: string,
   telefone:string
   datascimento: Date,
}

APP.COMPONENT.HTML
<app-home></app-home>
<app-user></app-user>

Alguém sabia me ajudar nessa situação, estou iniciando no Angular.
Comment: Tenta inicializar o user `users: User[] = []` - Acredito que não seja isso, mas vamos tentar...
Comment: no user module, seu import do user service parece estar diferente. Essa linha aqui está correta? import { UserServices } from './userServices';
Comment: normalmente isso se da porque vc esta usando algum input tipo
Mas no seu caso não vejo por que daria esse erro. Em que momento vc acessa o users?
Comment: Não era isso...infelizmente o erro permanece o mesmo
Answer: Man , pra fazer o data-bind precisa adicionar o decorator @Input no arquivo user.component.ts antes da variável user, e também importar do angular/core, assim o angular entende que é uma variável de entrada.
   import { Input } from '@angular/core'
   import { User } from 'user-interface'

   @Input() user:User


How to get MimeContent while fetching an email from EWS?

Question: I am using EWS service in my Application. At point I want fetch an existing email and then convert it to a file. i am using following code for this.
private ExchangeService _service = null;

internal EWSClient()
{
     _service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
     _service.Credentials = new WebCredentials(HandlerSettings.MailReceiverLogin, HandlerSettings.MailReceiverPassword);
     _service.Url = new Uri(HandlerSettings.MailReceiverServer);
}

To Fetch email I use Bind method.
var completeEmailMessage = EmailMessage.Bind(_service, emailId);
var mimeContent = completeEmailMessage.MimeContent;
string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".eml");
using (var fileStream = new FileStream(tempFile, FileMode.Create))
{
      fileStream.Write(mimeContent.Content, 0, mimeContent.Content.Length);
}

Here, i get exception as completeEmailMessage.MimeContent; is null.
Which method shall i use to get complete email having MimeContent ?
Answer: You should create a PropertySet and add the MIMEContent as a property to load then specify that as an overload property for Bind eg
        PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties);
        psPropSet.Add(ItemSchema.MimeContent);
        var completeEmailMessage = EmailMessage.Bind(_service, emailId, psPropSet);
        var mimeContent = completeEmailMessage.MimeContent;
        string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".eml");
        using (var fileStream = new FileStream(tempFile, FileMode.Create))
        {
            fileStream.Write(mimeContent.Content, 0, mimeContent.Content.Length);
        }


Why existence of universal covering implies that the base space be locally path connected?

Question: I am reading Chapter 13, the chapter about classification of covering spaces, of J.Munkres' Topology. My confusion raised when I read
Corollary 82.2. which says:
the space $B$ has a universal covering space if and only if $B$ is path connected, locally path connected, and semilocally simply connected.
The book does not give a proof so I believe it should be straight forward. But I just can not prove the "only if" part of this corollary. I do not know how to see that a space which has a universal cover must be locally path connected. I understand that by Lemma 80.4., a base space with a universal cover has to be semilocally simply connected. And since covering space is simply connected, the base space must be path connected.
Thank you very much for your attention and really appreciate your helps.
Answer: It depends what the definition of "universal covering" is.
If the definition is that a universal covering of $B$ is a simply connected covering (as it is in Munkres), then this statement as you're writing it isn't quite true. If $B$ is path-connected and simply connected but not locally path connected, then the identity function $B\to B$ is the universal covering of $B$ (but it exists!). For example, let B be the union of the line segments in $\mathbb{R}^2$ from $(0,0)$ to each point of $\{(1,0),...,(1,1/3),(1,1/2),(1,1)\}$.
But if I recall correctly, Munkres typically assumes spaces in consideration are locally path connected. So what is meant is the following: A path-connected and locally path-connected space $B$ has a universal covering if and only if $B$ is semilocally simply connected.
Comment: Thank you. I believe you are right. There are simply connected spaces that are not locally path connected. You are right that there is a general assumption that spaces taking into consideration are locally path connected. But the statement I copied is exactly the statement in Munkres' book as you can check. I guess he was not very careful at this point.
Comment: @JeremyBrazas If we mean a universal covering in the categorical sense, that is, a covering $p :\tilde{X}\to X$ with the property that for every covering $q :\tilde{Y}\to X$ with a path connected space $\tilde{Y}$ there exists a covering $h :\tilde{X} \to \tilde{Y}$ such that $q\circ h = p$, then is there any non-simply connected universal covering for a non-locally path connected space?
Comment: @M.Ramana A space, whether it is locally path-connected or not, might have a non-simply connected ``categorical" universal covering space. See [this answer](https://mathoverflow.net/questions/111310/universal-covering-space-for-non-semilocally-simply-connected-spaces/111388#111388).
Comment: @JeremyBrazas Thank you so much for your help.
Answer: This statement is indeed false for the usual definition of a universal covering space. However, in the beginning of Chapter 13 Munkres makes the following convention:

Convention. Throughout this chapter, the statement that $p:E\to B$ is a covering map will include the assumption that $E$ and $B$ are locally connected and path connected, unless specifically started otherwise.

I agree, however, that formulating this corollary this way is misleading (and for no good reason).
Answer: Let $\pi\colon A\to B$ be a universal covering of $B$. Let $b\in B$ and $U\ni b$ open. We want to show that $b$ has a path-connected neighbourhood $U'\subseteq U$. Let $a\in A$ with $\pi(a)=b$ and $V$ the connected component of $\pi^{-1}(U)$ that contains $A$. I.e., $V$ contains all points that are reachable from $a$ via a path in $\pi^{-1}(U)$. But then $U':=\pi(V)$ is a path-connected open neighbourhood of $b$. (Careful: why is $U'$ open?)
Comment: What is your definition of a universal covering space? The one I know, does not make any assumptions about the connected component $V$ in your proof being path connected or even if it is, yielding an open neighborhood of $A$.
Comment: Thank you but I am unable to show your $U'$ is open. I think $V$ is not necessarily open so we can not say $U'$ is open. The openness of path components of any open subset is equivalent to locally path connectedness of the space. But there do exist a simply connected space that is not locally connected.
Answer: It might be too late to answer it, but I'm sure that Munkres Lemma 80.4 is what you are looking for.


I have an epidemiology question with logs

Question: I am a graduate student in biochemistry working on cancer. I am currently looking at epidemiology models of the disease. Epidemiologists have developed formulas that predict the frequency of various cancers as a function of age. The disease incidence and mortality rates occurs as a function of $a^4$ to $a^7$. I am reading some papers, but I don't understand what the authors are saying:
1) If the probability of an outcome is indicated by $a^n$, this means that $n+1$ independent events, each occurring randomly and with comparable probability per unit time, must take place before the ultimate outcome (e.g. lethal cancer). I understand that one multiplies the probabilities together to follow $a^n$ (e.g. flipping a coin three times to get a sequence). However, why is it $n +1$ and not simply $n$?
2) The author introduces the log-log plot where the slope of the regression represents $n$. Basically, you take the log of the age (x-axis) and the log of the incidence rate and put a regression line. For example, I have used Canadian statistics data on cancer mortality in men and generated a log-log plot.

So, the slope represents $n$, so there should be 5.5 events that occurred to create a lethal cancer, no? I would greatly appreciate the community's feedback.
Thank you!
Comment: In your plot the x axis is age in years rather than "events" (presumably mutations). You would need to get to either directly measure, or at least get some estimate of "events" per year of age to test the theory.
Comment: Sorry for the previous comment, I did not read the description correctly. I do not understand from your description how the exponent can be interpreted as number of events required to create a lethal cancer. Can you share the paper and data source?
Comment: As Livid mentioned, could you please provide a reference for what you're pulling this from. I'm a trained epidemiologist, and what you're describing is...odd, and makes me think there's potentially some misunderstanding going on.
Comment: @Fomite I believe it is this: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2007940/ There it looks like they calculate the expected number of times a specific sequence of n events had occurred by time t. However, from Armitage and Doll's description, I would think they wanted the probability that sequence occurred at least once, before any others (eg out of sequence mutations kill the burgeoning cancer cell). I'd think that if `q=1-p` and `p1=p2=..pn`, then `P(CancerCell)=((1-q^t)^n)/n!`
Comment: @Johnathan Can you provide the data used for that chart? I want to use it to ask a follow up question based on that A & D paper. I still do not think that they calculated the same thing they discuss in the text. Also,  _"there should be 5.5 events that occurred to create a lethal cancer"_ is incorrect based on that legend. They interpret the exponent as number of required events. You need to convert from log: `log(Incidence)=n*x-log(Constant)`. So `4.51x-5.51` means `Incidence=exp(-5.51)*x^4.51.`
Answer: Armitage and Doll assumed that some total number of mutations are required for a cancer to develop. It's simplest to explain if the probability of any mutation occurring over a short time interval is low, independent of age, and equal for all cancer-causing mutations. I find it simpler to understand if you drop the Armitage-Doll requirement of a particular required order of mutations, but the relation between the slope of your plot and the number of mutations will be the same in either case.
If only 1 mutation were needed for a cancer, then the incidence rate would be constant over age, equal to the mutation probability. That would be a slope of 0 on your plot.
If 2 mutations are needed, the age-dependent issue becomes the probability that 1 prior mutation occurred before the (age-independent) second mutation. The probability of the cancer developing at any age is then the probability of already having the first mutation (first power of age) times the (age-independent) probability of getting the second mutation. Slope of 1 on your plot. And so on for larger numbers of required mutations: the slope of incidence rate versus age represents the probability of already having all except the last mutation, with the probability of the last mutation independent of age. So a slope of n means that n+1 mutations are ultimately needed.
The value of 5.5 on your plot represents the difference between cancers at young ages and older ages. Childhood and youth cancers typically occur when an individual is already born with a cancer-related mutation, so that fewer additional mutations are required for a cancer to develop. In adults, cancer incidence represents the accumulation of acquired mutations. Armitage and Doll reviewed literature suggesting that analysis should be restricted to individuals over 25 years of age, in which case your plot would have a slope closer to 6.
You should know that the simple interpretation in terms of "mutations" has changed somewhat over the 60 years since that paper appeared. It's probably best to think about cancer-related events rather than mutations in DNA as we understand them today. (The Watson-Crick DNA-structure paper was less than 1 year old when Armitage and Doll wrote.) The nature of these events is nicely explained by Hanahan and Weinberg in a 2011 review.
Comment: >"not necessarily in any particular order" Then what is that `(r-1)!` doing in equation 1 in the appendix? After reading that paper I am also confused as to the reason for this "n+1". Actually, I think there are number of points of confusion here due to the way they 1) refer to mutation rates as probabilities, 2) lump everything but time together into a constant, and 3) interpret expected number of events (p*t) as a probability. Can you explain precisely what the number represents that A & D have derived in that paper?
Comment: The `(r-1)!` specifically corrects for the number of different orders in which the `(r-1)` mutations might have occurred, allowing all orders of occurrence to be treated the same. The text below Equation 1 explains that. What might be confusing you about probabilities in this paper is that they are to be understood as probabilities _per unit time_. So the probability of an event over a specified period of time _t_ is the product of the probability _p_ per unit time and the elapsed time _t_. Technically, mutations are being treated as Poisson processes.
Comment: Why do they write (page 2): _"It will be assumed further that the changes must proceed in a unique order"_?  Also, if _"the probability of an event over a specified period of time t is the product of the probability p per unit time and the elapsed time t"_, then the "probability" `(p*t)` will be >1 when t gets large. This is why I say that `p*t` is not a "probability", it is the expected number of events. It does not make sense to me to calculate this for a single cell (each mutation can only happen once). I am sure I am just confused, thank you for your patience.
Comment: Sorry, it had been a while since I read this paper so I had forgotten their assumption of a particular order. You are correct, and I will edit my answer accordingly. (The slope of the relation between log(incidence rate) and log(time) will still be one less than the number of required events, as `(r-1)!` contributes to the constant term.) An assumption in modeling with a Poisson process is that the probability per unit time is so low that more than one occurrence of the same event over the time course of interest (human life span) is negligible.
Comment: _"more than one occurrence of the same event over the time course of interest (human life span) is negligible."_ How would you interpret the intercept? From the A & D paper, I gather it is `(p1*p2*...pn)/(n-1)!`. From the plot the value is `~exp(-5.51)~.004`. If n=7 then `(p1*p2*...pn)=.004*(n-1)!=2.88`. Doesn't seem right.
Comment: The units on the y-axis are cases _per 100,000 individuals_ per year, so the product of probabilities is 2.88 x 10^(-5) per year for an individual. If all probabilities are the same, that would make the probability of a particular mutation 0.22 per year. That is high if you interpret it as a true mutation rate. There are at least two issues here. First, if the plot had been properly restricted to those over 25, the intercept would be lower. Second, unlike the 60-year-old assumptions of A&D, you don't have to have a fixed order of all 7 "mutations".
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/22701/discussion-between-edm-and-livid).
Comment: Thank you very much for your input everyone! It really helped! I am reading the Amritage and Doll paper
Comment: @EdM Thank you again for your answer. I have another one if you don't mind. You refer to Watson and Crick. How did our knowledge of the double-helix change our understanding of a "mutation"? Sorry for being confused. I mean, didn't we know the A,T,G,C already?
Comment: @EdM I have another question about Armitage and Doll paper. When discussing the Fisher and Hollomon paper (multiple cancer cells), the authors say: "This hypothesis, however,also leads to the conclusion that cancer incidence should be proportional to the fifth or sixth power of the concentration of the effective carcinogen whereas experimental data suggest that, in general, tumour incidence and concentration of the carcinogen vary' in arithmetical proportion. The hypothesis in its simple form is, therefore, untenable". Arithmetical proportion: a-b = c-d, right? I don't understand. Thank you!
Comment: In 1953, DNA may have been understood to be the store of genetic information, and that it was composed of T,C,G,A was well known, but the way that DNA transmitted heritable information could not become clear until the structure was determined. For "arithmetical proportion," all A&D are trying to say is that if you double the concentration of a carcinogen you double the tumor incidence. The simple Fisher/Hollomon model would have a much greater increase incidence. Although it's instructive to see where these ideas came from, don't get too hung up on the details of 60-year-old disputes.
Comment: @EdM See here: http://stats.stackexchange.com/questions/145764/what-is-the-probability-that-a-sequence-of-events-occurs-within-a-given-time-int
Comment: @EdM Thank you! If you don't mind, I would greatly appreciate if you could please explain me this statement in Armitage and Doll paper:
Given t(o)^s-1(t -t(o)^6-s It can be that the weight by which a varying probability of the first mutation would be multiplied is highest at age 0 and decreases rapidly throughout life. The weight for the probability of the second change reaches its maximum one-fifth of the way through the exposure period; that for the third change, two-fifths; and so one. I am confused with the 1/5 and 2/5. Thank you!
Comment: Don't get too hung up on that. It's how they dealt with the possibility of different mutations having different rates, in their (now unrealistic) model with a completely fixed order of a defined set of mutations. They consider the time at which a difference in the mutation rate for a particular gene will have its greatest influence on ultimate cancer incidence time. With a fixed order of 7 mutations required, that time will be at the time when the mutation occurs during the process: at the beginning for the first mutation, 1/5 through the process for the second, 2/5 for the third, etc.


Compute the following sum in closed form : $\sum_{n=1}^{\infty}\frac{n\binom{2n}{n}}{4^{n}(2n+1)(2n-1)(4n+1)}$

Question: $$\text{Find : }\sum_{n=1}^{\infty}\frac{n\binom{2n}{n}}{4^{n}(2n+1)(2n-1)(4n+1)}$$
I know that $\displaystyle\sum_{n=0}^{\infty}\binom{2n}{n}x^{2n}=\frac{1}{\sqrt{1-4x^{2}}}$ so $\displaystyle\sum_{n=1}^{\infty}n\binom{2n}{n}x^{2n}=\frac{2x^2}{\sqrt{1-4x^{2}}}$.
But I don't know he to complete this work because I find hypergeometric function.
Comment: @clathratus. I think that the hypergeometric function is not correct (if I am not mistaken !). Using another CAS, I had $$\frac{\pi }{24}-\frac{1}{45} \,
   _3F_2\left(\frac{5}{4},\frac{3}{2},\frac{3}{2};\frac{9}{4},\frac{5}{2};1\right)$$ which I could not simplify but which numerically is effectively what Chip Hurst gave in comments.
Comment: @clathratus. Please, listen the old man : we are all equal  here ! I may be right today and wrong tomorrow and same for you. Cheers :-)
Comment: @Kînan Jœd - If you don't mind me asking, I would like to know how you came across this sum? The final result is quite beautiful.
Comment: Using Mathematica I get $-\frac{\pi}{8} - \frac{\sqrt{\pi}\; \Gamma(1/4)}{3 \Gamma(-1/4)}$.
Comment: The sum is given by the triple integral $$\sqrt{2}\int_0^{1/\sqrt2}\int_0^t\frac{1}{u^3}\int_0^u \frac{2v^2dv}{\sqrt{1-4v^2}}dudt$$
Comment: If I'm not mistaken, the sum is also given by the hypergeometric $$\frac1{30}\,_2F_2(1/2,5/4;5/2,9/4;1)$$
Comment: @ClaudeLeibovici you, having far more experience than me, are most likely correct
Answer: As remarked in the OP,
\begin{equation}
\sum_{n=0}^{\infty}\binom{2n}{n}x^{2n}=\frac{1}{\sqrt{1-4x^{2}}}
\end{equation}
or, by changing $x\to x/2$,
\begin{equation}
\sum_{n=0}^{\infty}\frac{1}{4^n}\binom{2n}{n}x^{2n}=\frac{1}{\sqrt{1-x^{2}}}
\end{equation}
We use the decomposition
\begin{equation}
\frac{n}{\left( 2n-1 \right)\left( 2n+1 \right)\left( 4n+1 \right)}=\frac{1}{12}\frac{1}{2n-1}-\frac{1}{4}\frac{1}{2n+1}+\frac{1}{3}\frac{1}{4n+1}
\end{equation}
Then, for $\left|x\right|<1$, as the three series converge absolutely
\begin{equation}
\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}\frac{nx^{2n}}{\left( 2n-1 \right)\left( 2n+1 \right)\left( 4n+1 \right)}=\frac{1}{12}S_--\frac{1}{4}S_++\frac{1}{3}S_2
\end{equation}
where
\begin{align}
S_+&=\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}\frac{1}{ 2n+1}\\
S_-&=\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}\frac{1}{2n-1}\\
S_2&=\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}\frac{1}{4n+1}
\end{align}
With the notation
\begin{equation}
f(x)=\frac{1}{\sqrt{1-x^{2}}}
\end{equation}
by integrating the above series, we have
\begin{align}
\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}x^{2n}&=f(x)-1\\
S_+=\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}\frac{1}{2n+1}&=\int_0^1 \left[f(x)-1\right]\,dx\\
&=\frac{\pi}{2}-1
\end{align}
A simple transformations is necessary forevaluating $S_-$:
\begin{align}
\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}x^{2n-2}&=\frac{f(x)-1}{x^2}\\
S_-=\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}\frac{1}{2n-1}&=\int_0^1\frac{f(x)-1}{x^2}\,dx\\
&=1
\end{align}
For the third term, changing $x\to x^2$ in the series before integrating
\begin{align}
\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}x^{4n}&=f(x^2)-1\\
S_2=\sum_{n=1}^{\infty}\frac{1}{4^n}\binom{2n}{n}\frac{1}{4n+1}&=\int_0^1\frac{dx}{\sqrt{1-x^4}}-1\\
&=\frac{\Gamma(\frac{5}{4})\sqrt{\pi}}{\Gamma(\frac{3}{4})}-1\\
&=\frac{\left[\Gamma\left( 1/4\right)\right]^2 }{4\sqrt{2\pi}}-1
\end{align}
This classical integral can be found for example here.
Putting all the results together gives
\begin{equation}
\sum_{n=1}^{\infty}\frac{n\binom{2n}{n}}{4^{n}(2n+1)(2n-1)(4n+1)}=-\frac{\pi}{8}+\frac{\left[\Gamma\left( 1/4\right)\right]^2 }{12\sqrt{2\pi}}
\end{equation}
which is also identical to the result given by @ChipHurst in the comments.
Comment: Excellent work!
Comment: Thanks @clathratus


Angular 5: Circular dependency detected between models

Question: I'm stuck for few days with this error, and I don't know how to solve it.
I have 2 models in my app : User and Team.
user.ts :
import { Team } from './team';

export class User {

id: string = null;
name: string = null;
email: string = null;
settings: any = {};

team: Team = null;

constructor(json?: Object){
    var defaultSettings = {};

    if(json){
        this.id = json['id'] || null;
        this.name = json['name'] || null;
        this.email = json['email'] || null;
        this.settings = json['settings'] || {};

        this.team = new Team(json['team']) || null;
    }
}

getSettings(){
    return  Object.assign(this.team.settings, this.settings);
}

team.ts
import { User } from './user';

export class Team {

id: string = null;
name: string = null;
settings: any = {};

users: User[] = [];

constructor(json?: any){
    if(json){
        this.id = json['id'] || null;
        this.name = json['name'] || null;
        this.settings = json['settings'] || {};

        if(json['users']) json['users'].forEach(user => this.users.push(new User(user)));
    }
}

}
When the user is logged in, I got his infos with the team. Like that, I can do user.getSettings() directly from the User, and get a merged array of these settings and the Team.
In the other hand, when I show a Team, it can have some users.
But with that, I got a warning :
WARNING in Circular dependency detected:
src/app/_models/user.ts -> src/app/_models/team.ts -> src/app/_models/user.ts
Is it possible to keep this logic and avoid the Circular dependency warning?
Thanks a lot !
Comment: The answer to your question is 'No, and you should not keep it like that'. Circular dependency means that you have wrong design and you need to fix it. That's all I can say for sure from the information you provided.
Answer: After few days, I've finally created a third model "LoggedUser", which extends my "User" model, with the "team: Team" property :
user.ts :
export class User {

    id: string = null;
    name: string = null;
    email: string = null;
    settings: any = {};

    constructor(json?: Object){
        var defaultSettings = {};

        if(json){
            this.id = json['id'] || null;
            this.name = json['name'] || null;
            this.email = json['email'] || null;
            this.settings = json['settings'] || {};
        }
    }
}

team.ts :
import { User } from './user';

export class Team {

    id: string = null;
    name: string = null;
    settings: any = {};

    users: User[] = [];

    constructor(json?: any){
        if(json){
            this.id = json['id'] || null;
            this.name = json['name'] || null;
            this.settings = json['settings'] || {};

            if(json['users']) json['users'].forEach(user => this.users.push(new User(user)));
        }
    }
}

loggedUser.ts :
import { User } from './user';
import { Team } from './team';

export class LoggedUser extends User {

    team: Team = null;

    constructor(json?: Object) {
        super(json);

        this.team = new Team(json['team']) || null;
    }

    getSettings(){
        return  Object.assign(this.team.settings, this.settings);
    }
}

Answer:
Is it possible to keep this logic and avoid the Circular dependency warning?

By Adding this to your angular-cli.json you can get rid of the warning.
    "defaults": {

    "build": {

        "showCircularDependencies": false
    }
  }

Comment: sorry, the correct answer is change the desing. As idea, why not replace in User the property Team by just a property teamId?


What is the ANOVA model to use for a 2x2 factorial experiment with units measured 3 times each?

Question: If I were to set up an experiment examining the effects of exercise, and coffee consumption on the number of hours slept, what would the be the ANOVA model that I should use, given:

16 volunteers randomly assigned to two groups:

1st group will drink cup of coffee in the morning,
2nd group nothing

Within each group:

4 volunteers will exercise once per day,
the rest will not.

Each subject will be tested on n=3 separate occasions, and the number of hours slept will be recorded.

I find it extremely confusing to get the correct model.
Comment: Why do you randomize coffee drinking, but not exercise?
Comment: Does each individual remain in the group he is assigned to during the 3 replicate (i.e., if he is a non-drinker at the first measurement, is he a nondrinker throughout the test)?
Answer: I dont see the problem! You have two factors, coffee={0 or 1} and exercise={0 or 1} and a response sleep=hours slept.  I think you need to specify a protocol for how to measure "hours slept". It is not obvious how to measure that and if you leave it to the subjects, they could use different methods of measurement!
The design matrix would loook like this:
  constant    coffee   exercise
     1          yes     yes          four lines like this
     1          yes     no                   "
     1          no      yes                  "
     1          no      no

You also need a column for the interaction. Assume coding no=-1, yes=1, the coded design matrix, with one extra column for the interaction, would be
 1          1       1     1
 1          1      -1    -1
 1         -1       1    -1
 1         -1      -1     1

with each line repeated four times.
In R you would use a specification like
Y ~  1 + coffee + exercise + coffee*exercise

Comment: Someone else should edit kjetil's answer so that the design matrix is blocked as a matrix the way he intended.  i unfortunately do not know how to do that.  Otherwise my edit fixed various typos and grammar.
Comment: I tried to make the answer look like you hopefully want it, feel free to change it or drop me a note if you are unhappy with how it looks. Other than that, I think you are right. The design doesn't sound overly complicated and the design matrix straight forward (+1).
Comment: Thanks for the edits! Except LaTeX, I know next to nothing about markup. Is there a place to read about markup at stackexchange?
Comment: @Kjetil start at http://stats.stackexchange.com/editing-help and follow links there for further information if required.
Comment: Actually I just marked the text that you already had correctly formatted and clicked on the `Code Sample` button (or press `Ctrl-k`).


If f(x) is given, what would be the distribution of Y = 2X + 1?

Question:
If the random variable X has a continuous distribution with the
  density $ f(x) = \frac{1}{x^2}\Bbb {1}_{(1, ∞)}(x)$, can you find the
  distribution of $Y = 2X+1$?

My attempt:
$CDF(Y)$
$\Rightarrow P(Y\le y)$
$\Rightarrow P(2X + 1 \le y)$
$\Rightarrow P(X \le \frac{y-1}{2})$
$\Rightarrow \int_{1}^{(y-1)/2} f(x) dx$
$\Rightarrow \int_{1}^{(y-1)/2} \frac{1}{x^2} \Bbb 1_{(1, \infty)}(x) dx$
$\Rightarrow \int_{1}^{(y-1)/2} \frac{1}{x^2} dx$
$\Rightarrow \frac{1}{-2+1}[x^{-2+1}]_1^{(y-1)/2}$
$\Rightarrow 1 - \frac{2}{y-1}$ Ans.

Is it a correct approach?
Comment: That you get the value of a CDF as $5$ and that this does not cause any alarm bells to ring in your mind that something is awry, is worrisome.
Comment: anonymous .... The very first issue is that the argument of a pdf is not a logical condition, but a real number. It seems like you're conflating the probability of an event with the pdf. You need to try to get the concepts more clearly sorted out.
Comment: No, you start off correctly but go wrong almost immediately because you don't seem to understand what is meant by a density function.
Comment: The line with "CDF(y)" on it is sort of okay. The next line is not, and the line after that has an additional error.
Comment: $PDF(Y\leq y)$ is nonsense. Start with $F_Y(y)=P(Y\leq y)=...$ and go on from there.  After that, *don't* substitute $2X+1$ for $y$. That's not what it's equal to.
Comment: As a double check of your edited answer, note that an (easy) integration gives the CDF of $X$ as $$F_X(x)=1-\frac{1}{x}.$$  Since (by simple algebra) $X=(Y-1)/2$, substituting gives $$F_Y(y)=F_X((y-1)/2)=1-\frac{1}{(y-1)/2}=1-\frac{2}{y-1}.$$ Since working entirely with the CDFs avoids potentially problematic differentiation and re-integration, it's an approach worth learning.
Answer: You make an early mistake.
$$\begin{align}
F_{Y}(y)&=\text{Pr}(Y\leq y)\\
&=\text{Pr}(2X+1\leq y)\\
&=\text{Pr}(X\leq \tfrac{1}{2}(y-1))\\
&=\int_{1}^{\tfrac{1}{2}(y-1)}f_{X}(u)\,du
\end{align}$$
Keep in mind that the bounds for $X$ are:
$$1\leq x <\infty$$
So the bounds for $Y$ will be:
$$3\leq y <\infty$$
Comment: @anonymous I have nothing but admiration for your attitude.
Comment: @anonymous Your answer is close, but still incorrect. You should know that your answer is wrong because for this CDF $F_{Y}(3)=0,\, F_{Y}(\infty)=1$ and your answer imples $F_{Y}(3)=1,\, F_{Y}(\infty)=2$.
Comment: Is the result $2 - \frac{2}{y-1}$ ?
Comment: Then, I am quitting!
Comment: I have a feeling that @anonymous is far from quitting, and he was kidding around. Anyway, I think you (@anonymous) have a new answer that wraps up the question, but you can also find an answer [here](http://math.stackexchange.com/q/1382687/152225).
Answer: Since the transformation function is monotonic, we can find the CDF by using PDF transformation and integrating the transformed PDF.
PDF Transformation:
$$ f_Y(y) = f_X(g^{-1}(y)) \Bigg|\frac{dg^{-1}}{dy} \Bigg|$$
For this situation, $g^{-1}(y) = \frac{y-1}{2}$, and by substitution:
$$f_X(g^{-1}(y)) = \frac{1}{((y-1)/2)^2} = \frac{4}{(y-1)^2}$$
The absolute value of the derivative of $g^{-1}(y)$ with respect to $y$ is easy:
\begin{align}
\Bigg|\frac{dg^{-1}}{dy} \Bigg| = \frac{1}{2}
\end{align}
Plug components into the PDF Transformation formula above to get a transformed PDF of :
\begin{align}
f_Y(y) = \frac{2}{(y-1)^2} \quad \text{for} \quad 3 \leq y \lt \infty
\end{align}
Remembering to use transformed lower and upper bounds, we integrate to get the CDF. Line 3 employs u-substitution to simplify the integration:
\begin{align}
F_Y(y) &=\int_{3}^{y} f_Y(t) \, dt\\
&=\int_{3}^{y} \frac{2}{(t-1)^2} \, dt\\
&=\int_{2}^{y-1} \frac{2}{u^2} \, du\\
&= -\frac{2}{u} \; \Bigg|_2^{y-1}\\
&= -\frac{2}{y-1} - (-\frac{2}{2})\\
&= 1 - \frac{2}{y-1} \quad \text{for} \quad 3 \leq y \lt \infty
\end{align}
Finally, we'll check the lower and upper bounds just to make sure we've fulfilled CDF validity requirements:
$$F_Y(3) = 1 - \frac{2}{2} = 0$$
$$F_Y(\infty) = 1 - \frac{2}{\infty} = 1$$


Ajax method not getting called using SpringMVC portlet in Liferay 6.1

Question: I using SpringMVC portlets with Liferay 6.1. I am trying to make an ajax call from tha jsp but the method is not getting called and I get an error as below
failed to load resource the server responded with a status of 404 (not found)
My jsp ajax method is
<code>jQuery.ajax({
    url:'<portlet:resourceURL id="ajax" ></portlet:resourceURL>',
                data: {id:data},
                type: 'POST',
                datatype:'json',
                success: function(respData) {

                    alert(respData);
                    jQuery('#farmerProfile').html(respData);
                }
            });
</code>
and my servResource method signature in the controller class is
<code>@ResourceMapping(value="ajax")
public void serveResource(
        PortletConfig config, ResourceRequest request, ResourceResponse response)

        throws Exception {
</code>
My controller class is implementing the
<code>   org.springframework.web.portlet.mvc.Controller interface
</code>
Can anybody shed some light on it?
Thanks
Answer: ajax POST gets handled by Portlet processAction.
ajax GET gets handled by serverRequest.
So, change your 'type' to from 'POST' to 'GET'
Answer: This sample portlet from "Portlets-in-action" book can be used as a reference to debug your code.
Hope this helps.


solutions of a linear equation system

Question: The following matrix is given over $\mathbb R$
A=$\begin{pmatrix} 1 & -1 & -1 \\ 1 & 0 & a \\ 1 & a & 0 \end{pmatrix}$
The linear equation System $Ax=\begin{pmatrix} 2 \\ 1 \\ 1 \end{pmatrix}$ has exactly one solution for all $a$ except $a=-2$ which has no solution. Is it right?
Answer: Almost correct.

At $a = -2$, we have no solution, so you are correct on that.
At $a = 0$, our augmented RREF matrix gives:

$$\begin{bmatrix} 1 & 0 & 0 & 1 \\ 0 & 1 & 1 & -1 \\ 0 & 0 & 0 & 0 \end{bmatrix}$$
This means we have infinite solutions as:
$x = 1, y = -1 + z$, where $z$ is a free variable.

At all other $a$, we have a single unique solution.
Comment: RREF, solutions or lack thereof for what values of $a$...? (Popular assigned problem-type presently!) +1 for the assistance!
Comment: @amWhy: There does seem to be an awful rash of those lately! Maybe instructors are running out of other problems and they can add variables all over the matrix! :-)
Comment: this is the reduced form:

$$\begin{bmatrix} 1 & 0 & 0 & 2(a+1)/(a+2)  \\ 0 & 1 & 0 & 1/(-a-2) \\ 0 & 0 & 1 & 1/(-a-2) \end{bmatrix}$$

a=-2 will be not defined (division by 0) and therefore i've to handle this case separately. But it seems for all other cases $Rank(A)=Rank(A´)=3$ (exactly one solution). But for a=0 there are of course infinite solutions. I am unable to see this regarding the reduced form !?
Comment: Sometimes, you need to look at several things and you always start with the determinant which is $-a(a+2)$. That shows the two points of interest $0$ and $-2$. Then, I do the general RREF and then handle the special cases as sometimes those are not always evident from the reduced form. Regards
Comment: my current basic math course will not give me the term "determinant" :/
Comment: http://en.wikipedia.org/wiki/Determinant. You can also solve for each variable and will see those two pints if you cannot  use the determinant. Lastly, during the rref reduction, if you don't take it all the way, you can see those critical points. Regards
Comment: i've divided by $a$ that was the mistake
Comment: No, I would not say it was a mistake, you just need to keep track of it is all. Regards
Answer: We see that $det(A)=-a(a+2)$. A matrix $A$ is invertible if and only if $det(A)\neq 0$. When $a=0$ there exist an infinite number of solutions. When $a=-2$ there exists no solution.
Comment: if a=0 then $$A=\begin{pmatrix} 1 & -1 & -1\\1 & 0 & 0\\1 & 0 & 0 \end{pmatrix}$$

the augmented matrix will be

$$B=\begin{pmatrix} 1 & -1 & -1 & | & 2\\1 & 0 & 0 & | & 1\\1 & 0 & 0 & | & 1\end{pmatrix}$$

the row reduced form:

$$\begin{pmatrix} 1 & 0 & 0 & | & 1\\0 & 1 & 1 & | & -1\\0 & 0 & 0 & | & 0\end{pmatrix}$$

$Rank(A)=Rank(B)=2 \ne n$ => exactly one solution ???
Comment: Amzoti cleared the issue.
Comment: We would have $x=1$ and $y+z=-1$ which implies an infinite number of solutions.
Comment: i am wrong: Rank(A)=Rank(B)=2≠n => infinite solutions
Comment: No worries. You had me looking through my Linear Algebra - Friedberg textbook to make sure that $a=0$ would imply an infinite number of solutions.
Comment: but now i am confused about the row reduced form:

$$\begin{bmatrix} 1 & 0 & 0 & (2(a+1))/(a+2) \\ 0 & 1 & 0 & 1/(-a-2) \\ 0 & 0 & 1 & 1/(-a-2 \end{bmatrix}$$

ok, no problem that a=-2 is not defined and therefore to handle this case separately and for all other cases the Rank(A)=Rank(B)=3=n which means there is exactly one solution. but how to see that if $a=0$ there are infinite solutions regarding this ?
Comment: any hints to this ?

solutions of a linear equation system


Amazon EC2 - Can't connect to my Windows instance using a remote desktop client

Question: Using Amazon EC2 I successfully launched a Windows Server 2012 instance. I was able to connect to it using a remote desktop client and configure it as needed.
From the EC2 console I then selected  the option to "Launch More Like This" and a new instance was successfully launched.
However, when I try to connect to it using the same credentials as the other instance, it fails.
Instead of showing me the Windows desktop I get a login screen for 'Other user' and a message telling me the username or password is incorrect. If I click OK, I can then enter the username 'Administrator' and the password but that fails in the same way and takes me back to the initial screen.
How do I connect to instances launched in the way described?
Comment: Did you try right-clicking the instance in the console and clicking "Connect"? It'll generate a .rdp file for that specific instance.
Comment: Yes, that's exactly what I did.
Answer: "Launch more like this" is more of a config copy (vpc id, subnet etc...) than a copy of the machine itself. The Administrator password was changed to something new during the instance launch. You can right-click your instance and click "Get windows password".
The only way to keep the same Administrator password is to create an AMI from your original instance and launch instances based on that AMI.
Comment: I followed you advice and created an AMI from my original instance. Now, when I launch instances based on that AMI the password is the same. Thanks for the advice.
Comment: No problem!! Always happy to help!
Comment: When I right-click the instance to get the Windows password it presents a screen where the Key Name is the same as that for the original instance. The password (when I decrypt it) is also therefore the same.
Comment: When you say 'create an AMI from your original instance' do you mean the 'Create Image' option?
Comment: Yes. It will create an AMI then you can choose that AMI when you launch an instance.


What advantages does classical regression have over shrinkage methods?

Question: Shrinkage approach like elastic net can produce predictive, sparse models when p >> n and when there's correlation between the predictors. In Zou and Hastie's paper on the elastic net, the simulation results show that elastic net out performed OLS.
So my question is, (and I know this depends on the actual research goals) in what situation does regression outperform the elastic net?
Comment: Well elastic net is a superset of ols, no so you have to more clearly define your terms. I think what is missing is the causal analysis /significance testing framework (eg for individual coefficients)
Comment: What do you mean by *outperform*? Time-wise OLS is always faster. To that extent, OLS will offer equally good $\beta$ estimates compared to EN in less time if the sample is large and all the predictors are relevant and reasonably uncorrelated. Can you make the question clearer please?
Comment: @usεr11852 It could be in any way that is advantageous, whether it be predictive power, computing time (like you have mentioned), interpretability, extrapolation, etc.
Answer: Time-wise OLS is always faster. To that extent, OLS will offer equally good β estimates compared to EN in less time if the sample is large and all the predictors are relevant and reasonably uncorrelated. -  usεr11852
elastic net is a superset of ols, so you have to more clearly define your terms. I think what is missing is the causal analysis /significance testing framework (eg for individual coefficients) – seanv507
Comment: I've copied these comments by usεr11852 and seanv507 as a community wiki answer because the comments are, more or less, answers to this question. We have a dramatic gap between answers and questions. At least part of the problem is that some questions are answered in comments: if comments which answered the question were answers instead, we would have fewer unanswered questions.


Como referenciar atributos de um objeto dentro de uma função interna?

Question: Estou fazendo a simulação de um chuveiro, e não consigo referenciar os atributos sem que dê erro.
Para executar o código uso docol.molhar() no console.
Quando verifico this.agua por exemplo, ele consta como undefined. No entanto, se eu declarar e usar os atributos como variáveis, estes funcionam normalmente.
Código que não funciona:

function chuveiro() //definição do Objeto
{
    /*this.marca = "Marca";
    this.serial = "Numero de Serie";
    this.lote = "Numero do Lote";*/
    this.agua = 20; //quant de agua em minutos
    this.min = 0;
    var chuva;

    //this.ligar = function() {console.log("bip")} ; //definição de função de objeto, a.k.a. método
    this.chover = function()
    {
        if (this.agua > 0)
        {
            this.agua--;
            console.log(`resta(m) ${this.agua} minuto(s) de agua`);
            this.min--;
            if (this.min < 1) clearInterval(chuva);
        }
        else
        {
            clearInterval(chuva);
            console.log("acabou a agua");
        }
    }
    this.molhar = function()
    {
        this.min = prompt("quantos minutos vc quer gastar?")
        chuva = setInterval(this.chover, 500);
    }
}

var docol = new chuveiro(); //Criação de uma instância do Objeto
docol.molhar();

Código que funciona:

function chuveiro() //definição do Objeto
{
    /*this.marca = "Marca";
    this.serial = "Numero de Serie";
    this.lote = "Numero do Lote";*/
    var agua = 20; //quant de agua em minutos
    var min = 0;
    var chuva;

    //this.ligar = function() {console.log("bip")} ; //definição de função de objeto, a.k.a. método
    this.chover = function()
    {
        if (agua > 0)
        {
            agua--;
            console.log(`resta(m) ${agua} minuto(s) de agua`);
            min--;
            if (min < 1) clearInterval(chuva);
        }
        else
        {
            clearInterval(chuva);
            console.log("acabou a agua");
        }
    }
    this.molhar = function()
    {
        min = prompt("quantos minutos vc quer gastar?")
        chuva = setInterval(this.chover, 500);
    }
}

var docol = new chuveiro(); //Criação de uma instância do Objeto
docol.molhar();
Answer: Na verdade o problema é passar o método como argumento de setInterval. Segundo a documentação:

When you pass a method to setInterval() or any other function, it is invoked with the wrong this value.
...
Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout.

Ou seja, ao fazer setInterval(this.chover, 500);, o método chover não executará com o mesmo this referente ao objeto em questão (em vez disso, o this dele é setado para o window ou o objeto global). Por isso que neste caso ele não enxerga mais os campos do objeto.
Uma solução é usar Function.prototype.bind(), que cria uma função igual à original, porém com o valor de this que quisermos. E como neste caso deve ser o próprio objeto, basta fazer setInterval(this.chover.bind(this), 500);. Ou seja:

function chuveiro() {
    this.agua = 20;
    this.min = 0;
    var chuva;

    this.chover = function () {
        if (this.agua > 0) {
            this.agua--;
            console.log(`resta(m) ${this.agua} minuto(s) de agua`);
            this.min--;
            if (this.min < 1)
                clearInterval(chuva);
        } else {
            clearInterval(chuva);
            console.log("acabou a agua");
        }
    }
    this.molhar = function () {
        this.min = parseInt(prompt("quantos minutos vc quer gastar?"));
        chuva = setInterval(this.chover.bind(this), 500);
    }
}

var docol = new chuveiro();
docol.molhar();


Is the LLL algorithm only applicable with integers?

Question: Why cannot it apply with a basis defined with irrational numbers? For example, such a basis:
$(1, \sqrt{2}, \sqrt{3}) $, $(1, \sqrt{5}, \sqrt{7 })$ and $(1, \sqrt{11}, \sqrt{13 })$.
Answer: It can be applied to any basis in $\mathbb{R}^n$, including your example.
The original paper of the LLL-algorithm (Factoring Polynomials with Rational Coefficients) defines the algorithm on any lattice, and defines lattice as $L := \left\{ \sum_{i=1}^n r_i b_i \;|\; r_i \in \mathbb{Z} \right\}$, where $b_1, b_2, \ldots, b_n$ is any basis in $\mathbb{R}^n$.
Most of the applications indeed use vectors in $\mathbb{Z}^n$, but not all, for example the article On multidimensional Diophantine approximation of algebraic numbers uses the LLL-algorithm for vectors with algebraic number coordinates (e.g. $\sqrt{2}$ is an algebraic number, but $\pi$ is not).
Answer: The input and the output of the LLL algorithm is a basis for a lattice, not a basis for a vector space. The span of your vectors isn't a lattice, and so it doesn't fit the conceptual scheme of the algorithm.
Note that in some restricted cases you can have irrationals. For example $(1,2\pi),(2,\pi)$ form a lattice and so the algorithm can be used with those two inputs.
Edit: Here's an argument that might convince you that your set doesn't form a lattice. Instead of your example, we'll look at $(1,1),(\sqrt{2},\sqrt{3})$. The set of $\mathbb{Z}$ combinations takes the form $\{(a+b\sqrt{2},a+b\sqrt{3}):a,b\in\mathbb{Z}\}$.
By the theorem in the link, the numbers of the form $a+br$ are dense in $(0,1)$ for every irrational $r$, and by increasing $a$ we can translate the set and see that it's dense in $\mathbb{R}$. This tells us that we can find a set of values for $a$ and $b$ such that the first coordinate is dense in $\mathbb{R}$ and that we can do it separately for the second. However, the defining property of a lattice is that it's discrete, and so the set generated by these two vectors doesn't form a lattice.
Now, your set doesn't have a vector of all ones, but we can fix that. If you take one dimension and scale all the vectors by a constant factor, you preserve the fact that it's a lattice. So when you have $(1,\sqrt{2},\sqrt{3}),(1,\sqrt{5},\sqrt{7})$ we can scale the second coordinate by $\sqrt{2}$ and the third by $\sqrt{3}$ to get $(1,1,1),(1,\sqrt{5/2},\sqrt{7/3})$. By the same argument, linear combinations of these two vectors don't form a lattice, and so the original vectors cannot! Adding in the third vector doesn't make things better, because adding in additional vectors can only increase the number of points we can reach
Comment: @S.Kohn $\{x=av_1+bv_2+cv_3:a,b,c\in\mathbb{Z}\}$ is not discrete for your $v_1,v_2,v_3$. Although the first coordinates can only be integers, the second and third take on a set of values that are dense in $\mathbb{R}$
Comment: Frankly speaking, I do not understand. Of course you can use integral coefficients before the three vectors above to form a lattice. What do you mean by saying the span of my vectors is not a lattice?
Comment: @S.Kohn You can use the theorem proved here to prove that your set isn't discrete: http://math.stackexchange.com/questions/272545/multiples-of-an-irrational-number-forming-a-dense-subset
Comment: But that problem takes only the fractional part of the number. For any irrational number $q$, the numbers $\{ n q , n \in \mathbb{Z}\}$ indeed forms a lattice.
Comment: @S.Kohn my response is long, so I edited it into my answer.
Comment: Sorry, 'we can do it separately for the second'? The second component is not independent of the first. Do not do algebra. Just use geometry. Picture it in your mind. Apparently (1,1) and $(\sqrt{2},\sqrt{3})$ can form a lattice.
Comment: @S.Kohn I meant that you can make the first or the second coordinate dense with a set of values for $a$ and $b$ separately but not necessarily simultaneously.
Comment: source for them forming a lattice?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/55251/discussion-between-s-kohn-and-stella-biderman).


Change/cycle through images using Javascript

Question: I'm following TechFunda's code on changing an image on a button click. Here is the code:
http://techfunda.com/howto/444/changing-of-images

Changing the Image

    <input type="button" onclick="changeImage()" value="Change" />

Click on the "Change" button to convert waterbottle

        into Softdrink bottle

It goes from one image to the second, then back to the first.
How would I go about adding another image to be in the cycle? (e.g. first image > second image > third image > back to first)
Answer: Use an array of srcs instead, and increment an index through the array:
const srcs = ['foo.png', 'bar.png', 'baz.png'];
let i = 0;
function changeImage() {
  var image = document.getElementById('myImage');
  i = (i + 1) % srcs.length;
  image.src = srcs[i];
}

Live demo:

const srcs = ['https://www.gravatar.com/avatar/49196f761a0b00f0ee42e3e4e6bad2f0?s=32&d=identicon&r=PG&f=1', 'https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=32&d=identicon&r=PG&f=1'];
let i = 0;

function changeImage() {
  var image = document.getElementById('myImage');
  i = (i + 1) % srcs.length;
  image.src = srcs[i];
}

Changing the Image

<input type="button" onclick="changeImage()" value="Change" />

Click on the "Change" button to convert waterbottle
 into Softdrink bottle

Comment: Can you put your example into a JSfiddle, or have the rest of the code involved in your message so I can run it? The code allows it to go to the next image, but once it reaches the last, it won't go back to the first image again.
Comment: Are you sure you added the `% srcs.length`? That will have `i` loop around back to 0 after the final image is reached
Comment: I must have done something weird with my code somewhere initially. It works now! Thank you so very much.
Comment: What do I do with the script when I have multiple buttons? One button changes an image, while another button changes a different image (unrelated to the first button)?
Comment: Have a different array (and a different image selector) for each image / button
Comment: May I have an example for that as well?
Comment: Just copy the code again, but use different variable names everywhere. Eg `const srcs2 = ['foo.png', 'bar.png', 'baz.png'];
let i2 = 0;
function changeImage2() {
  var image2 = document.getElementById('myImage2');
  i2 = (i2 + 1) % srcs2.length;
  image2.src = srcs[i2];
}` and replace the `src`s in the array as well. Could also be done less repetitively
Comment: Do I need to separate the two different Javascript codes in some way?
Comment: No, no problem putting them in the same file
Comment: I replaced the srcs for the second, but the second button changes the second srcs to the first array's srcs. Here's my code: https://jsfiddle.net/Jonjei/s04nL97e/13/
Comment: Need to change `image2.src = srcs[i2];` to `image2.src = srcs2[i2];`, all the variable names should be different, using this approach
Comment: Changed, and everything's working now and looks amazing. Thanks so much for all your help!


What is a realm in Loopback?

Question: So I have been working with loopback 3 for a while, and I have seen in the user model that it contains the property realm.
So far I haven't found any information about what a realm is. I know It's mostly used in subjects like partitioning, but I have no clue what realm is about.
Are realms used to partition data based on for example company.
Like you have 2 users:
A: {
    username: "Mike",
    email: "email@example.com",
    realm: "Google",
    companyId: "12345e"
}
Company A: {
    name: "Google",
    adres: "1600 Amphitheatre Parkway, Mountain View, CA, US, 94043",
    id: "12345e"
}

B: {
    username: "John",
    email: "email@example.com",
    realm: "Microsoft",
    companyId: "56186f"
}
Company B: {
    name: "Microsoft",
    adres: "1065 La Avenida, Mountain View, CA, USA, 94043",
    id: "56186f"
}

When a user logs in will it then only see data of that company, or what does realm do exactly?
Answer: Yes, realm is used to partition users and their data.
For example, say you are implementing QuickBooks Online system, which has a single login endpoint and presumably a single 'User' table, but when a user logs in, he or she is logging into his or her own 'Company' dataset. To limit users to their own data in a hosted application, one approach is to dress the user and all their entities with a 'realm' property. QuickBooks is hosting data for 1000s of companies, and might have multiple users per company and those users might have differing permission levels within their own company.
Similarly you essentially have realms in Microsoft Azure or Amazon AWS. Basically whenever you have a web application that has more than 1 'tenant' meaning more than one data fiefdom, you use realms.

What is a realm in Loopback?


How to organize survival count/percentage data for a GLM

Question: I have a dataset ("mort") containing two variables in R.  The predictor variable is Treatment (categorical, 4 categories A, B, C, D) and the response variable is mortality (denoted as 1 for died and 0 for survived). I am interested in the question, "does mortality rate differ significantly between treatments." I'm trying to run a GLM with a binomial distribution.
Below is a subset of the dataset:
ID  Treatment  Mortality
1    A         0
2    A         0
3    A         0
4    A         0
5    B         0
6    B         1
7    B         1
8    B         0
9    C         0
10   C         0
11   D         0
12   D         1

I also made a summary table to get a sense of the counts and percentage mortality per treatment, which looks like this:
Treatment    Survived  Died  Total   Percent_mort
A            38         3     41      7.32
B            29         9     38      23.68
C            39         0     39      0.00
D            76         5     81      6.17

I've read through a couple guides on GLMs and seen several different methods of setting up the data for the GLM, but I am still unclear whether I should input the raw data or the summary of counts or percentages. I have a different total sample size in each treatment so it seems like I should be dealing in percentages to reflect that.
The Crawley R book chapter on proportion data summarizes deaths and survival counts by treatment, use cbind to combine the two columns, and runs the GLM on that data. Another source ran the glm on the raw 0/1 data as shown above (example here). I am confused on what the difference is between these methods and which would be better to use here to account for my different sample sizes. I guess my main question is, should I be running the model on the raw data (0s and 1s) or the summary (counts or percents)?
I then want to perform pairwise comparisons to see which treatments are significantly different from each other.
Here is what I ran so far on the raw data:
model <- glm(Mortality ~ Treatment, family = binomial, data = mort)

summary(model)

##to get a p value
Anova(model)

##to perform post-hoc comparisons
library(emmeans)

lsmeans(model, pairwise ~ Treatment)

Any advice would be greatly appreciated. Thank you!
Answer: You can do it either way, if you're careful. You'll get the same results from
model2 <- glm(cbind(Died, Survived) ~ Treatment,
              family = binomial,
              data = mort_table)

where mort_table is a data frame containing the summary you show.
Or yet another option:
model3 <- glm(Percent_mort/100 ~ Treatment,
              weights = Total,
              family = binomial,
              data = mort_table)

Comment: Thank you very much for your help!


What kind of SPSS test is this?

Question: I was wondering if anyone could tell me what kind of SPSS test would output something like this? I am trying to determine what method they used to compare whether nursing intervention or nicotine patch reduced the number of cigarettes a patient smoked daily compared to no treatment/intervention. I want to be able to recreate this output somehow. Please let me know. thanks.
Comment: So are you saying you saw this somewhere & are wondering what they did? Where did you see it? If it was in a article, there should have been a description of their analyses.
Comment: This is a standard ANOVA: you can confirm that by reproducing the $F$ statistic and its p-value from the `N` and `Mean (SD)` columns.
Answer: I don't believe this output table was created in SPSS, as the basic formatting is very different to SPSS. As whuber has said, it is a completely standard ANOVA. There are quite a few ways of getting something like this from SPSS, but the easiest would be to select Analyze > Compare Means > One-Way ANOVA, and selecting a Post Hoc comparison. I can't tell from this output what specific post hoc comparison was performed based on the data provide; however, most academic fields have their own preferred "standard" approach (e.g., Tukey, or, if standard are very low, LSD).
The output suggests that Nurse counselling was better than no Treatment (p = 0.036). Due to the small sample sizes, there is not really enough power to conclude much about Nicotine patch in my opinion.

What kind of SPSS test is this?


Change Google Home LED lights

Question: Google Home and Google Home Mini's use LED lights at the top of the device to indicate what the device is doing. Most of the time it is used by the system to indicate state of the device or actions.
https://support.google.com/googlenest/answer/7073219?hl=en
Is it possible to use the LED lights to interact with the user or change the standard behavior to improve the experience for users? For instance, changing the LED's to a full red circle when the action hits a fallback intent.
Answer: No, 3P developers do not have any control over the LEDs that may appear on a smart speaker.

Change Google Home LED lights


Why is $n_1 \sqrt{2} +n_2 \sqrt{3} + n_3 \sqrt{5} + n_4 \sqrt{7} $ never zero?

Question: Here $n_i$ are integral numbers, and not all of them are zero.
It is natural to conjecture that similar statement holds for even more prime numbers. Namely,
$$ n_1 \sqrt{2} +n_2 \sqrt{3} + n_3 \sqrt{5} + n_4 \sqrt{7} + n_5 \sqrt{11} +n_6 \sqrt{13} $$ is never zero too.
I am asking because this is used in some numerical algorithm in physics
Comment: If $n_1\sqrt{2}+n_2\sqrt{3}=0$ then $\sqrt{\frac{3}{2}}=-\frac{n_1}{n_2}$ is rational, a contradiction.
Comment: I am asking because this is used in some numerical algorithm in physics
Comment: As far as I can tell, this is answered [here](http://math.stackexchange.com/a/437374/42969) as a quite general answer to a much simpler question.
Answer: Assume that:
$$ n_1\sqrt{2}+n_2\sqrt{3}+n_3\sqrt{5}+n_4\sqrt{7}=0.\tag{1} $$
That implies:
$$ (2n_1^2+3n_2^2)+2n_1 n_2 \sqrt{6} = (5n_3^2+7n_4^2)+2n_3 n_4 \sqrt{35}\tag{2} $$
as well as (just keep rearranging and squaring):
$$ (2n_1^2+3n_2^2-5n_3^2-7n_4^2)^2 = 24 n_1^2 n_2^2 + 140 n_3^2 n_4^2 - 8n_1 n_2 n_3 n_4 \sqrt{2\cdot 3\cdot 5\cdot 7} \tag{3}$$
but the last line implies $\sqrt{2\cdot 3\cdot 5\cdot 7}\in\mathbb{Q}$, which we know to be false.
The same approach works also in the second case.
Comment: "The same approach works also in the second case." Not so sure. Of course we can try it, but at some moment can get lost in calculations.
Comment: @user26857: you do not need to really perform them, you just have to convince yourself that by rearranging and squaring we may obtain many integers and a single square root, the square root of $2\cdot 3\cdot 5\cdot\ldots$.
Answer: If $p_1,\dots,p_n$ are prime numbers with $p_i\ne p_j$ for $i\ne j$, then the field extension $\mathbb Q\subset\mathbb Q(\sqrt{p_1},\dots,\sqrt{p_n})$ has degree $2^n$ and a basis is given by the set $$\{1,\sqrt{p_{i_1}\cdots p_{i_k}}:1\le i_1<\cdots<i_k\le n, 1\le k\le n\}.$$ See Proving that $\left(\mathbb Q[\sqrt p_1,\dots,\sqrt p_n]:\mathbb Q\right)=2^n$ for distinct primes $p_i$.
Answer: We will prove a more general statement:

If $a_i\in \mathbb{Z}-\{0\}$ and $b_i$ are distinct positive integers which are square-free then $a_1\sqrt{b_1}+\cdots+a_k\sqrt{b_k}$ is irrational.

Proof: We'll prove by induction on $n\ge1$ that $a_1\sqrt{b_1}+\cdots+a_k\sqrt{b_k}$ is not irrational of second degree i.e. it's not a root of a polynomial of second degree with integer coefficients.
For $n=2$ it can be easily checked.
Let it's true for $n\leqslant k-1$. Then $\alpha=a_1\sqrt{b_1}+\cdots+a_k\sqrt{b_k}$ cannot be integer.
Suppose that $\alpha$ is a root of $p_2(x)=x^2+bx+c$ with integer coefficients.
We'll consider $P(x)=\prod(x-\alpha^*)$ where product taken by all numbers of form $\alpha^*=\varepsilon_1a_1\sqrt{b_1}+\cdots+\varepsilon_ka_k\sqrt{b_k}$
 where $\varepsilon_i \in \{-1,+1\}$.
The next two statements can be proved easily:
1) $P(x)$ is polynomial degree $2^k$ with integer coefficients.
2) $P(x)$ divides into $p_2(x)$.
From these statements we conclude that some $\alpha^*$ is also root of $p_2(x)$. By Vieta's theorem $-b=\alpha+\alpha^*=2(a_{i_1}\sqrt{b_{i_1}}+\cdots+a_{i_m}\sqrt{b_{i_m}})$ where $m<k$ and we get contradiction.
Comment: Could you prove two statements? It is not easy for me.


Inserting the output of a query into a table created on a different server SQL Server 2008

Question: I was wondering if someone can guide me as to how I can insert the output of a query into a table that I created on a different server from where I am running my query.
For example:
table is located on server1 called tbl1 in a database called database1.
the query that i am running is querying data located on server2.
for the insert command, would this work: server1.database1.tbl1
If you need more information please let me know.
Answer: Fully qualified remote names have 4 parts: servername.databasename.schemaname.tablename. You can do any operation with them, including INSERT-SELECT, as long as the linked server is properly configured for updates and the MSDTC is properly configured for the two servers to engage in a distributed transaction.
Answer: As long as you can reach both servers, it should be easy enough:
 INSERT INTO server1.database1.dbo.tbl1(list of columns)
   SELECT
      (list of columns)
   FROM
      server2.database2.dbo.tbl2
   WHERE
      (some condition here)

Answer: Your insert command on server2 would work but only if server1 is registered as linked server in server2.
Answer: Assuming you've created a linked server for server1, with appropriate permissions, you should be able to:
insert into server1.database1.dbo.tbl1
    select ...


Tabulação com jquery

Question: Como que eu faço para tabular uma frase e colocá-la uma debaixo da outra ?
Deixa eu explicar:
Estou usando este código para adicionar dentro de uma div:

Eu seleciono em uma select e vai adicionando com append. Só que está ficando meio embolado.
Detalhe: Não estou trazendo nada de banco de dados e sim está estático.
Alguém me sugere algo mais prático ou me orienta a tabular ???
Grato professores.
Answer: Você pode incluir a frase numa div, por exemplo, porque a div ocupa toda a largura da linha fazendo com que cada frase fique numa linha única:

$(document).ready(function() {

  $('#cbo_vitrine').change(function(){

  itemsel = $("#cbo_vitrine option:selected").text();

           if(itemsel == "REF-01")

                $("#det_prod_vitrine").append("
FLOR BATIDO - MARROM - Nº: 23 ao 41 - R$34,99
");

           if(itemsel == "REF-02")

                $("#det_prod_vitrine").append("
MEDALHÃO - MARROM - Nº: 33 ao 44 - R$34,99
");

           //if(itemsel == "REF-...")
   });
});

<select id="cbo_vitrine">
   <option>REF-01</option>
   <option>REF-02</option>
</select>

Ou quebrar a linha com um
 no final da frase:

$(document).ready(function() {

  $('#cbo_vitrine').change(function(){

  itemsel = $("#cbo_vitrine option:selected").text();

           if(itemsel == "REF-01")

                $("#det_prod_vitrine").append("FLOR BATIDO - MARROM - Nº: 23 ao 41 - R$34,99
");

           if(itemsel == "REF-02")

                $("#det_prod_vitrine").append("MEDALHÃO - MARROM - Nº: 33 ao 44 - R$34,99
");

           //if(itemsel == "REF-...")
   });
});

<select id="cbo_vitrine">
   <option>REF-01</option>
   <option>REF-02</option>
</select>

Tabulação com jquery


What does Drush error "Unknown option: --db-url" mean?

Question: Somehow user 1 has become blocked on a Drupal site I manage.   As a result, I can't issue a uli command via Drush.  I tried to use the command
drush @pantheon.xxxxxx.dev user-unblock --uid=1

but it returns error
Unknown option: --db-url.  See `drush help user-unblock` for available options.

I have checked the help for user-unblock for but it does not mention --db-url.  The site is working and and other users can log in, however I can't get in as admin.
Thanks.
Comment: http://help.getpantheon.com/pantheon/topics/using_drush_60_pantheon_how_set_strict0_globally Looks similar?
Answer: Pantheon site aliases are only compatible with Drush 5. I had the same message when trying to use Drush 6.
On a Mac with Homebrew, I ran "brew install drush5" and then symlinked the resulting file (/usr/local/Cellar/drush5/5.9/libexec/drush) to "/usr/local/bin/drush5" not to interfere with my existing Drush installation.
Now I can run commands such as "$ drush5 @pantheon.xxx uli" when needed for Pantheon.
Comment: Note for those not handy with the CLIs, symbolic link is created via "ln -s /usr/local/Cellar/drush5/5.9/libexec/drush /usr/local/bin/drush5"
Answer: incase someone is trying to add -- to other drush commands you can use:
terminus drush site.env -- [drush command here] -- [drush option here]
the "--" after the site.env will pass the options to drush instead of terminus.
example: terminus drush $SITE_ID -- up -s --security-only
Answer: As of this writing, Pantheon site aliases are only compatible with Drush 5.
If you're using a newer version of Drush (6, 7, 8+), you'll likely get the following message when trying to execute a Drush command with a Pantheon alias:
$ drush @pantheon.xxx.xxx status

Unknown option: --db-url. See `drush help pm-enable` for available [error]
options. To suppress this error, add the option --strict=0.

There are two possible workarounds:

Provide the option --strict=0 to each Drush command
$ drush @pantheon.xxx.xxx status --strict=0
Install Drush 5 and use it specifically with Pantheon
If you're a Mac user and use Homebrew, the second option is as simple as:
$ brew install drush5
$ ln -s /usr/local/Cellar/drush5/5.9/libexec/drush /usr/local/bin/drush5
$ drush5 @pantheon.xxx.xxx user-login

The first method works for me using Drush 8.1.9 and Drupal 7.53 (and optionally Terminus 1.0.0) on macOS 10.12.3 "Sierra". I have not personally tested the second method.
In either case, be sure your Pantheon aliases are up-to-date:
$ terminus aliases
[notice] Aliases file written to ~/.drush/pantheon.aliases.drushrc.php

Comment: This is an older question, so the later answer is more applicable. --strict=0 is the quickest and least confusing solution, imo.
Answer: Have you tried fixing it directly in the database?  You should be able to update users set status = 1 where uid = 1;
If for whatever reason you cant do this, you can try running the query with drush: drush sql-query "update users set status = 1 where uid = 1"


mDNS - how to know a device is out of the wifi signal range

Question: I would like to ask a question about mDNS.
I am trying to create a Linux process which can discover some services (e.g. _airplay._tcp., _raop._tcp) from the other device
when the device joins the Linux AP.
I can get the notification through mDNS, and use the dns-sd command,
dns-sd -B _xxxx._tcp

I can see:
Browsing for _xxx._tcp

Timestamp     A/R   Flags if    Domain    Service Type    Instance Name
18:06:15.281  Add   3     8     local.    _xxxx._tcp.     xxxx_name

However, when I move the device out of the WiFi range, I can not get the removed notification through mDNS and no removed event is seen by dns-sd command. I was wondering if it is expected that mDNS can not know the device is removed in this case?
Or maybe mDNS can know the device is removed through the network interface changed?
I can not get the removed event, it is because my Linux network configuration is wrong?
Comment: A device that is out of radio range cannot communicate that it is out of range!
Answer: Yes, it is expected that mDNS cannot know that a device has disconnected from the network.  A device that is not on the network cannot say that it is no longer on the network, and there is no central registry of devices or service registrations in mDNS -- it is entirely and explicitly designed to be decentralised.  You can trade off accuracy for network traffic and query latency, by setting the mDNS record TTL to be quite low, but you can't solve the problem entirely.
Given that essentially the same problem can happen even using regular DNS (and dynamic updates), or practically speaking any service discovery system, the solution to whatever problem you're actually trying to solve is "don't rely on service discovery data being up-to-date, because it often won't be".  That means doing your own "liveness" checking on services, properly handling all manner of errors (including using sensibly low connection timeouts), and generally assuming that SD data is, at best, a vague hint in the right direction, and not some sort of absolute guarantee that a particular service is available for you to use at any given moment.


Installation fails with missing "file" -plugin error

Question: We are creating our own D8 installation profile from previously built site. We exported config and split it to modules, so that our custom modules are defining their own configs.
We've had a lot of issues, basically because we don't know how to debug site installation. XDebug seems to catch nothing. But now I've gotten pretty far, modules do get installed, but the configuration import fails on following error:
<code>[ERROR] The "file" entity type does not exist.
</code>
Error gets thrown at Drupal\Component\Plugin\Discovery\DiscoveryTrait.php, but sadly I'm not able to get PHPStorm's debugger to catch that file.
<code>protected function doGetDefinition(array $definitions, $plugin_id, $exception_on_invalid) {
    // Avoid using a ternary that would create a copy of the array.
    if (isset($definitions[$plugin_id])) {
      return $definitions[$plugin_id];
    }
    elseif (!$exception_on_invalid) {
      return NULL;
    }

    throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist.', $plugin_id));
  }
</code>
So basically I'd need a way to debug this installation via profile or some way to find out which config file is responsible. I'm finding this unnecessarily difficult, so any help is appreciated.
Cheers,
Janne
Answer: Yeah, got this sorted.
The reason for this strange behavior was unsurprisingly misconfigured field in some entity's baseFieldDefinition method.
Someone had used in display plugin configuration "file" instead of correct "file_generic" and for some reason this hadn't been triggered before this. The app has been live for about 6 months and gone through numerous updb's and entity-updates.
This was a nice one. I'll just leave this here in case someone has same mistakes :)


Multivariate Normal Distribution: Divide each random variable by its standard deviation

Question: If $X$~$Normal(\mu,\Sigma)$, and I divide each random variable in $X$ (the marginals) by its standard deviation, what will happen to the covariance matrix $\Sigma$?
Answer: So, let's say $X=[X_1,...,X_n]$, and your new vector is $Y=[X_1/\sigma_1, ...,X_n/\sigma_n]$. For each pair $i,j$, the new covariance entries will be
$$(\Sigma_Y)_{ij}=\operatorname{cov}(X_i/\sigma_i, X_j/\sigma_j)=\frac{\operatorname{cov}(X_i,X_j)}{\sigma_i\sigma_j}=\frac{(\Sigma_X)_{ij}}{\sigma_i\sigma_j}$$
Note that, the diagonal entries will all be $1$ (assuming no degenerate entries exist).


What is the right name for an "inversive" function

Question: Say, $y = x^2$ is the function, while $x = \sqrt{y}$ is its "inversion". I'm not sure what is the right name for this. What is it?
Comment: [inverse function](https://en.wikipedia.org/wiki/Inverse_function), though you have to be careful about the domain so it's a function
Comment: @J.W.Tanner maybe you can turn your comment into an answer and I'll happily accept it?
Comment: The inverse , and when a confusion is possible (with the *multiplicative* inverse, $\frac1x$), the *functional* inverse.
Answer: A function that "reverses" another function is called its inverse function.
Note that $f(x)=x^2$ on $\mathbb R$ does not have an inverse function,
because, for example, both $2$ and $-2$ get mapped to $4$ by $f$.
But $f(x)=x^2$ on $\mathbb R^{\ge0}$ does have an inverse function.


String comparison not working correctly

Question: I'm having a problem with String comparison, while some words return the correct result others simply don't..
for (int s = 0; s < subjects.getLength(); s++) {
    Element subject = (Element) subjects.item(s);
    String sub = subject
                    .getElementsByTagName("name").item(0)
                    .getTextContent();
    Log.d("Subject", getSubject() + "!A");
    Log.d("Subject", sub + "!B");
    Log.d("Subject", "equalsIC: " + String.valueOf(getSubject().equalsIgnoreCase(sub)));
    Log.d("Subject", "Contains: " + String.valueOf(getSubject().contains(sub)));
    Log.d("Subject", "Equals: " + String.valueOf(getSubject().equals(sub)));
    Log.d("Subject", "ContentEqu: " + String.valueOf(getSubject().contentEquals(sub)));
    Log.d("Subject", "Length A: " + String.valueOf(getSubject().length()) + "; Length B: " + String.valueOf(sub.length()));
    if (getSubject().equalsIgnoreCase(subject
               .getElementsByTagName("name").item(0)
               .getTextContent())) {
        Log.d("Subject", getSubject() + "Success !C");

The getSubject method is returning a String.
While this works perfect for "BK G3":
D/Subject﹕ BK G3!A
D/Subject﹕ BK G3!B
D/Subject﹕ equalsIC: true
D/Subject﹕ Contains: true
D/Subject﹕ Equals: true
D/Subject﹕ ContentEqu: true
D/Subject﹕ Length A: 5; Length B: 5
D/Subject﹕ BK G3Success !C

It simply fails with "D  G4":
D/Subject﹕ D  G4!A
D/Subject﹕ D  G4!B
D/Subject﹕ equalsIC: false
D/Subject﹕ Contains: false
D/Subject﹕ Equals: false
D/Subject﹕ ContentEqu: false
D/Subject﹕ Length A: 5; Length B: 5

I tried it with sub.trim(), but nothing changed..
Thanks in advance.
Edit
Debugging gives me the following information:
sub = (java.lang.String@83000929)"D  G4"
value = {char[5]@830092913560}
hashCode = 0
offset = 0
count = 5

((Activity_Add)this).subject = java.lang.String@830088265176)"D  G4"
value = {char[59]@830080636976}
hashCode = 0
offset = 6
count = 5

Comment: Have you tried to debug each string to see the byte by byte it's content?
Comment: From what I see they are in fact different. Looking at the html from your post I can see that the first string is `D  G4` and the second one is `D  G4`.
Comment: What are those 59 chars that the second string have?
Comment: @Pedro Oliveira It's probably due to this line `subject = subjectList.get(position);`
Answer: Use
sub.replaceAll("\\s+","")
instead of
sub.trim();

String comparison not working correctly


Java how to repeat a statement if it doesn't match a condition

Question: I am trying to get this program to restart if the user input doesn't match the correct format. However I am unsure of how to do this. I have attached the code below:
package weeek4;

import javax.swing.JOptionPane;

public class rollNumber {
public static void main(String[] args) {

String input = JOptionPane.showInputDialog(null,"Enter your Roll Number in        this format **-***-*****");

if (input.matches("\\d{2}-\\d{3}-\\d{5}")) {
JOptionPane.showMessageDialog(null,"Thank you");
}
else {
    JOptionPane.showMessageDialog(null,"Invalid Number");
    }

}
}

Comment: use a while loop and a flag?
Comment: Please format your code before posting a question. Also, class names in Java should start with an upper-case letter.
Comment: I would advise you check out the following portion of the Javadoc about `while` statements.: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Answer: It is quite easy . Just use a loop(A statement that repeats a block of code until a certain condition is met) and a flag variable(in this case , k checks for the condition in the while loop)
package weeek4;

import javax.swing.JOptionPane;

public class rollNumber
{
   public static void main(String[] args)
   {

      String input = JOptionPane.showInputDialog(null,"Enter your Roll Number in        this format **-***-*****");
      int k = 0;
      while (k!=1)
      {
         if (input.matches("\\d{2}-\\d{3}-\\d{5}")) {
            JOptionPane.showMessageDialog(null,"Thank you");
            k=1;
         }
         else
            JOptionPane.showMessageDialog(null,"Invalid Number");
      }

    }
}

Hope I helped :)