What's the use of the new Star button in the project pages?

Question: If you go to a Drupal project page (for example, Views) you will see a new button with a Star, like this:

Logged-in users can Star and Unstar a project.
But what is the real use of this button?
I can't find all the users that have starred a project.
Comment: Hey downvoter. Why do you think that this question is bad? Help me to improve it please.
Comment: When I look at the views page, I don't see that "star" (as in your image), I only see the star itself, and the "35" ... That is when I'm not logged in. After I log in, I do get a similar Star-image like your question here. Also, do you mean "star" or "start"?
Answer: Consider this "Star"-facility as a way to "bookmark" specific contributed modules as your "favorites". Some more details about it (from What's new on Drupal.org? - April 2017):

Users on Drupal.org may now star their favorite projects - making it easier to find favorite modules and themes for future projects, and giving maintainers a new dimension of feedback to judge their project's popularity. Users can find a list of the projects they've starred on the user profile. Over time we'll begin to factor the number of star's into a project's ranking in search results.

Notes:

Projects that you star-ed are shown to others also. E.g here are your current star-ed projects.
When I look at the views page (without being logged in to D.O), I don't see that "star" (as in your image), I only see the star itself, and the "35". After I log in, I do get a similar Star-image like your question here.
Answer: For the moment the only thing that I can remark is a list with your starred projects, this is available in your profile:

And you can access trough https://www.drupal.org/user/YOUR_USERNAME/starred
Comment: https://www.drupal.org/drupalorg/blog/whats-new-on-drupalorg-april-2017 https://www.drupal.org/node/1973934


EXCEL Distribute values in a column based on conditions

Question: I need a formula to distribute values based on conditions.
In below (attached) image of excel sheet are two tables. Table-1 where i need data to be filled from Table-2. Formula should look in to table-2 and pick a value of 88587+HAWA+Jan and distribute in to Table-1 88587+HAWA+Jan column and so on till Dec...
Example:
In Table-2 formula pick 88587+HAWA+Jan (value is 71,405) than search in Table-1 for 88587+HAWA+Jan (in my case there are two matches to be filled with C3 and C6) now divide the value with count of matches 71,405/2= 35,703. Now formula put that 35,703 into C3 and C6.
Thanks in advance
Answer: Put this in C3 and copy over and down.
<code>=SUMIFS(C$28:C$100000,$A$28:$A$100000,$A3,$B$28:$B$100000,$B3)/COUNTIFS($A$3:$A$24,$A3,$B$3:$B$24,$B3)
</code>
Comment: Thank you Scott that's exactly what i want.
Comment: @AXL please mark as correct by clicking the check mark by the answer.


Theme default Colors FG and BG for both editing and compare makes elements never seen

Question: I am quite newbie.
After I have installed Studio3 plugin Eclipse, I got some problems of colors with Default Theme.
In these for the moment I have a not workaround situation while using the "Text compare" because I could not find how two change the color of elements which have the same color as background "black".
When black background is used, as the comparison mode uses black as default color for many elements they are hidden. I made some test with a variant grey background to find the elements, it obviously can't be used for normal use.
Where are the template definition for "comparison mode" seems the main question ?
The minimum to reach is that the black ForeGround colored elements (defined surely for white background) become white with a black background.
Elements of analysis :
The changes on other elements are taken in account in comparison mode (and obviously in edit mode which functions normally), but the elements that are not taken in account in comparison mode are black by default. So I look at a default color for not held elements, I could not find such an item. The default values that I found, and that I declared FG white, have no effect.
Thanks for help.
Trebly
Aptana Studio 3.0.7
No changes done to default parameters
context : Php
black elements in compare mode : vars; functions calls; names; syntax base;
hold elements : text; keywords (var, function, parent, class, extends, array, empty....); comments
Answer: After quite long search :
When Aptana studio3 plugin is installed, the default theme can not be well setup for others editors than Aptana such as standard comparison if you use the Aptana studio3 theme. Then you get incoherent display. The solution is simple.
To get everything right, if the application is able to hold new Aptana theme management, you must simply :
1- change the default Aptana studio3 theme for example for ECLIPSE (Base) theme
2- Change again to Aptana studio3 theme, this will reset all elements of themes (for various compatible editors)
Note : SmartyPDT (and others not tested probably) are not compatible with the theme management of Sudio3, in such case you need to stay with another theme as Studio2 (theme option in studio3). In fact the defined colors are compatible with studio2, particularly black standard text (which was default color). The incompatibility makes that you get a not a coherent fit of colors which lead to incoherency, which can't be avoided, worse black on black... for some text-elements.
Trebly


pass a 2-parameter function to combn

Question: I'm using the built in dataset "ChickWeight". For each name, weight, Time, Chick, Diet, my function is simply taking the difference between each pair of names, weight Time, weight Chick, weight Diet, Time Chick, Time Diet, Chick Diet. The function and calculation itself are rather simple and unecesary, but I would like to find  how I can pass the 2 parameter function in the combination.
My script is as follows
out <- combn(names(ChickWeight), 2, simplify=FALSE)

f <- function(x, y)
{
diff <- (x - y)
}

mapply(f, out[1,], out[2,])

UPDATE: It seems that I need to subtract the numeric values in my function f, NOT the names. I'm wondering how I may do this. Perhaps I need to find a way to reference out[1,] and out[2,] so that the numeric values in the respective columns can be called upon.
Comment: Have you checked `out[1,]`?  The `f` is getting the difference between `names` and not on numeric elements
Comment: You should use simplify=TRUE in `comb`. Then your `mapply` function should work.
Comment: Then you'll get a different error since you are subtracting characters
Comment: Thanks guys. Is there a way to reference ChickWeight with out[1,] and out[2,] so that my function substracts the numbers within their respective columns?
Answer:
I would like to find how I can pass the 2 parameter function in the combination.

Ok, so there are two problems. The programming one is resolved by something like
combn(names(ChickWeight), 2, function(x) ChickWeight[[x[1]]] - ChickWeight[[x[2]]])

combn always takes a single-parameter function, confusingly.

The conceptual problem is: Chick is ordinal data and Diet is categorical. Neither of these make sense in arithmetic operations like subtraction (which is why the code above gives warnings and NAs).
Comment: Thanks a lot for this. I've tried using a different data set and it works fine. Having only one paramater may make things a bit more difficult as I eventually want to use a function that is more complicated. For eg. I would like to find the coefficient between the datasets via lm(). Would you recommend I use a command other than combn?
Comment: I guess `lm` should work fine with `combn`. You'll probably just want to reorder the columns rather than try to pass their names to the `~` formula, though, like `lm(ChickWeight[c(1,2)])$coef`. Depending on the application, I might just use a loop (to simplify things) or parallelization (if the problem is so big that it's slow to do sequentially).

pass a 2-parameter function to combn


express.js - render the full data

Question: I am trying to render a array of object (highcharts points). The data should be fine, but when I try to render, I get [object Object] instead of the data themselves.
JSON.stringify() doesn t go well with HTML.
util.inspect, doesn t either, and add data.
toString() give me the same as the rendering.
I don t know what else to try, what I m trying to send is data for a highchart graphic.
Minimal example:
app.js:
var express = require('express'),
    app = express();

app.listen(8080);

app.get('/', function (req, res) {
    var view = 'test.ejs',
        theme = [{name: '1', y: 5}, {name: '2', y: 2}];

    res.render(view, {theme: theme});
    console.log('ok');
});

theme_days.ejs:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Result (as if, toString()):
[object Object],[object Object]

Result with JSON.stringify():
[{"name":"1","y":5},{"name":"2","y":2}]

Result with util.inspect:
[ { name: '1', y: 5 }, { name: '2', y: 2 } ]

EDIT:
I now understand that what s happenning is that ' is escaped to html, is there a way to prevent that?
Comment: The eacaping happends in the template level see this for solution http://stackoverflow.com/questions/8547131/how-to-include-html-code-in-a-view
Comment: @Max: Urg, that and JSON.stringify onstantly resolved the problem...
Answer: I ended up with this:
careful, it is sub optimal:
app.js
var express = require('express'),
    app = express(),
    util = require('util');

app.listen(8080);

app.get('/', function (req, res) {
    var view = 'test.ejs',
        theme = [{"name": "1", "y": 5}, {"name": "2", "y": 2}];//Added "
    console.log(JSON.stringify(theme));
    res.render(view, {theme: JSON.stringify(theme)});
    console.log('ok');
});

test.ejs:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Answer: Why don't you use <%- instead of <%= , and pass object JSON.stringify() method.
The first one will render object in HTML, the second one will render variables (as they are, eval)

express.js - render the full data


Menu css + javascript e jquery

Question: Bom galera, estou precisando de criar uma forma para reconhecer em qual menu estou clicando, tenho minha index onde eu chamo meus menus com um include, portanto preciso colocar uma barra verde no bottom do menu que está clicado.
Como fazer isto ?

Início

 Cadastro

Usuários

Publicação

Clientes

Paginas Internas

Menu

Banner

Contatos

Eu preciso apenas acrescentar active na classe do li que está em seleção. Um exemplo é
Conseguir fazer, porem ele ativa o Active na classe, mais fica pouco segundos voltando apenas para li marcada principal, o objetivo para iniciar a index como Active é para ela aparecer marcada assim que o site for iniciado, alguém tem alguma ideia melhor que solucione este problema.
$(function () {
    $('.mainnav li').on('click', function(){
        $(this).addClass('dropdown active');
        $(this).siblings().removeClass('active');

    });
});

Comment: isso é um site?, você está usando algum *CMS* ou *framework* pra desenvolver?
Comment: utilize o seletor CSS `li:hover a`, tem uma resposta que pode ajudar: http://pt.stackoverflow.com/a/42669
Comment: @ErlonCharles sim é um framework
Comment: @Sanção não é desta forma, quero dinâmico.
Comment: Deixa eu ver se entendi, você quer que quando você estiver em uma página o link no meno referente a esta página já venha marcado é isso?
Comment: @ErlonCharles conseguir o Caio mostrou como fazer da forma correta, obrigado pela colaboração.
Answer: Talvez algo deste tipo seja o que você procura?

$('.dropdown-menu li').on('click', function(){
  $(this).addClass('active');
  $(this).siblings().removeClass('active');
});
li.active{
  color: green;
}

li{
  cursor: pointer;
}

Item 1

Item 2

Item 3

Item 4

EDIT:
Conforme conversamos nos comentários, e conforme a edição da sua pergunta (e, honestamente, conforme o meu entendimento dela), fiz um ajuste no código acima, pra chegar no resultado que acredito que você deseja. Pra não blotar a resposta, coloquei o código numa pen.
Considerações:

Usei praticamente o mesmo HTML que você postou na sua pergunta. Retirei coisas como s e s pra deixar o código mais limpo.
Usar o hover, conforme citado pelo @Sanção nos comentários, me parece a coisa mais natural (e mais fácil de se fazer). Não sei se você tem algum impedimento com relação a isso.
O código não considera (e isto também não entra no escopo da sua pergunta), como você vai fazer para abrir os seus dropdowns, tanto que você verá que a classe active continua presente no último elemento interno que você clicou, caso você clique em um elemento externo (não sei se você precisa tratar isso). Se sim, acredito que esse tratamento possa ser feito juntamente com a abertura dos referidos dropdowns.

O segredo pra resolver foi colocar os títulos dos itens no primeiro nível dentro de uma tag . Assim, os seletores ficaram mais simples.
Comment: Conseguir resolver, faltava colocar o index, como active, pois ele é o primeiro a ser selecionado.
Comment: `.removeClass('active')`? Se um dia o @RenanRodrigues colocar outra classe em algum item, ela vai pro espaço no dia que alguém clicar em algum item do menu.
Comment: Porem quando está clicado no index não funciona.
Comment: Esse código funciona apenas para os `li` dentro de `.dropdown-menu`, Se você clicar em algum outro `li`, ele não vai funcionar mesmo.
Comment: Excelente, @ctgPi. editado.
Comment: E se caso eu tiver uma ul dentro do li, este itens como fica ?
Comment: @ctgPi Sabe como resolver o problema de quando vc clica em um li dentro de uma um diferente ele marca o index ?
Comment: Ok Obg, que Deus lhe abençoe!
Comment: @CaioFelipePereira conseguiu resolver ? porque agora na verdade ele não funciona, direitinho, devido ao index, eu preciso que ele comece com Active, preciso também quando ele clicar nos menus dropsdowns ele permaneça selecionado o li maior.
Comment: @CaioFelipePereira conseguiu mexer em algo ?
Comment: @RenanRodrigues veja minha resposta editada. qualquer coisa, só perguntar
Comment: @CaioFelipePereira infelizmente seu código ainda não está conseguindo obter o desejável. Quando eu clico em algum menu que tenha um link ele desabilita o Active e deixa apenas para o index. Se observar no site mesmo que me mandou ele não cumpri com os objetivos. Teria como dar mais uma olhada ?
Comment: @RenanRodrigues mas não é exatamente isso que você quer? que a classe `active` fique apenas no ícone que você clicou? Se não for, desconfio que não estou entendendo a sua pergunta. Se você puder explicar melhor, posso até tentar te ajudar
Comment: @CaioFelipePereira está acontecendo o seguinte, quando eu clico em algum menu que não tem o `href`, ele permanece clicado, porem quando eu clico em algum menu que tem um `href`, ele adiciona o `Active` e logo depois desabilita, não fica permanente, o ideal seria sair somente depois que eu mudar de pagina, ai sim ele iria para o `Active` da pagina em que eu estou em questão, da forma que está, ele fica apenas no index, ele vai para outra mais desabilita logo em seguida.
Comment: Ah. Você está mudando de página, certo? Quando você vai `listaUsuario.php`, por exemplo, ele carrega o menu com a classe `active`  no primeiro link,  é isso?
Comment: Exatamento @CaioFelipePereira quando clico em qualquer link ele volta para primeira.
Comment: Então o problema é diferente. Você tem que atribuir a classe `active` de acordo com a página que você se encontra. Se o seu menu, estaticamente, tem a classe no `index`, ele vai ser recriado toda vez que você muda de página e, assim, voltar a classe pro index. Você pode criar um menu diferente para cada página, no seu php, de acordo com o ícone que tem que estar ativo, ou salvar o ultimo elemento que vc clicou em um cookie ou algum tipo de storage, e atribuir a classe a partir daí. Mas dessa maneira o problema se tornou outro....

Menu css + javascript e jquery


Is it the case that for all sets $A, B, C,$ and $D$, $(A \times B) \cup (C \times D) = (A \cup B) \times (C \cup D)$?

Question: I think I have managed to work this out, however there is no solution provided with the question so I thought it best to check.
My working:
Let $(x,y) \in (A \times B) \cup (C \times D)$
$\Rightarrow x \in (A$ or $C)$ and $y \in (B$ or $D)$
$\Rightarrow (x, y) \in (A \cup C) \times (B \cup D)$
$\Rightarrow (A \times B) \cup (C \times D) \subseteq (A \cup C) \times (B \cup D)$
Now let $(x,y) \in (A \cup C) \times (B \cup D)$
$\Rightarrow x \in (A$ or $C) $ and $y \in (B$ or $D)$
$\Rightarrow (x, y ) \in (A \times B) \cup (A \times D) \cup (C \times B) \cup (C \times D)$
$\Rightarrow (A \cup C) \times (B \cup D) \nsubseteq (A \times B) \cup (C \times D)$
$\Rightarrow (A \times B) \cup (C \times D) \not= (A \cup C) \times (B \cup D)$
Is this correct?
Thank you.
Comment: i suggest you to check what you have done for another time (even the title)
Comment: What you try to prove in the body is more sensible that what you wrote in the title (switched $B$ and $C$ on the right-hand side).  But (as noted) even that is wrong in general.
Answer: No.
Suppose $B = D = \emptyset$ and $A \neq \emptyset$ and $C \neq \emptyset$.
Answer: To see if something is true or not, it is always a good idea to check on trivial examples. For example:

Is $[0,1]\times[0,1]\cup [1,2]\times[1,2]$ equal to $[0,2]\times[0,2]$?

Even better, just take a set with a small number of elements, for example:

Is $\{x\}\times\{u\} \cup \{y\}\times\{v\}$ equal to $\{x,y\}\times \{u,v\}$?
Answer: Usually if we want to show some set equality is incorrect, we can show this with a counterexample. You can think about what's going on here with the following example, and draw a picture: take $A=C=[0,1], B=D=[1,2].$  $A\times B=[0,1]\times [1,2],$ $C\times D=[0,1]\times [1,2].$ If you draw their union, it's a square with unit side length. But $(A\cup B)\times (C\cup D)$ is a square of side length two, namely $[0,2]^2$.
Answer: The first part was good: you did indeed show that $$(x,y) \in (A \times B) \cup (C \times D) \implies (x,y) \in (A \cup C) \times (B \cup D)$$
which is the definition of $(A \times B) \cup (C \times D) \subseteq (A \cup C) \times (B \cup D)$.
The second part was not good. If you want to show that an inclusion does not hold, you need to produce a counterexample. All you have done is showing $(A \cup C) \times (B \cup D) \subseteq (A \times B) \cup (A \times D) \cup (C \times B) \cup (C \times D)$.
So if you want a counterexample, can you find an element of $(A \cup C) \times (B \cup D)$ which is neither in $A \times B$ nor in $C \times D$?
Answer: You're right that $(A\times B)\cup(C\times D)\subseteq(A\cup C)\times(B\cup D)$, but your proof is slightly lacking.
Instead of "$x\in(A\text{ or }C)$" you should write "$x\in A$ or $x\in C$" -- natural language allows more freedom in where you can put "or" and expect to be understood, but once you start using symbols you're expected to be more rigorous.
Then it looks like everything of interest actually happens in the step from $(x,y)\in(A\times B)\cup(C\times D)$ to ($x\in A$ or $x\in C$) and ($y\in B$ or $y\in D$). Where you should go, doing things step by step is to ($x\in A$ and $y\in B$) or ($x\in C$ and $y\in D$).

You're also right that the opposite inclusion doesn't always hold, but instead of a series of $\Rightarrow$-connected formulas you should just show a counterexample.
The way you're writing it there looks like you're claiming that $(A\cup C)\times(B\cup D)\not\subseteq(A\times B)\cup(C\times D)$ necessarily holds, which isn't the case. For example, with $A=B=C=D=\{1\}$ equality does hold (both sides are $\{\langle 1,1\rangle\}$).


How to use following equation by using Green's function?

Question: Let's have the following equation:
$$
u''(r) + \frac{1}{r}u'(r) - \alpha^{2}u(r) = f(r),
$$
where $r$ is polar radius.
Method of Green's function leads to
$$
u''(r) + \frac{1}{r}u'(r) - \alpha^{2}u(r) = \delta(r). \qquad (1)
$$
Here I have little trouble.
It seems that the solution is $C_{1}I_{0}(\alpha r) + C_{2}K_{0}(\alpha r)$, where $I_{0}, K_{0}$ are Infeld and Macdonald functions respectively. But I don't know how to choose constants. It's obvious that Macdonald functions is correct solution of $(1)$, but I don't sure that I can set $C_{2},C_{1}$ to $1, 0$.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert #1 \right\vert}%
 \newcommand{\yy}{\Longleftrightarrow}$
$\ds{u''(r) + \frac{1}{r}u'(r) - \alpha^{2}u(r) = f}$
$$
u\pars{r}
=
{\rm u_{p}}\pars{r} + \int_{-\infty}^{\infty}{\rm G}\pars{r,r'}f\pars{r'}\,\dd r'
$$
where ${\rm u}_{p}\pars{r}$ is a solution of
$\ds{u''(r) + \frac{1}{r}u'(r) - \alpha^{2}u = 0}$ which satisfies the given boundary conditions. ${\rm G}\pars{r,r'}$ is the Green function which satisfies
$$
\pars{\partiald[2]{}{r} + {1 \over r}\partiald{}{r} - \alpha^{2}}G\pars{r,r'}
=
\delta\pars{r - r'}
$$
${\rm G}\pars{r,r'}$, as a function of $r$, satisfies homogeneous boundary conditions.
Comment: But can you comment my solution?


How to get continuous surface from collection of data points?

Question: I have a collection of datapoints in three dimensions x,y,z.
I'd like to be able to visualize the data as a smooth surface.
Stated another way:
Given those points, I'd like to be able to determine z for any arbitrary x and y such that the surface is smooth and continuous.
Tools available are anything that I can get my hands on for free.  Bias is for Processing, Python, or php.
Answer: There is scipy.interpolation for Python.
(This might be more of a question for stackoverflow or math.stackexchange.)
Answer: It looks like @bayer's answer will work well for you. For someone using R, the akima, fields, and tgp packages among others, would do the job, depending on the type of interpolation you want.


Solve related rate problem

Question:
The swimming pool has water coming in @ 12m^3/min. The contents with the pool keep mixing. The contents flow out @ 10m^3/min. Sugar is added to the pool @rate 0.1kg/min. At the beginning there is 10 kilogram of salt within 100m^3 of water. What is the kilogram of salt left after 30 min?

Let $x$ be the amount of sugar. Then conc = amount/vol
We have that initially $sugar/water = 10/100 = 1/10$. Concentration should be $x/(100 + 2t)$. We know that $dx/dt = 0.1$ and thus we want to multiply by $2t$. Thus
$dx/dt = (x*2t/[100 + 2t])*2t$?
Comment: @Chinny84. Sorry, detsild cominh right up
Comment: Sugar? Salt? Which one is it? Is it both?
Answer: No, $dx/dt$ is not $0.1$.  Rather $dx/dt$ is the sum of all the changes in sugar.  One change is $0.1$ kg/m.  Another changes is how much sugar is leaving the pool.  If $x$ is the kilograms of sugar in the pool at time $t$ then the concentration of sugar is $x/(100+2t)$.  The amount of sugar leaving each minute is $10$ times that.  So the differential equation is
$$\frac{dx}{dt} = 0.1 -\frac{10x}{100+2t}$$ with initial condition $x(0) = 10.$
This isn't really a "related rate" problem.  You need to solve the (linear) DE.

Solve related rate problem


Is there a R command for testing the difference in coefficients of two linear regressions?

Question: I am looking for a R command to test the difference of two linear regressoon betas. Lets say I have data $x_1, x_2...x_{n+1}$.
$\beta_1$ is obtained from regressing $x_1$ to $x_n$ onto $1$ to $n$.
$\beta_2$ is obtained from regressing $x_2$ to $x_{n+1}$ onto $1$ to $n$.
Is there a way in R to test whether $\beta_1$ and $\beta_2$ are statistically different?
Edit:
Here is a clearer problem statement:
I changed the notation for data from $x$ to $z$...
That's it. Should be very clear now... Thanks!
Data observations: $z_1, z_2, ..., z_{n+1}$
y1 = z_1,z_2,.........  z_n
y2 = z_2, z_3,......... z_{n+1}

x1 = 1, ..., n
x2 = 1, ..., n

y1 = A1+ x1 * B1 + epsilon_1
y2 = A2 + x2 * B2 + epsilon_2

H0: B1 and B2 are statistically significally different...
Comment: I'm a bit confused by your notation. Is "x1, x2...x(n+1)" referring to random variables or observations? And what is the significance of "(n+1)"?
Comment: Presumably you mean "H0: B1 and B2 are the same" and you are looking for statistically significant evidence to reject H0.
Comment: Are you trying to model a structural change in the data? If so, then the package [strucchange](http://cran.r-project.org/web/packages/strucchange/index.html) might be appropriate.
Answer: You can stack the data so that you have $x_1 ... x_n$ followed by $x_2 ... x_{n+1}$ in one column, then the next column would have $1 ... n$ repeated twice, then a third column would have $0$'s coresponding to the 1st group and $1$'s for the second group.  Now do the regression including an interaction between the $1 ... n$ and the $0/1$ group variable.  The slope for the interaction represents the difference between the 2 slopes you are interested in, testing the interaction will test if the slopes are different.  However, the standard regression assumptions may not hold here (your data certainly is not independent), so you should do some type of simulation under the null hypothesis to determine the critical region to use to determine significance.
Here is some example R code:
y1 <- anscombe$y1[order(anscombe$x1)]
y2 <- anscombe$y2[order(anscombe$x2)]

df1 <- data.frame( y=c(y1[-11], y1[-1]), x=rep(1:10, 2), g=rep(0:1, each=10))
df2 <- data.frame( y=c(y2[-11], y2[-1]), x=rep(1:10, 2), g=rep(0:1, each=10))

fit1 <- lm( y ~ x*g, data=df1 )
fit2 <- lm( y ~ x*g, data=df2 )

tmpfun <- function(n, beta, sigma) {
    x <- 1:n
    y <- beta*x + rnorm(n,0,sigma)
    df <- data.frame( y=c(y[-n],y[-1]), x=rep(seq(to=n-1), 2),
        g=rep(0:1, each=n-1) )
    fit <- lm( y~x*g, data=df )
    coef(fit)[4]
}

tmpfit <- lm(y1 ~ seq_along(y1))
out1 <- replicate(1000, tmpfun(11, coef(tmpfit)[2], summary(tmpfit)$sigma) )
hist(out1)
abline( v=quantile(out1, c(0.025, 0.975)), col='red')
abline( v=coef(fit1)[4], col='blue' )

tmpfit <- lm(y2 ~ seq_along(y1))
out2 <- replicate(1000, tmpfun(11, coef(tmpfit)[2], summary(tmpfit)$sigma) )
hist(out2)
abline( v=quantile(out2, c(0.025, 0.975)), col='red')
abline( v=coef(fit2)[4], col='blue' )

If you tell us more about what you are trying to accomplish we may be able to suggest better methods.
Comment: "Stacking" the data in this manner is clever.  However, that induces *perfect* correlations among many of the responses.  Because your model does not appear to account for that, its estimates look problematic--and even if they are correct, the covariance matrix, p-values, intervals, and associated hypothesis tests will certainly be wrong.  This problem is likely so severe that "your data certainly is not independent" doesn't look like a sufficiently strong caution.
Comment: Sorry for not being clear in my previous problem statement: I changed the notation for data from x to z...

That's it. Should be very clear now... Thanks!

Data: z1, z2, ..., z_{n+1}

y1 = z_1,z_2,.........  z_n
y2 = z_2, z_3,......... z_{n+1}

x1 = 1, ..., n
x2 = 1, ..., n

y1 = A1+ x1 * B1 + epsilon_1
y2 = A2 + x2 * B2 + epsilon_2

H0: B1 and B2 are statistically significally different...
Comment: @Greg Snow: Can you explain what `out1` & `out2` in your code are?
Comment: @user603, The `tmpfun` function returns the coefficient for the interaction in the analysis of the simulated data.  `out1` and `out2` are vectors with the returns from `tmpfun` from 1,000 runs of the simulation (so vectors of interaction coefficients from 1,000 simulation runs).
Comment: @GregSnow; thanks. What is the difference between them? I mean why do you have two?
Comment: @user603, they are based on different models.  In the code `tmpfit` is fit using `y1` then `out1` is created based on that model, then `tmpfit` is refit using `y2` and `out2` is created.  I probably should have used different names for the 2 fits to make it clearer.
Comment: @GregSnow Thanks. Could you also perhaps also explain what those two models are (it seems they only differ in how the response is sorted, is this correct?).
Comment: @user603, plot the 2 y-variables.  One is more linear than the other, so the more linear one does not reject that the slope changes and the less linear one does.
Answer: Are you doing something like:
set.seed(1)

x1<-rnorm(100,1)
x2<-rnorm(100,mean(x1))
y<-rnorm(100, mean(x1+x2)+rnorm(100))

fit1<-lm(y~x1, data)
fit2<-lm(x1~x2, data)

If so, you might be able to get away with:
d<-coef(fit1)[2] - coef(fit2)[2]

coef(fit)[2] is the second coefficient in the model, i.e. the beta

var1<-summary(fit1)$coef[4]^2

This is the fourth coefficient in the summary, or the se of beta1
var2<-summary(fit2)$coef[4]^2

ztest<- d / sqrt(var1+var2)

1-pnorm(ztest)

       x1
0.5918211

this was my answer, so I would say there is no difference, but beta1 was -.11 and beta 2 was .-07, so they're pretty similar.
Comment: Welcome to the site Corey. Please use the markdown formatting available (see the buttons at the top of editor when inserting your answer), or take a look at the advanced markdown editing help, http://stats.stackexchange.com/editing-help. In particular, it is much easier to read code when it is formatted appropriately.


How to calculate line integral over an ellipse with vector field undefined inside the ellipse?

Question:
Given vector fields:
  $$
P=\frac{-y}{(x-1)^2+y^2}\\
Q=\frac{x-1}{(x-1)^2+y^2}
$$
  calculate $\oint_CP\,dx+Q\,dy$ over ellipse $\frac{x^2}{25}+\frac{y^2}{36}=1$.
Define the domain where the function $U=\arctan\big(\frac{y}{x-1}\big)$ is the potential function to the given field.

I tried doing parametrization for the curve that can de derived from ellipse:
$$
c(t)=\langle 5\cos t,6\sin t\rangle
$$
and plugging this directly into the integral. But very quickly the integral becomes quite complicated.
I think there must be some trick here which I don't see. If there's a potential function then the field is conservative. But the problem is that the field is not defined at point $(1,0)$ which is inside the ellipse. For the same reason I don't think we can use Green's theorem as well.
Comment: Do you know Green's theorem?
Comment: @JohnHughes yes, now that you mentioned it I actually did calculate $P_y$ and $Q_x$ and it turns out that $\iint (P_y-Q_x)=0$ so the integral is zero I guess? (because $P_y=Q_x$)
Comment: You tell me! When you're done, write it up as an answer and accept it, which'll close out the question (but won't get you any points).
Comment: I'm not interested in points :)  I will write this as edit to the question but there's one part of the answer which is missing: the domain for the potential function. The way I see the potential is undefined along the line $x=1$, is it correct?
Comment: I hadn't really looked at the formulas for $P$ and $Q$; these are not even defined at the points on the ellipse where $x = 1$, so I'm not certain what the integral even means.
Comment: @John Hughes: of course the components *are* defined at the points *on the ellipse* where $x=1$, for in those cases $y\neq0$. The singularity happens when the denominators vanish, which happens at the point $(1,0)$.
Comment: D'oh! Nevermind.... Need more coffee. :)
Comment: @symplectomorphic so the field has the potential function everywhere on the $xy$ plane except for $(1,0)$?
Answer: Let $E$ denote the interior of the ellipse and $\partial E$ the boundary (i.e. the ellipse itself). You're trying to calculate
$$\color{blue}{\oint_{\partial E}\mathbf{F}\cdot d\mathbf{r}}$$
Your first hope is that Green's theorem applies, so you can instead calculate
$$\int_E(Q_x-P_y)\,dA$$
The problem is that the hypotheses of Green's theorem are not satisfied, for the functions $P$ and $Q$ are not continuously differentiable throughout the region $E$. As you observed, there is no way we may continuously extend the field to be defined at the point $(1,0)$, so that point is a singularity.
The way to proceed in such cases is to put a little closed curve around the singularity but still lying entirely inside the region $E$ of interest; in this case a unit circle will be convenient (the calculation will show you why). So let $D$ be the unit disk centered at $(1,0)$, and let $\partial D$ be the unit circle centered there, which has parametrization $C(t)=(\cos t +1, \sin t)$ for $t\in[0,2\pi)$.
You can easily check by direct calculation that
$$\color{red}{\oint_{\partial D}\mathbf{F}\cdot d\mathbf{r}}=\int_0^{2\pi}(\cos^2t+\sin^2t)\,dt=2\pi$$
Now, consider the region $E-D$, the complement of the disk in the elliptical region. In this region, $P$ and $Q$ are continuously differentiable everywhere, so we may use Green's theorem, which says
$$\int_{E-D}(Q_x-P_y)\,dA=\oint_{\partial(E-D)}\mathbf{F}\cdot d\mathbf{r}\tag{$\star$}$$
The left side vanishes, because $Q_x-P_y=0$ in the region $E-D$. What about the right side? What is the "boundary" $\partial(E-D)$ of the elliptical annular region $E-D$? It is $\partial E - \partial D$, where we interpret the negative sign on $\partial D$ to mean reversing the standard counterclockwise orientation.
So $(\star)$ says
$$0=\color{blue}{\oint_{\partial E}\mathbf{F}\cdot d\mathbf{r}}-\color{red}{\oint_{\partial D}\mathbf{F}\cdot d\mathbf{R}}$$
The blue integral is the one the problem asks for, and the red integral we calculated above.

To summarize, the strategy for calculating line integrals of curl-free fields around closed curves that encircle a single singularity is to replace the original closed curve with an easier one (but still contained within the original one). Green's theorem in the region between the curves guarantees the line integral around the easier curve equals the line integral around the original curve.
What makes a good candidate for an "easier curve"? Well, you're trying to find a curve whose parametrization will make the integrand simple enough to calculate. In your problem, integrating around the ellipse gives a "hard" integrand. But integrating around a circle centered at the singularity gives an "easy" integrand.
Why a circle in this case? Because your field is closely related to the pullback of the length element of a circle of radius $r$ (the length element is $ds=r d\theta$); thus it was, in some sense, tailor-made to be integrated around a circle. It is not always so easy to spot what sort of curve will make the line integral easier, but you should remember the general form $(-\frac{y}{r^2}, \frac{x}{r^2})$, which is $\frac{1}{r}$ times the circle's unit tangent vector. The line integral of the unit tangent vector around the circle gives $2\pi r$, and the factor $\frac{1}{r}$ scales the result to $2\pi$. (In other words, you are just integrating $d\theta=\frac{1}{r}ds$ around the circle.) So the radius of the circle you use around the singularity doesn't matter. (This make sense, because the region between two concentric circles centered at the singularity doesn't contain a singularity and the field is conservative there, so by the above argument, the line integral of the field around them should be the same.)
Comment: PS: The deeper moral of this problem is that *the line integrals of two closed curves in the plane, one inside the other, will be equal whenever the (two-dimensional) curl of the field vanishes in the region between them* (and there are no singularities there). This has to do with the "homotopy-invariance" of the integrals of closed 1-forms.
Comment: @Yos: if $x=1+\cos t$ and $y=\sin t$, then $P=-\frac{\sin t}{(1+\cos t - 1)^2+\sin^2t}=-\frac{\sin t}{1}=-\sin t$, and $dx=-\sin t\,dt$, hence $P\,dx=\sin^2t\,dt$, etc.
Comment: (You seem to have forgotten that $x=\color{red}{1+}\cos t$, not $\cos t$ alone.)
Comment: @Yos: **no**, integrating $F$ around a circle of radius $0.04$ does not give $0.04\cdot 2\pi$. The argument in my previous comment implies you must be wrong, so to find your error you should try writing out the integral in detail. Notice your parametrization will now be $(1+0.04\cos t, 0.04\sin t)$. And notice the cancellation that happens...
Comment: @Yos: the function $U=\arctan(\frac{y}{x-1})$ isn't defined when $x=1$. The domain in which $U$ is a potential for $(P, Q)$ is disconnected by the line $x=1$.
Comment: The function $U = \arctan(\frac{y}{x-1})$ can be extended to a function defined everywhere except on a "branch cut" such as $x \le 1, y = 0$.  (See, for example, the C function `atan2` which is a typical example of this.)  In fact, that gives another way to calculate the integral: by taking out a small piece of the ellipse near the branch cut, on which piece the integral is tiny, the rest of the integral then becomes the difference in $U$ between the two sides of the branch cut, which is exactly $2 \pi$.
Comment: @Yos: I don't know what your last comment means. Are you asking how someone figured out that $U(x,y)=\arctan(\frac{y}{x-1})$ is a potential function for $(P,Q)$ (in the region where it's defined)? That has nothing to do with the ellipse. To find a potential $U$, you want $U_x=P$ and $U_y=Q$. So integrate $P$ with respect to $x$; that gives $U=\arctan(\frac{y}{x-1})+C(y)$, where $C(y)$ is some function of $y$ alone. Differentiating this $U$ with respect to $y$ and setting it equal to $Q$ shows we can take $C(y)=0$.
Comment: First of all this is an amazing answer! I have a few questions though: did you just plug in the parametric curve values into $\int_{\partial D} F\cdot dr$? I got $\cos^2 t+\sin^2t$ in the nominator but in the denominator: $$x^2-2x+1+y^2=(\cos t+1)^2-2(\cos t+1)+1+\sin^2 t=0$$
Comment: You're absolutely right, forgot that $x=1+\cos t$. My other question is you chose the circle around singularity to be of radius one hence we got $2\pi$. but what if you chose another circle which would be much tighter, say with radius $0.5$ then we'd get a different value when calculating $\int_{\partial D} F\cdot dr$. but the answer must be unique right?
Comment: @Yos: no, you wouldn't get a different answer if you chose a circle of radius $0.5$. This follows from my first comment on my answer: because $Q_x-P_y$ vanishes in the region between the two concentric circles and because there are no singularities in that annulus, the line integral around one circle will equal the line integral around the other circle. In other words, the exact same reasoning given in my answer shows that the radius of the circle doesn't matter.
Comment: I'm trying to understand: if we chose a circle of radius $0.2$ then $\int_{\partial D}Fdr=0.04\cdot 2\pi$. Then $\int_{\partial E} Fdr=\int_{\partial D}Fdr=0.04\cdot 2\pi\neq 2\pi$
Comment: Last question: the domain of where the function $U$ is the potential function to the field is all of $xy$ except for $(1,0)$?
Comment: What would be the curve to calculate the potential, the ellipse curve? But it's parametrization, provided I did it correctly, is $c(t)=\langle 5\cos t,6\sin t\rangle$ and if we calculate it from $0$ to $2\pi$ then $5\cos t=0, 6\sin t=0$ which doesn't make sense
Comment: The way I understood Daniel Schepter's comment is that we can also calculate the integral with the potenial function. But for that we need two points for $x$ and $y$. How do I get those two points?


How can I edit coordinates on a map imported from a delimited text layer?

Question: I have a .shp and a .csv with coordinates. I want to plot those coordinates on the map. However, some points are out of my desired range and I want to delete them. I know I can't edit the layer but what are my options? Plot every single coordinate and delete them in the csv and then upload it?
Answer: Using QGIS, I would do as follows:

Load the shapefile, and the CSV (delimited text).
Save the CSV points as a layer (geopackage or shapefile)
Use the "Select by Location" tool (Under Vector->Research Tools), and choose the "disjoint" predicate (points originally from CSV not in shapefile areas).
Begin editing the points layer, and click the "Delete Selected" button to delete all selected (those outside the shapefile areas).
Save edits
If you need this as a CSV, use the "Save as" option on that layer.


Falta de conexão com servidor via HttpURLConnection

Question: Tenho uma aplicação que faz consulta em uma URL através do seguinte método dentro de uma AsyncTask:
 try {
            HttpURLConnection http = getHttpUrlConnection("http://www.sitedoservidor.com.br");
            if (http != null) {
                http.setRequestProperty("Cookie", "flag=0");
                http.setInstanceFollowRedirects(true);
                http.setConnectTimeout(10000);
                http.setReadTimeout(10000);
                http.connect();

                Map<String, List<String>> reqMap = http.getHeaderFields();
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, List<String>> e : reqMap.entrySet()) {
                    for (String i : e.getValue()) {
                        if (e.getKey() != null && e.getKey().startsWith("Set-Cookie") && i.contains("SESSION")) {
                            sessionId = i.split(";")[0].trim();
                        }
                    }
                }

                http.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

Logo que o método é chamado, aciono o ProgressDialog até que o método retorne o resultado desejado.
Para que o usuário saiba que a função ainda está em funcionamento, parametrizei progress.setCanceledOnTouchOutside(false) para que feche somente após o retorno do método esperado, sem que o usuário feche o app ou saia da Activity por acidente.
O problema é que eventualmente, se o servidor está fora do ar, a aplicação congela no http.connect() e praticamente trava a aplicação, pois o ProgressDialog continua em funcionamento.
Como posso tratar esse erro para que quando o servidor estiver fora do ar, a AsyncTask pare, feche o ProgressDialog e assim avisar o usuário de que não foi possível completar a ação ou que a URL está fora do ar?
Comment: Quando da esse erro, cai no ```catch (IOException ex) {```?
Comment: Não.  Ele simplesmente congela.  Gostaria de pelo menos um método para testar a conexão com a URL e que depois de um determinado tempo, sem resposta do servidor, ele fosse para 'catch (IOException ex)'
Comment: Adicionei um código que pode te ajudar, da uma olhada na resposta
Answer: Rogério, você pode fazer dessa forma:
Adiciona mais um catch, que será responsável por observar o TimeOut, caso estoure o tempo sem resposta do servidor, irá cair nele, ai é só remover o ProgressDialog
try {
            HttpURLConnection http = getHttpUrlConnection("http://www.sitedoservidor.com.br");
            if (http != null) {
                http.setRequestProperty("Cookie", "flag=0");
                http.setInstanceFollowRedirects(true);
                http.setConnectTimeout(10000);
                http.setReadTimeout(10000);
                http.connect();

                Map<String, List<String>> reqMap = http.getHeaderFields();
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, List<String>> e : reqMap.entrySet()) {
                    for (String i : e.getValue()) {
                        if (e.getKey() != null && e.getKey().startsWith("Set-Cookie") && i.contains("SESSION")) {
                            sessionId = i.split(";")[0].trim();
                        }
                    }
                }

                http.disconnect();
            }
        }catch (SocketTimeoutException e) {
        //remove o loader aqui

        } catch (IOException ex) {
           ex.printStackTrace();
        }

O SocketTimeoutException deve vir antes do IOException
Comment: Muito obrigado Leonardo pela sugestão.  No momento a URL está funcionando perfeitamente e assim nao consigo testar.  Logo que tiver um resultado, postarei aqui.  Muito obrigado mais uma vez.


My code for solving a maze goes into an infinite loop

Question: Currently, I have a maze solving algorithm, and it goes into inifinite loop for some reason, I have been on it for hours, but I just can't seem to figure it out. Am I doing something wrong. I am going to post some of the other necessary functions that "could" be the poential problem along with my maze solving code.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mazegen.h"
#define  MAXSIZE 100

int main(int argc, char**argv)
{
    char*readFile;
    char maze[MAXSIZE][MAXSIZE];
    int rows=0;
    int cols=0;
    int x;
    int y;
    FILE*fp;
    int counter;
    int length=0;
    counter = 0;

    fp = fopen(argv[1], "r");

    if(fp == NULL)
    {
       printf("Cannot open file\n");
       exit(0);
    }

    readFile = malloc(sizeof(char)*MAXSIZE);

    while(fgets(readFile,MAXSIZE,fp) != NULL)
    {
        for(cols=0; cols <MAXSIZE; cols++)
        {
            maze[rows][cols] = readFile[cols];
        }
        rows++;

        counter++;
    }

    fclose(fp);

    length = strlen(readFile);

    mazeSolution(maze,counter, length);

    for(x=0; x<rows; x++)
    {
       for(y=0; y<cols; y++)
       {
            printf("%c", maze[x][y]);
       }
    }

   free(readFile);

   return 0;
}

mazeSolve.c
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define  BUFFERSIZE 500
#define  FLAG

void mazeSolution(char maze[100][100], int counter, int counter2)
{
   stack*currentCell;

   int i;
   int j;

   currentCell = create();

   /*push(currentCell, 1,2);
   push(currentCell, 3,4);
   pop(currentCell);
   printStack(currentCell);*/

   for(i=0; i<counter; i++)
   {
       for(j=0; j<counter2; j++)
       {
           if(maze[i][j] == 'S')
           {
               push(currentCell,i,j);
               i = counter;
               break;
          }
      }
   }

   while(currentCell != NULL)
   {
      if(maze[i][j] == 'F')
      {
           break;
      }

      if (maze[i][j] == ' ')
      {
          maze[i][j] = '.';
      }

      if (i>0 && maze[i-1][j] == ' ')
      {
          push(currentCell,i-1, j);
          i--;
      }
      else if (j>0 && maze[i][j-1] == ' ')
      {
          push(currentCell,i, j-1);
          j--;
      }
      else if (i+1<counter && maze[i+1][j] == ' ')
      {
          push(currentCell,i+1, j);
          i++;
       }
       else if (j+1<counter2 && maze[i][j+1] == ' ')
       {
          push(currentCell,i, j+1);
          j++;
       }
       else
       {
          pop(currentCell);
       }
   }

   if (listLength(currentCell->list) > 0)
   {
       printStack(currentCell);
   }
    else
    {
        printf("NO SOLUTION\n");
    }

}

stack.c
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>

stack*create()
{
    stack*myStack;

    myStack = malloc(sizeof(stack)+1);

    myStack->list = createList();

    return myStack;
}

node*push(stack*theStack, int xpos, int ypos)
{
   node*top;

   if(theStack == NULL)
   {
       printf("Empty Stack.Error\n");
       exit(0);
   }

   top = addFront(theStack->list, xpos, ypos);

   return top;
}

void pop (stack*theStack)
{
    node*theHead;

    if(theStack == NULL)
    {
        printf("Empty Stack. Error\n");
         exit(0);
    }

    theHead = removeFromFront(theStack->list);

    theStack->list = theHead;

}

void peek (stack*theStack)
{
    getFromFront(theStack->list);
}

void printStack(stack*theStack)
{
    if(theStack == NULL)
    {
        printf("Error Empty Stack. Cannot print stack\n");
        exit (1);
    }
    printList(theStack->list);

}
void destroyStack(stack*theStack)
{
    destroyList(theStack->list);

    free(theStack);

}
linkedList.c

#include "linkedList.h"
#include <stdio.h>
#include <stdlib.h>

node*createList()
{
    node*dummyNode;

    dummyNode = malloc(sizeof(node));

    dummyNode->next = NULL;

    return dummyNode;
}

node*addFront(node*list, int xpos, int ypos)
{
   node*newNode;

   if(list == NULL)
   {
       printf("Add to front Error\n");
       exit(0);
   }

   newNode = initNode(xpos, ypos);

   newNode->next = list->next;

   list->next = newNode;

   return list;
}

void printList(node*theList)
{
    node*currentPosition;

    currentPosition = theList->next;

    while(currentPosition != NULL)
    {
        printf("This is the value of the current node : %d,%d\n",currentPosition->xpos, currentPosition->ypos);

        currentPosition= currentPosition->next;
    }

}

node*initNode(int xpos, int ypos)
{
    node*newNode;

    newNode = malloc(sizeof(node));

    newNode->xpos = xpos;

    newNode->ypos = ypos;

    newNode->next = NULL;

    return newNode;

}

void destroyList(node*theList)
{
    node*temp;

    while(theList->next != NULL)
    {
        temp = theList->next;
        free(theList);
        theList=temp;
    }
}

node*removeFromFront(node*theList)
{
    node*temp;

    if (theList == NULL)
    {
        printf("Error\n");
        return NULL;
    }

    temp = theList->next;
    theList->next = NULL;

    return temp;
}

int listLength(node*list)
{
    int length;
    node*ptr;
    length = 0;

    ptr = list->next;

    while(ptr != NULL)
    {
        length++;
        ptr = ptr->next;
    }

    printf("This is the length of the list : %d\n",length);

    return length;
}

void getFromFront(node*theList)
{
    node*temp;

    int value1;

    int value2;

    temp = theList->next;

     if(temp == NULL)
     {
         printf("Empty List.\n");
         exit(0);

     }

    value1 = theList->next->xpos;

    value2 = theList->next->ypos;

    printf("This is the value from the front : %d,%d\n", value1, value2);

}

Answer: Looks like it may be several things: your while loops. Your while loops use the expression
while (<insert code> != null)
{
<insert body of code>
}

using the != null expression is tricky at times because unless the condition is true, it will continue going in an infinite loop. I noticed that in your code, you don't have any kind of exit statement in your while loops. In my experience while loops are the main causes of infinite loops. It doesn't seem that the condition will ever be false (= null). For example:
while(fgets(readFile,MAXSIZE,fp) != NULL)
{
    for(cols=0; cols <MAXSIZE; cols++)
    {
        maze[rows][cols] = readFile[cols];
    }
    rows++;

    counter++;
}

if the fgets method does not become null, you will never exit the while loop. You did not post the fgets method and so I'm afraid I can't say whether or not that's where your problem is located. The same concept is true for your second while loop.
A good strategy I often like to use when debugging infinite loops is having a System.out.println (I'm used to java haha), inside the while loop. Doing so allows me to see what the computer is doing inside the while loop.
Comment: Oh okay and I have never done java actually is system.out.println a printf statment within the while loop?? and I did post the fgets method did I not ? :S What do you suggest would be a good exit condition when dealing with while loops? one way would be to read till the end of file I guess instead of NULL
Comment: `System.out.println` is just printing out on the screen and yes, it would be inside your while loop. I'm sorry if I missed your fgets method, your code is on the longer side and I'm used to reading code in eclipse or BlueJ format, not SO's. As for while loops, generally honestly I try and avoid them. Instead of having something vague such as `!= null` try setting more specific conditions. This is why I find for loops to be a better option, they are more specific and don't tend to head into infinite loops as easily.
Comment: Well I tried something specific like while its not equal to an 'F' because that is the ending the position in our maze, however it does not seem to be work I might have to try putting a bunch of printf statements in the while loop like you said. Thank you for your help, I really appreciate it.


How to evaluate $\sqrt {6\sqrt {6\sqrt{\cdots}}}$

Question: I was playing mental maths in which we solve problems without pen and pencil.
Then I came across a problem
$$\sqrt {6 \sqrt{6 \sqrt{6\sqrt\cdots}}}.$$
I asked my teacher and he told me that the answer is $6$
I was amazed and asked how but didn't get satisfying reply.
Kindly tell me what was the reason behind my teacher's saying...
If this question is asked somewhere else, please send the link in comments
I am still amazed!!!!
Comment: This is not a full proof but if $x=\sqrt{6\sqrt{6\sqrt{6...}}}$ then $x = \sqrt{6x}$.
Comment: Worth checking this http://math.stackexchange.com/questions/115501/sqrtc-sqrtc-sqrtc-cdots-or-the-limit-of-the-sequence-x-n1-sq
Comment: I am not familiar with convergence of series...!!!!   Sorry
Comment: Assume the expression to be equal to x. Then square both sides.u will find a quadratic equation like x^2=6x and solve it......
Answer: Suppose that expression indeed defines a number, call it $x$:
$$x = \sqrt{6\sqrt{6\sqrt{6\sqrt{\cdots}}}}$$
Square both sides:
$$x^2 = 6\color{blue}{\sqrt{6\sqrt{6\sqrt{\cdots}}}}$$
Notice that the blue part is $x$ again, so:
$$x^2 = 6x$$
This equation has two solutions; but one of them is...

From the comment:

why $x \ne 0$ ?

Take a look at the sequence:
$$\sqrt{6}, \sqrt{6\sqrt{6}},\sqrt{6\sqrt{6\sqrt{6}}}, \ldots$$
This sequence is increasing with first term $\sqrt{6}>0$ so if this converges, it cannot converge to $0$.
To show this increasing sequence converges, you only need that it is bounded. Call the $n$-th term in the sequence above $x_n$ and observe that $x_1 = \sqrt{6} \le 6$. Now if $x_n \le 6$, then by induction also $x_{n+1} = \sqrt{6x_n} \le \sqrt{6 \cdot 6} = 6$. Thanks to Bungo for his comments.
You can also take a look at this similar question.
Comment: why $x \neq 0$ ???
Comment: Indeed; I added a reference concerning the boundedness.
Comment: I will add this; thank you for the suggestion.
Comment: (+1) Nice, complete answer which includes the convergence proof, without which the $x^2 = \sqrt{6x}$ is unjustified. I deleted my previous comments now that you have integrated them into your answer.
Comment: See addition in the answer.
Comment: But clearly It is visible that the equation is quadratic ,,, then why don't both roots are satisfying the equation??  Please make me understand
Answer: Another possible solution: just compute the geometric sum in the exponent.
$$x=6^{\frac{1}{2}+\frac{1}{4}+\frac{1}{8}...}=6$$
Could be done in your head if you wanted to.
Answer: It is important that you look for a possible recursion in these questions.
Suppose $x=\sqrt{6\sqrt{6\sqrt{6\sqrt{6\ldots}}}}$. Then, see that $x = \sqrt{6x}$ (Can you see why? Basically, what was happening outside the radical is now happening inside the radical).
Now, square it so that $x^2 = 6x$ hence $x=6$ or $x=0$.
To show that $x \neq 0$, do the following: define $x_1 = \sqrt{6}$, and let $x_{n+1} = \sqrt{6x_n}$. By induction prove ,that $x_n$ is an increasing strictly positive sequence. Then prove that $x = \lim x_n$, hence $x$ also must be positive, hence can't be zero.
As another example, you can consider $x= \frac{1}{1+\frac{1}{1+\frac{1}{1+\ldots}}}$. This also can be rewritten recursively, to give $x = \frac{1}{1+x}$, which when solved gives $x = \frac {\sqrt 5 - 1}2$. Hence,
$$
\frac {\sqrt 5 - 1}2 = \frac{1}{1+\frac{1}{1+\frac{1}{1+\ldots}}}
$$
There are many more of these marvels. Try to create some on your own.
Comment: The "!" in _Then, see that $x = \sqrt{6x}$!_ could be confusing (+1).
Comment: @NiklasHebestreit removed. Thank you.
Answer: Hint Consider the function $f(x)=\sqrt{6x}$ and evaluate the limit of the sequence given by the recurrence
$$x_1=1,\quad x_{n+1}=f(x_n),\quad\mbox{for $n\geq 1$}$$
Show that $x_n$ is increasing and bounded and it tends to $L$ where $f(L)=L$.
Answer: assume that $\sqrt {6 \sqrt{6 \sqrt{6\sqrt....}}}=x$
$x^2=6\times \sqrt {6 \sqrt{6 \sqrt{6\sqrt....}}}$
$x^2=6\times x$
$x=6$  Or   $x=0$.
But Notice that $x=\sqrt{6}\times \sqrt{6}^{1/2}\times\sqrt{6}^{1/4}......$
$x=\sqrt{6}^{{1+\frac{1}{2}+\frac{1}{4}+\frac{1}{8}...}}$.The series on the  right is never gonna converge to zero. I shall let you conclude now.
Comment: Here x could also be 0,, why it is not??
Answer: The first embedded infinite radical is identical to the whole thing. Supposing that the whole thing is $6$, the nested infinite radical is also $6$. When we multiply this by the leftmost $6$, we get $\sqrt{36}$, which is $6$, meaning it holds.
Answer: If you start with $$x = \sqrt{6\sqrt{6\sqrt{6\cdots}}}$$ with an infinite number of terms then $$x=\sqrt{6x}$$   which you can solve.  Depending on how you do it, perhaps by squaring both sides, this could give two potential solutions and you need to satisfy youself about which, if any, is correct.


Interpretation of y-axis in impulse response function graphs for VAR models

Question: I read different papers which try to analyse the relationship between oil and macroeconomics with the help of a VAR model. The results are explained in graphics which show the impulse response functions. The question is now how to interpret the Y-axis. There is no graphic with an description of the Y-axis. I read in a learning book that it is in some cases only "how strong is the dependence of the variables " but in other cases it is the percentage of change in the variables. As example: 0.5 in period 1 = 0,5% change in variable x in period one / or only positive relationship.
Comment: Right now the question is a bit unclear and thus hard to answer. Do you have an example of such a graph and can you show us the model specification?
Comment: Yes sure.
http://www.pic-upload.de/view-27157416/HELP.png.html

Here are three examples. My opinion is, that number one and two only have got the statement if there is a positiv or negativ relationship. Number three could be interpret as percentage changes in the values.
Comment: As example in number one: oil supply shock /oil quantity: is there an 1% depreciation in oil quanity? or is there only a niegative relationship?
Answer: The vertical axis is expressed in units of the $Y$ variable. The solid line is a point estimate for the amount $Y$ is expected to change following a unit impulse after the number of periods on the horizontal axis.
Look at the top left graph, of Oil Quantity vs Oil Supply Shock. Using the point estimate (the solid line), a one-unit Oil Supply Shock (whatever the units are) is expected to lead to a change in Oil Quantity of -0.5 units after 10 periods
Comment: Maybe I should write that before. In all of these VAR Modells the x-axis is the periods, in the case of picture one in month. And what are the Units? And is it every new Period again the amount of units?
Comment: And when you look at picture two: it is the respond of stockindex to oil shocks. why there is only a .002 percent or unit shock? the author discribes the reactions as significant positiv or negativ. so i think its only expression of how much positive ( very positive , small positive etc.)not how much percent.
Comment: @Mark if the horizontal axis is in periods, then it's the effect of a one unit impulse after that many periods. I edited my post
Comment: I don't know what you're trying to say here. It's possible that "significant" means "significantly different from zero based on the confidence interval" but without seeing the quote from the paper it's hard to say.
Comment: As for _why_ it's only 0.002%? That's what the model predicts. I don't think you're saying what you mean to be saying
Comment: Is it possible, that .002 stands for 0.2% ? Why do you think its Units and not %? When you have got Athens Log In here is the full paper: http://www.sciencedirect.com/science/article/pii/S0140988313002429
it is figure 2
Comment: Ans is it a change of -0,5 Units per period or to pale in comparison to the start Value without the shock?


Dúvida específica usando ng-repeat no angular

Question: Estou usando AngularJS em um projeto onde preciso exibir uma lista de fotos de produtos cadastrados no sistema e meu html está assim:
// Titulo para a área de produtos

Produtos

// Ng-repeat para listar os produtos, somente serão exibidos produtos com foto

porém a div header-products só deve ser exibida se pelo menos um produtos da minha lista tiver foto, se não tiver nenhuma foto não exibo este header. Na lista sempre terá o nome do produtos mas pode s er que nao tenha a foto:
[
 {produto: 'lapis', imageUrl: 'url-da-imagem'},
 {produto: 'caneta', imageUrl: 'url-da-imagem'},
 {produto: 'borracha', imageUrl: ''}
]

Como posso fazer isso se meu header esta fora do ng-repeat?
Comment: Olá Felipe, você já tentou utilizar o ng-if? Algo como:
Answer: Coloque a diretiva ng-show perguntando se a lista de products é maior do que zero, exemplo:

 0" class="header-products">

Produtos

Abaixo um exemplo funcional, onde a div com o titulo Produtos vai aparecer, enquanto que a div com o titulo Alimentos não, porque, products tem elementos para apresentar e aliments não.

var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
  $scope.products = [{
      'id': 1,
      'name': 'name1'
    },
    {
      'id': 2,
      'name': 'name2'
    },
  ];
  $scope.aliments = [];
});

 0" class="header-products">

Produtos

 0" class="header-products">

Alimentos

Com a nova edição da pergunta tinha um item que não foi mencionado que só aparece a header se alguns dos itens de products contiver foto, então faça uma função que vai percorrer essa lista e buscar o primeiro item com imagem, exemplo:

var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
  $scope.products = [{
      produto: 'lapis',
      imageUrl: ''
    },
    {
      produto: 'caneta',
      imageUrl: ''
    },
    {
      produto: 'borracha',
      imageUrl: 'a'
    }
  ]
  $scope.showItem = function() {
    var sts = false;
    for (i = 0; i < $scope.products.length; i++) {
      if ($scope.products[i].imageUrl !== '') {
        sts = true;
        break;
      }
    }
    return sts;
  }
});

Produtos

Referencia

ngShow
AngularJS - Entendendo as diretivas ng-show e ng-hide
Comment: Tem um detalhe que acabei não explicando. Minha lista é assim:
[
{produto: 'lapis', imageUrl: 'url-da-imagem'},
{produto: 'caneta', imageUrl: 'url-da-imagem'},
{produto: 'borracha', imageUrl: 'url-da-imagem'}
]

Porém pode ser que só um ou dois produtos tenham foto. Para exibir o titulo preciso verificar se pelo menos um dos  itens tem foto senão não exibo nada.
Comment: @FelipeCoelho mas, isso não muda nada na resposta veja, que até coloque dois exemplos, mas, diga ai o que aconteceu? se não deu certo, é melhor você editar a sua pergunta e colocar tudo que precisa.!
Comment: Editei a perguntando. Valeu
Comment: @FelipeCoelho editado a resposta


For which real $k$ do we have $k^nA^n\to0$?

Question: I do not understand how to obtain the set of values for k. Here is the question:

Determine the set of values of the real constant k such that $k^nA^n$ tends to the zero matrix as n $\rightarrow$ $\infty$.

From the previous section of the question, I have obtained the invertible matrix P and diagonal matrix D. They are
P =$\begin{pmatrix} -17&-1&1\\ 6&2&0\\ 7&-1&1\end{pmatrix}$ and D =$\begin{pmatrix} 1&0&0\\ 0&5^n&0\\ 0&0&7^n\end{pmatrix}$
I understand that $k^nA^n = P\begin{pmatrix} k^n&0&0\\ 0&k^n5^n&0\\ 0&0&k^n7^n\end{pmatrix} P^{-1}$ but I do not know how to continue. Please help.
Comment: If $k$ is, say, $1/2$, does $k^n7^n$ converge to zero?
Comment: Good! Let me encourage you to write up a solution, and to post it as an answer.
Comment: So, for what values of $k$ do the sequences $k^n$, $k^n5^n$, and $k^n7^n$ all converge to zero?
Comment: hmm I got -1 < k < 1? but from the answer sheet, its $\frac{-1}{7}$ < k < $\frac{1}{7}$. I don't understand why. Can someone please explain to me why?
Comment: Oh, yes I get it now. Thanks a lot!
Answer: For $k^nA^n$ to converge to the zero matrix, $k^n, k^n5^n$ and $k^n7^n$ must all converge to zero.
For $k^n, k^n5^n$ and $k^n7^n$ to converge to zero when n $\rightarrow\infty$ , the value of k, 5k and 7k must be between -1 and 1. Since 7 is the greatest number in the diagonal matrix, the maximum value of k will correspond to that number.
Therefore, $$-1 < 7k < 1$$
$$\frac{-1}{7} < k < \frac{1}{7}$$


how to set up the cron job on WHM server?

Question: I am trying to set up a cron job on let's say example.com So, what I have php script right in public_html directory called cron_job.php I can run it easily right of the browser and I am sure it works.
But when I go to control panel on example.com then to cron jobs. I set up timing and path as following, but when time comes it does not work:
<code>/usr/bin/php -f /home/vmax/public_html/cron_job.php
</code>
Comment: Please post the error message.
Comment: I does not show any errors, the code works just fine if I just run it from the browser. But when time comes for it as set in "cron jobs", it just does not get launched.
Comment: Ok. What OS are you using?
Comment: it is Linux based server
Comment: What does the cron job line look like? E.g. "54 9 2 7 3
Comment: I am using "putty" to access it, so I do "crontab -l" to look it up and it says: 10 9 * * 1-5 /usr/bin/php -f /home/stahlinl/public_html/cron_autolead.php
Comment: try running `/usr/bin/php -f /home/vmax/public_html/cron_job.php` command through putty and see whether it is working or not.
Answer: Can you please try with following.
<code> /usr/bin/php -q /home/vmax/public_html/cron_job.php
</code>


Get a free seat (randomizing?)

Question: i have a global variables which handles if users standing on "items" (on seats) or just standing on the seat. Therefore i have 2 global variables as mentored.
<code> $users[$someUserID]['seat']     <----
</code>
and this:
<code>  $standing[$someSeatID]['seat'] <----
</code>
which handles if user is standing on a seat.
Now i will make a function that gives me a random seat which is free and not taken by other users. How can i make this?
<code>$random = mt_rand(0, 97);
</code>
But how can i check if it's also free in
<code> $users[id..]['seat']
</code>
and
<code> $standing[seat..]['seat']?
</code>
Comment: What is the reason you are using global variables to store this information?
Answer: You could try building an array of unused seat IDs and then retrieve a random array index from this array.
Note that if the datatype of the seat is fairly large (and not, for example, an integer) and you have thousands of these, this could cause performance issues and you might need to simplify the seat representation to avoid this.

Get a free seat (randomizing?)


Submit package to packagist.org

Question: I'm trying to submit a module to packagist.org so that it can be directly installed via composer. I've followed the necessary steps and created the composer.json as required. Now when I'm trying to submit the module to packagist.org its giving me the following error:

The vendor is already taken by someone else. You may ask them to add
  your package and give you maintainership access. If they add you as a
  maintainer on any package in that vendor namespace, you will then be
  able to add new packages in that namespace. The packages already in
  that vendor namespace can be found at drupal
Answer: You should not put your Drupal modules on packagist.org. Drupal modules are available on packages.drupal.org, where the module will be automatically exposed if you add it on Drupal.org.
it is explained here:
Using packages.drupal.org.

Submit package to packagist.org


How do I learn proper breathing when teaching myself the flute?

Question: I have slowly, over time, begun to teach myself the flute. I play the piano and the recorder (sort of), so learning the note positions and how to read music is not a big issue for me. The biggest difficulty I am facing is how to learn to breathe correctly. I can produce sound- and it sounds pretty- but I'm pretty sure that I'm breathing incorrectly (I don't make the "pph" sound when I breathe) and I'm worried my incorrect technique will hamper my skills when I get to a more advanced level.
So, what is the best way to teach myself how to breathe correctly while playing the flute?
Thank you for your help!
Comment: Once you learn how to breathe properly, this sheet of exercises is useful for developing your breathing skills!                                                  http://www.co-bw.com/Health%20PDF/Health_breathing_exercises_for_winds.pdf
Comment: What's the "pph" sound?
Comment: Do they refer to tonguing or similar, rather than just blowing?
Answer: You're right to be aware of your breathing, it really is the core of flute playing and so much depends on it.
Firstly, I wouldn't worry too much about the sound. Most people would agree it is preferable to not make a sound whilst breathing, simply because it sounds nicer.
The thing I would encourage you to check is that you are "tummy breathing". Place your palm over your belly button and breath in. Hopefully you find your hand moves away from you. And hopefully your shoulders aren't be moving when you breath.
If you find that doesn't happen, you need to make it do so! This means breathing deeper. I struggled to do this, without thinking very hard about it! I sorted it out by just placing my hand on my belly, and breathing in and out, say fifteen times, and repeating this exercise while out and about.
Answer: I agree with @fluteflute, tummy breathing is very important.  Another way that I learned to hear yourself breathing, if you feel better knowing that there is a sound, is to put your hand against the middle of your mouth, so the side of one finger is at the middle of your lips pointing to your nose.  When you breathe in, you'll hear the sound.
Also, if you bend at your hips at a 90 degree angle, your body automatically breathes "properly", so doing that will help you get a good feel for it.
I hope this helps.
Answer: Look at what singers say about breath support -- same thing for flute.  You need to balance tension in the muscles in your abdomen used for expiration with that in those used for inspiration, to get more control of just how fast the air is moving up through your mouth (since that has to change going from one note to another and going from soft to loud).  Here is a good discussion:
http://www.starmountpres.org/sva-breath-support/


View should use certain textboxes and models on certain button clicks, how to do that?

Question: So what I want, if a user clicks one of the two buttons only certain textboxes should be used. At the moment the check I do for SafeForLater is always false and does not work this way. So I would be thankful if someone has a hint oder advice how to use certain textboxes only then when a certain button got hit and bind the data to my model.
@model ProblemExample.Models.ViewModelOrder

@{
    ViewBag.Title = "Create Order";
}

CreateOrder

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @if (TempData["CallFrom"] != null && Convert.ToString(TempData["CallFrom"]) == "SenditNow")
        {
            @Html.TextBoxFor(m => m.viewModelSenditNow.NameOfCustomer)
            @Html.TextBoxFor(m => m.viewModelSenditNow.Address)
        }

        else
        {
            @Html.TextBoxFor(m => m.viewModelSafeForLater.NameOfCustomer)
            @Html.TextBoxFor(m => m.viewModelSafeForLater.Address)
        }

        <button class="formular-button-submit" type="submit" name="SenditNow" value="SenditNow">Send it now!</button>
        <button class="formular-button-submit" type="submit" name="submit" id="SafeForLater" value="SafeForLater">Save it for later!</button>

}

ViewModel from View:
public class ViewModelOrder
    {
        public ViewModelSendItNow viewModelSenditNow { get; set; }
        public ViewModelSafeForLater viewModelSafeForLater { get; set; }
    }

ViewModel SendItnow:
public class ViewModelSendItNow
    {
        [Required]
        public string NameOfCustomer { get; set; }
        [Required]
        public string Address { get; set; }
    }

ViewModel SaveForLater:
public class ViewModelSafeForLater
    {
        public string NameOfCustomer { get; set; }
        public string Address { get; set; }
    }

Controller:
public ActionResult CreateOrder()
        {
            ViewModelOrder viewModel = new ViewModelOrder();
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult CreateOrder(ViewModelOrder viewModel, string submit)
        {
            TempData["CallFrom"] = submit;

            if(submit == "SendItNow")
            {
                Order myOrder = new Order()
                {
                    NameOfCustomer = viewModel.viewModelSenditNow.NameOfCustomer,
                    Address = viewModel.viewModelSenditNow.Address,
                    State = 1
                };
                db.Orders.Add(myOrder);
                db.SaveChanges();
            }

            else
            {
                Order myOrder = new Order()
                {
                    NameOfCustomer = viewModel.viewModelSafeForLater.NameOfCustomer,
                    Address = viewModel.viewModelSafeForLater.Address,
                    State = 999
                };
                db.Orders.Add(myOrder);
                db.SaveChanges();
            }
            return View(viewModel);
        }

Comment: Do the models have to be separate? Can't your view model just have a single Name and Address and then the controller decides what to do with them? If you do that, you only have to distinguish the button which was pressed which you can do like Sandip says or otherwise you can create two forms, which allows you to post directly to 2 different actions.
Comment: Thanks for your comment. I will try to explain to you why Im using two models. The reason for that is, I want to use the client-side validation through the [Requirement]-Attribute in the ViewModel. So in case the user decides to send his order now, hes data is completely validated. I hope the reason now is clear, but if you have a new idea how this could be solved, im very interested in it, because Im still learning a lot in ASP.NET MVC :)
Answer: You can set value in Tempdata on button click from controller and check that Tempdata value instead of Request.Form value.
Controller:
public ActionResult Save(string submit)
{
     TempData["CallFrom"] = submit;
     return RedirectToAction("Index");
}

View:
@using (Html.BeginForm("Save","Home"))
{

        @if (TempData["CallFrom"] != null && Convert.ToString(TempData["CallFrom"]) == "SenditNow")
        {

SenditNow

            <input type="text" value="NameOfCustomer" />
            <input type="text" value="Address" />
        }

        else
        {

SafeForLater

            <input type="text" value="NameOfCustomer" />
            <input type="text" value="Address" />
        }

        <button class="formular-button-submit" type="submit" name="submit" id="SenditNow" value="SenditNow">Send it now!</button>
        <button class="formular-button-submit" type="submit" name="submit" id="SafeForLater" value="SafeForLater">Safe it for later!</button>

}

Note: in your controller get the value of submit. Only the button clicked will pass its value
Comment: Thanks for your answer, do you have a small snippet how you would do that?
Comment: Thanks a lot for you explaining it and creating this code-snippet, it solved my problem completely and im very thankful for your help! :)
Comment: Its me again, I got one last problem, how do I check in my controller which button got hit? I tried it with the following statement: if(TempData["CallFrom"] != null && Convert.ToString(TempData["CallFrom"]) == "SenditNow") but that did not work. Do you have a tip for me?
Comment: I have already mention in "Note" , what ever pass in "value" you got in controller, better you put all my answer code , so you have better idea
Comment: I will do that as soon, as my problem is solved, thats no problem for me :)
Above I added the code of my controller, because I got the problem the program always jump in the else part, but not in the if part as it should, so maybe this helps to figure my problem out.
Comment: please add value attribute in button :
Comment: Thanks for all of your effort, I did it like you said, but it still jumps only in the else part. I updated my sourcecode above so you can exactly see how the code in view and controller is.
Comment: change your button to : Send it now!
Comment: So, now everything is updated and like you suggested, but still it wont jump in the right part. I added a state property to say if its right part set 1 if it is the else part add 999 as control, and its always 999.


PHP file names appending in URL during header() call

Question: I have a button on profile_page.php called Send Message:
<form method='post'>
   <input type='submit' class='btn btn-info' name='sendmsg' value='Send Message'/>
</form>

And I have the following, simple piece of code which on click the Send Message button, should take them to messages.php/$user - $user being their username:
if (isset($_POST['sendmsg'])){
    header("Location: messages.php?u=$user");
    }

Now, when I click Send Message the URL reads
http://localhost/profile_page/messages.php?u=freddy

Why is messages.php appending to profile_page.php?
Answer: That is what header() function does. If you want to redirect the user to a more specific route, you should use / in the beginning of the location to specify more. For example header("Location: /messages.php?u=$user"); will lead to http://localhost/messages.php?u=freddy
Comment: actually you should provide the full URI in accordance with the specs
Comment: Thank you. A very educating answer.


How can I join these MYSQL tables?

Question: I'm having 2 tables. Table A contains a list of people who booked for an event, table B has a list of people the booker from table A brings with him/her. Both tables have many colums with unique data that I need to do certain calculations on in PHP , and as of now I do so by doing queries on the tables with a recursive PHP function to resolve it. I want to simplify the PHP and reduce the amount of queries that come from this recursive function by doing better MYSQL queries but I'm kind of stuck.
Because the table has way to many columns I will give an Excerpt of table A instead:
booking_id | A_customer | A_insurance
1          | 134        | 4

Excerpt of table B:
id | booking_id | B_insurance
1  | 1          | 0
2  | 1          | 1
3  | 1          | 1
4  | 1          | 3

The booking_id in table A is unique and set to auto increment, the booking_id in table b can occur many times (depending on how many guests the client from table A brings with him). Lets say I want to know every selected insurance from customer 134 and his guests, then I want the output like this:
booking_id | insurance
1          | 4
1          | 0
1          | 1
1          | 1
1          | 3

I have tried a couple of joins and this is the closest I've came yet, unfortunately this fails to show the row from A and only shows the matching rows in B.
SELECT a.booking_id,a.A_customer,a.A_insurance,b.booking_id,b.insurance FROM b INNER JOIN a ON (b.booking_id = a.booking_id) WHERE a.booking_id = 134

Can someone point me into the right direction ?
Please note: I have altered the table and column names for stackoverflow so it's easy for you guys to read, so it's possible that there is a typo that would break the query in it right now.
Answer: I think you need a union all for this:
select a.booking_id, a.insurance
from a
where a.a_customer = 134
union all
select b.booking_id, b.insurance
from a join
     b
     on a.booking_id = b.booking_id
where a.a_customer = 134;

Answer: The simplest way I can think of to achieve this is to use a UNION:
SELECT booking_id, A_insurance insurance
FROM A
WHERE booking_id = 134

UNION

SELECT booking_id, B_insurance insurance
FROM B
WHERE booking_id = 134

Comment: It is, except for that I apperently needed UNION ALL to get the duplicate records on my primary key !
Answer: As my understanging of your isso is right, that should give you the result you need:
 SELECT a.booking_id,a.insurance FROM a WHERE a.booking_id = 134
union
 SELECT a.booking_id,b.insurance FROM b INNER JOIN a ON (b.booking_id = a.booking_id) WHERE a.booking_id = 134

How can I join these MYSQL tables?


Is there a tool that can check for null reference exceptions?

Question: Is there a tool available that can scan code and check for possible null reference exceptions, i.e. where there is no code to check for null before calling a method / accessing a property?
Answer: ReSharper can do this.
Answer: Resharper will offer suggestions for when you might have accessed a member on an object that could be null.
In 4.0, "code-contracts" support this at compile time - for example, it will stop you passing a possible-null into a method that states it doesn't want one.
Answer: resharper is checking
Answer: RedGate has a commercial tool called Exception Hunter that can analyse your (compiled) code and show which exceptions can be thrown from an given function. You can also find all methods that throw a particular exception.
Answer: Perhaps you may be interested in the new contracts goodies in .NET 4.0?


What is the intuitive meaning of having a linear relationship between the logs of two variables?

Question: I have two variables which don't show much correlation when plotted against each other as is, but a very clear linear relationship when I plot the logs of each variable agains the other.
So I would end up with a model of the type:
$$\log(Y) = a \log(X) + b$$ , which is great mathematically but doesn't seem to have the explanatory value of a regular linear model.
How can I interpret such a model?
Comment: I've nothing substantial to add to the existing answers, but a logarithm in the outcome and the predictor is an elasticity. Searches for that term should find some good resources for interpreting that relationship, which is not very intuitive.
Comment: The complementary log-log link is an ideal GLM specification when the outcome is binary (risk model) and the exposure is cumulative, such as number of sexual partners vs. HIV infection. https://www.jstor.org/stable/2532454
Comment: @Alexis you can see the sticky points if you overlay the curves. Try `curve(exp(-exp(x)), from=-5, to=5)` vs `curve(plogis(x), from=-5, to=5)`. The concavity accelerates. If the risk of event from a single encounter was $p$, then the risk after the second event should be $1-(1-p)^2$ and so on, that's a probabilistic shape logit won't capture. High high exposures would skew logistic regression results more dramatically (falsely according to the prior probability rule). Some simulation would show you this.
Comment: @AdamO There's probably a pedagogical paper to be written incorporating such a simulation which motivates how to chose a particular dichotomous outcome link out of the three, including situations where it does and does not make a difference.
Comment: The interpretation of a log-log model, where the dependent variable is log(y) and the independent variable is log(x), is: $\%Δ=β_1\%Δx$.
Comment: Thank you @AdamO ! Do you know if there are any circumstances where logit, probit, or complementary log-log links give substantively different results, either in point estimates, or in standard errors? As the authors you cited wrote "Since the logit of *P* closely approximates the complementary log-
log of *P* over a wide range, such an analysis is likely to lead to qualitatively similar results to the methods described here," I wonder if there's a *strong* reason to prefer any in given circumstances? I know that the econometricians like probit links as natural for things like elasticities.
Answer: You just need to take exponential of both sides of the equation and you will get a potential relation, that may make sense for some data.
$$\log(Y) = a\log(X) + b$$
$$\exp(\log(Y)) = \exp(a \log(X) + b)$$
$$Y = e^b\cdot X^a$$
And since $e^b$ is just a parameter that can take any positive value, this model is equivalent to:
$$Y=c \cdot X^a$$
It should be noted that model expression should include the error term, and these change of variables has interesting effects on it:
$$\log(Y) = a \log(X) + b + \epsilon$$
$$Y = e^b\cdot X^a\cdot \exp(\epsilon)$$
That is, your model with a additive errors abiding to the conditions for OLS (normally distributed errors with constant variance) is equivalent to a potential model with multiplicative errors whose logaritm follows a normal distribution with constant variance.
Comment: OP may be interested to know that this distribution has a name, the log-normal: https://en.wikipedia.org/wiki/Log-normal_distribution
Comment: What about the effect of Jensen's inequality? Generally for convex g, $E[g(X)]≥g(E[X])$
Answer: You can take your model $\log(Y)=a\log(X)+b$ and calculate the total differential, you will end up with something like :
$$\frac{1}YdY=a\frac{1}XdX$$
which yields to
$$\frac{dY}{dX}\frac{X}{Y}=a$$
Hence one simple interpretation of the coefficient $a$ will be the percent change in $Y$ for a percent change in $X$.
This implies furthermore that the variable $Y$ growths at a constant fraction ($a$) of the growth rate of $X$.
Comment: @DimitriyV.Masterov Ok, then since the $\log(Y)$ is linear in $\log(X)$ it means that the variable $Y$ grows at a constant fraction of the growth rate of $X$. Is there something wrong with my answer according to you?
Comment: So if the log-log plot is linear, that would imply a constant growth rate?
Comment: Not actually, the growth rate of $Y$ will be constant if and only if $a=0$.
Comment: Not over time, the growth rate with respect to the growth in x.
Comment: reordering doesn't help, i'd remove it
Comment: @RScrlli I like your answer very much, and +1ed already. I just wanted to emphasize what linearity means in the log-log setting.
Comment: I see,@DimitriyV.Masterov I was struggling to find out what was wrong, since it is obvious you already knew the answer :-)
Answer: Intuitively $\log$ gives us the order of magnitude of a variable, so we can view the relationship as the orders of magnitudes of the two variables are linearly related. For example, increasing the predictor by one order of magnitude may be associated with an increase of three orders of magnitude of the response.
When plotting using a log-log plot we hope to see a linear relationship.
Using an example from this question, we can check the linear model assumptions:
Comment: +1 for an intuitive answer to an unintuitive concept. However, the image you have included clearly violates constant error variance across the predictor.
Comment: The answer is right, but authorship attribution is wrong. The image shouldn't be attributed to Google Images but, at least, to the web page where it is to be found, that can be find out just by clicking in Google images.
Comment: @Pere I cannot find the original source of the image unfortunately (at least using reverse image search)
Comment: It seems to come originally from http://diagramss.us/ though that site is down and most of its pages are not in the Web Archive apart from [its homepage](http://web.archive.org/web/20171118204828/http://diagramss.us/)
Answer: Reconciling the answer by @Rscrill with actual discrete data, consider
$$\log(Y_t) = a\log(X_t) + b,\;\;\; \log(Y_{t-1}) = a\log(X_{t-1}) + b$$
$$\implies \log(Y_t) - \log(Y_{t-1}) = a\left[\log(X_t)-\log(X_{t-1})\right]$$
But
$$\log(Y_t) - \log(Y_{t-1}) = \log\left(\frac{Y_t}{Y_{t-1}}\right) \equiv \log\left(\frac{Y_{t-1}+\Delta Y_t}{Y_{t-1}}\right) = \log\left(1+\frac{\Delta Y_t}{Y_{t-1}}\right)$$
$\frac{\Delta Y_t}{Y_{t-1}}$ is the percentage change of $Y$ between periods $t-1$ and $t$, or the growth rate of $Y_t$, say $g_{Y_{t}}$. When it is smaller than $0.1$, we have that an acceptable approximation is
$$\log\left(1+\frac{\Delta Y_t}{Y_{t-1}}\right) \approx \frac{\Delta Y_t}{Y_{t-1}}=g_{Y_{t}}$$
Therefore we get
$$g_{Y_{t}}\approx ag_{X_{t}}$$
which validates in empirical studies the theoretical treatment of @Rscrill.
Comment: This is probably what a mathematician would call *intuitive* :)
Answer: A linear relationship between the logs is equivalent to a power law dependence:
$$Y \sim X^\alpha$$
In physics such behavior means that the system is scale free or scale invariant. As an example, if $X$ is distance or time this means that the dependence on $X$ cannot be characterized by a characteristic length or time scale (as opposed to exponential decays). As a result, such a system exhibits a long-range dependence of the $Y$ on $X$.


If two matrices commute with a nonscalar matrix resp., they commute with each other

Question: Let $A \in M_2(\mathbb C)$ be an arbitrary matrix which is not scalar. (In what follows the matrices are elements of $M_2(\mathbb C)$.) Then let $X := \{B \mid AB = BA\}$.  Here I would like to show that if $S,T\in X$, $ST = TS$.
I figured out that the condition that $A$ is not scalar is equivalent to saying that $X$ is properly contained in $M_2(\mathbb C)$, and that $X$ is closed under multiplication, but I  cannot go any further.
I would appreciate for your help.
Comment: If  $A$ has two distinct eigenvalues, it is diagonalizable: then you can show that any $B$ commuting with $A$ is diagonalizable in the same basis, and the result follows. So it only remains to consider the case of a nontrivial Jordan block, whose cummutant is not difficult to determine.
Comment: Precision: if $A$ has two distinct  eigenvalues, it is diagonalizable with one dimensional eigenspaces. If $B$ commutes with $A$, it leaves these eigenspaces invariant and so it must be diagonal in a diagonalization basis of $A$. Of course, this is not true if $A$ is just diagonalizable in general.
Comment: Is it well-known that any B commuting with A is diagonalizable in the same basis?
Answer: I'd like to post the solution Julien indicated, in detail:
$2\times 2$ matrices are either:

diagonalizable with repeated eigenvalues (scalar)
diagonalizable with different eigenvalues, or
non-diagonalizable, i.e. similar to

$$\left ( \begin {matrix} \lambda &1\\0 &\lambda \end {matrix} \right ). $$
The question deletes case #1. For case #2, if a $2\times 2$ matrix is diagonalizable with non-repeated eigenvalues, it has a spectral decomposition
$$A = \lambda_1 P_1 + \lambda_2 P_2, \text { for } P_1 + P_2 = I \text { a resolution of identity}.$$
If $B$ commutes with $A$, then it commutes with each projection $P_i$; therefore, $B$ preserves the one-dimensional spaces $\operatorname{range}{P_i}$. Therefore these are eigenspaces for $B$. So $B$ is diagonalizable with respect to the same basis as $A$. This relation is clearly transitive, and the problem is solved in case #2.
For case #3, $A$ is similar to $\lambda I + N$, for $N$ a $2\times 2$ nilpotent Jordan block. If $PAP^{-1}=\lambda I + N$, denote by $B'$ the matrix $PBP^{-1}$. Since $\lambda I$ commutes with everything, a matrix $B'$ commutes with $\lambda I + N$ iff it commutes with $N$. It can be shown that the only matrices which commute with $N$ are polynomials in $N$, i.e. of the form $a_0I + a_1N$ (these are the only polynomials since $N^2 =0$).
So if $B_1$ and $B_2$ commute with $A$, then $PB_1P^{-1}$ and $PB_1P^{-1}$ are both polynomials in $N$, and so they commute with each other. So $B_1$ and $B_2$ commute with each other, ending case #3.


Can I share buckets in Amazon S3 so that multiple users see them in their management console?

Question: Using account A, I can add user B to the permissions of a bucket, but that bucket does not then show up in user B's management console.

What does it mean to give a user permissions in this way?
Is it possible for 2 users to truly have the same access to a bucket, so that it shows up in both consoles?
Answer:
Buckets are fully private by default so basically you allow their AWS account the [selected] permissions to your bucket.
Nope. But I think this feature is coming soon. If you notice the bucket properties it has a line for who the owner is :)

Other tools have what's called an "External Bucket" feature to add other user's buckets they have permission for.
If the S3 console is important enough, see if the newly released "AWS Identity and Access Management" feature can get the job done:
http://aws.amazon.com/iam/


Change color of external ViewController

Question: I have a viewController and a containerView in it. Unfortunately, I am unable to change the color of the child viewController represented in the containerView from the parent class. Changing the background color of the containerView, which is the only thing I am able to reach from my parent viewController, does not change the background color of the referenced child, but only the invisible containerView holding it.
Therefore, I have tested a method where I call a function from within the class of the child from the parent as shown below:
@IBAction func changeToRed(sender: viewController) {
    self.view.backgroundColor = UIColor(red: 230/255, green: 80/255, blue: 30/255, alpha: 1.0)
}

This is in the child viewController
otherView().changeToRed(sender: self)

This in the parent viewController
This technique does not work. I have already tried it with a regular function and with random trial and error in the parent viewController. Is there anything obvious I am doing wrong? Or is there a potentially different technique to do this? Thank you in advance!
Comment: what is otherView ?
Comment: That is just some name I used for this example which references the class of the child view.
Comment: Could you specify the various *view controllers* **and** *views*? It's easy to confuse what is a view versus controller. Two lines of code don't cut it. If you can't do that - then please define your view controller **hierarchy** along with the view **hierarchy** so we can duplicate your issue. Thanks.
Comment: I have one viewController (actually more, but they are irrelevant in this case). In this viewController, I have, in the storyboard, put a UIView which I have called a containerView in my question. This UIView obviously has an embedded segue linked to the view in which I want to change the background color from the viewController. Obviously, I have created an IBOutlet to the view, yet this when doing UIView.backgroundcolor does not affect the visible background.
Comment: For those who are downvoting this question, I would enjoy a helpful working solution. If you cannot supply a proper answer, do not take your time to downvote a valid question. Else, please suggest what I need to improve in my asking of questions.
Answer: If you have set up the container with Storyboard and segue, then you can get the child view controller like this. You put this in your parent view controller, where you also declare the childViewController.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    childViewController = segue.destination
}

Comment: As specified in my question, I do not declare the childViewController. It is simply an IBOutlet, which is therefore already predefined. I have tried possibly redefining this value but that should render useless as my doing this manually in the storyboard automatically creates the link to the ContainerView destination.
Comment: Please try my solution. Your outlet is connected to the container, which is not the child view controller. This solution works. I have tried it.
Answer: The easiest option would just be to change the child view controller's view's background to transparent (UIColor.clear), either in the XIB/Storyboard or programmatically. Then, you can change the background color of the container view directly, as you tried before.
Comment: This sadly does not work. I have tried adding it before the other section as you suggested, yet this does not make a difference. I believe that it is less of an error assigning the color, but rather a mistake of the setup. For example, I have tested my background color change with a button's IBAction, which did work. Thank you for the suggestion nevertheless.

Change color of external ViewController