Relationship between Beta regression of Y on X and linear regression of X on Y. (where Y is a proportion)

Question: I am trying to model the relationship between school district funding and a district's poverty rate.
If I treat funding as the independent variable then the dependent is a proportion on [0,1]. This seems to be good for beta-regression. If I treat poverty rate as the independent variable then it seems good for simple linear regression.
So my question is - what are the differences between treating the proportion as independent with SLR or as the dependent with beta-regression?
SLR:
Answer: The main difference is that in SLR you use the poverty rate which takes values in $[0,1]$ whereas in beta regression you use a transformation of poverty rate as the explanatory variable which takes values $(-\infty, \infty)$.
Let $Y$ be the poverty rate and $X$ be the funds per student.
In the standard linear regression you have fit the line $ X = b_0 + b_1 Y $ which can be rearranged to give
$$
Y = \alpha_0 + \alpha_1 X
$$
where $\alpha_0 = -b_0/b_1$ and $\alpha_1 = 1/b_1$. This results in the straight line shown in your first graph.
For beta regression you fit the line
$$
f(Y) = \beta_0 + \beta_1 X
$$
where $f:[0,1] \rightarrow \mathbb{R}$. This ensures that $Y = f^{-1}(\beta_0 + \beta_1 X)$ gives a valid value for the proportion. This also explains why we see some non-linearity in the fitted line on your second plot.
Comment: Besides the link function $f$, also different is: 1. the error distribution (normal vs beta distributed) 2. the direction of regression attenuation (the bias in the curve line to the mean of $X$ vs the mean of $Y$) 3. the interpretation of the line (a predictor of $E(X|Y)$ versus a predictor of $E(Y|X)$). I would say that this attenuation is effectively/practically the main difference because linear regression of Y on X and linear regression of X on Y give a similar picture.
Comment: Thanks a lot, you made this was very clear!! And @Martijn, thank you!. So I guess I will just go with simple linear regression for the easy to interpret coefficients and its assumptions of normal error and linear relationship seem (sort of) satisfied.


Append columns from one data table to another data table

Question: I have multiple data tables(upto 28) in C# and I want to append all their columns in one data table(with data).
Example:
datatables are: DT1,DT2,DT3 and so on
Number of Columns in these respective data tables: N1,N2,N3 and so on
Output: One data table DT with total columns N1+N2+N3+... and all the data from the above data tables.
Thanks.
Edit:
My tables have clustered primary keys.
Comment: so what type of data in your column n1,n2, n3? its int, string, double or any else?
Comment: See this link https://stackoverflow.com/questions/12278978/combining-n-datatables-into-a-single-datatable
Comment: @ershoaib the data can be of any type, each table have around 100 columns so in short I want to get a table consisting of around 2000 columns that includes all the DT1,DT2 etc. The number of rows will be same in the all tables.
Comment: if your have 3 datatables with each of 5 columns so your want 15 coulmns in resulting datatable or only 5 column with concatenating of each of respective column in all 3 datatable
Comment: @ershoaib the solution in the link cannot be implemented in my case as I have clustered primary key
Comment: @NiranjanKala in that case the primary key is one column, I have a clustered primary key
Comment: @ershoaib I need 15 columns. for example i have 3 datatables with 5 columns each and 10 rows in all three datatables, I need a datatable with 15 columns and 10 rows
Comment: @DIVIJ: you can take idea from that code and modify according to your requirement. It will make you move forward to complete your task.
Comment: clustered primary key and primary key are same read this https://stackoverflow.com/questions/10706992/database-primary-key-clustered-or-nonclustered but if your clustered index is rather than primary key then you please mention in your question.
Answer: <code>var all = new DataTable();

all.Merge(DT1);
all.Merge(DT2);
all.Merge(DT2);
</code>
...
better to use in a loop.


Solving a transcendental equation consisting of a quadratic part and a part involving inverse Lambert W functions

Question: Question statement
I would like to solve the following equation in the two variables $x$ and $y$:
\begin{gather}
0 = x^2 - a y^2 + i b [x y - W^{-1}(x)W^{-1}(y)] ,
\end{gather}
where $a$ and $b$ are purely real parameters, and $W^{-1}(x)$ is the inverse Lambert W function of $x$. Domain constraints exist due to physicality: for all physical solutions $y$ is purely imaginary, and for some physical solution $x$ is purely imaginary.
Answer attempt
Put the above equation in the alternative form thus:
\begin{gather}
0 = x^2 - a y^2 + i b x y (1 - e^x e^y) .
\end{gather}
Then, by inspection (separate terms into pairs), we have at least the solutions
\begin{gather}
\begin{aligned}
\text{(i)}&\text{ } x = \sqrt{a} y \text{ and } y = \frac{2 i n \pi}{1 + \sqrt{a}} \text{, where } n \in \mathbb{Z} \text{,}\\
\text{(ii)}&\text{ } x = - \sqrt{a} y \text{ and } y = \frac{2 i n \pi}{1 - \sqrt{a}} \text{, where } n \in \mathbb{Z} \text{,}\\
\text{(iii)}&\text{ } x = - i b y \text{ and } y = \frac{\operatorname{Log}(- a / b^2)}{1 - i b} \text{, and}\\
\text{(iv)}&\text{ } x = - i \frac{a}{b} y \text{ and } y = \frac{\operatorname{Log}(- a / b^2)}{1 - i (a / b)} .
\end{aligned}
\end{gather}
The method of this answer attempt is quite obviously not general; hence I post. I might ask more specifically: Can we prove that (i) to (iv) are the only solutions? and if not, is there a more elegant method that derives all solutions?
Thanks
I extend sincere thanks for any help.
Comment: It's possible to show (using just the intermediate value theorem) that the equation has a solution with $x \in \mathbb R$ and $y=(2n+1)\pi i$, but I don't think they'll be easy to write down explicitly.  I've been thinking about how to find an approximate formula but I've had no luck with that either.
Comment: Thanks very much for your comment!

I hadn't thought of proving solution domains, which is definitely a good idea. Would you be able to outline how you used the Intermediate Value Theorem?

I was wondering about approximations as well. It would be nice if one could prove solution domains for which particular approximations are valid, but alas I too have had no luck yet.
Comment: Sure.  There are some cases to check (when $a$, $b$, and $n$ are positive and negative) so let me just do one of them.  Suppose $a>0$, $b>0$, and $n\geq 0$.  If $y = (2n+1)\pi i$ then $$\begin{align}&f(x,y) = x^2-ay^2 + ibxy(1-e^x e^y) \\&\qquad= x^2+a(2n+1)^2\pi^2-\pi bx(1+2 n)(1+e^x) \to -\infty\end{align}$$ as $x \to +\infty$ and $f(0,(2n+1)\pi i) = a(2n+1)^2\pi^2 > 0$, so $f(x,(2n+1)\pi i)$ has a zero with $x>0$.
Comment: Once again, I thank you! Your idea is clever. It is not obvious to me how to find for $y = (2 n + 1) \pi i$ an expression for $x$, nor if there is an appropriate approximation one can use at this point, although I've just had beer with dinner. Nevertheless, the nice, albeit possibly unsurprising, result is that my solutions (i) to (iv) are definitely not the only solutions. So this is something to go on. Thanks!
Comment: Introducing the new variables
\begin{gather}
q =_\text{Df.} x + \sqrt{a} y \text{ and } r =_\text{Df.} x - \sqrt{a} y \nonumber
\end{gather}
the governing equation looks slightly more symmetric:
\begin{gather}
0 = q r + i \frac{b}{4 \sqrt{a}} (q^2 - r^2) (1 - e^{(1 + 1/\sqrt{a}) q / 2} e^{(1 - 1/\sqrt{a}) r / 2}) .
\end{gather}
I'm not sure if this is helpful.
Answer: Using the basic idea behind the method of dominant balance I can get a good approximation for the solutions mentioned in my comment.
Let $a>0$, $b>0$, and $y=(2n+1)\pi i$.  By expanding the parentheses the equation becomes
$$
a\pi^2 + 4 a \pi^2 n + 4a\pi^2 n^2 - b\pi x + x^2 - b\pi xe^x - 2b\pi nx - 2b\pi nxe^x = 0.
\tag{1}
$$
Numerically it appears that as $n \to +\infty$ the root $x$ also tends to $+\infty$ so let's go ahead and assume this.  The two largest terms in the equation are then $4a\pi^2 n^2$ and $-2b\pi nxe^x$, so as $n \to \infty$ the equation is approximately the same as
$$
4a\pi^2 n^2 - 2b\pi nxe^x = 0
$$
or, upon dividing through by $2\pi n$,
$$
2a\pi n - bxe^x = 0.
$$
This has an explicit solution
$$
x = W(2\pi n a/b),
\tag{2}
$$
which appears to give a good approximation for the solutions of $(1)$ as $n \to +\infty$.  This approximation appears to get better when the ratio $a/b$ is large.
If you'd like you can get a more elementary leading order approximation by using the known asymptotic
$$
W(q) \approx \log q - \log \log q + \frac{\log \log q}{\log q} + \cdots
$$
as $q \to \infty$.
Numerics.
Let's fix $a=b=1$.  In the plots below $n$ is on the horizontal axis.
The blue dots in this plot are the numerical solutions of $(1)$ for $x$ when $n=1,2,\ldots,40$ and the black line is the asymptotic solution $(2)$ we obtained.

This second plot shows the absolute error between the numerical solutions to $(1)$ and the asymptotic solution $(2)$ for $n=10,11,\ldots,5\times 10^4$.  The $n$-axis is plotted with a logarithmic scale for clarity.


Problema com Lógica do If com GPS em Android

Question:
Como Funciona:

A latitude do GPS do usuário deve estar entre -22.899529 e
  -22.899922 para que se crie um perímetro. O aplicativo só vai funcionar algumas funcionalidades caso esteja dentro deste perímetro

.

Observação:

1) Eu não inseri a longitude pois estou tentando fazer com que ele
  entre neste If, mas estou com uma grande díficuldade, caso for
  possível por gentileza mostrar exemplos com o longitude juntos.

Shopping.java

package com.vuforia.samples.Books.app.Neoris;

import android.app.Activity;

import com.vuforia.Vuforia;
import com.vuforia.samples.Books.ui.ActivityList.AboutScreen;

/**
 * Created by th on 14/06/17.
 */

public class Shopping {

    private String nomeShopping;
    private String licenseKey;
    private String accessKey;
    private String secretKey;

    private Activity mActivity;
    private int mVuforiaFlags = 0;

    public Shopping(AboutScreen aboutScreen) {
    }

    public Shopping() {

    }

    public String getNome() { return nomeShopping; }

    public void setNome(String nome) {
        this.nomeShopping = nome;
    }

    public String getLicenseKey() {
        return licenseKey;
    }

    public void setLicenseKey(String licenseKey) {
        this.licenseKey = licenseKey;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public void setDados(double latitude, double longitude){
//   -22.899529    -22.899922
        // O menor é o MAIOR
        // o maior é o MENOR
        if((latitude >= -22.899529 && latitude <= -22.899922)){
            setNome("Neoris");
            setLicenseKey("Ad84Z0z/////AAAAGSgcOhPVvkoniWypHW2Dfsw+iX69sih5qx5JH1PEs92sM2xIhbsKnb2eTNkfBeQymsfgyRswpCDi2Ocu78RH+5+7/fXED7hJPLf3T7k4xKKLl4z8OKfCmr8jE0L5wQdJVV9L3tiHEoUx67M4b3ZSlO3/AzDLYi2/Zt3z8fuPo62osy469O+bKBsKKZtnyX9K7RYwJ2colMQ1bIhQERjg1w5cEZLHUacXAI1ndYhzS2Xl5iwAz98VZ65sptn+PrA5Xno55VGddt7rSBmvwuhZzeyShWnOqiYFhjWg80F3PFv2H/hYfIt4ML37yerJxS/n0z8yFv1H5gPi+Abd5nfaboz/xx1WgXf0yDvQKslFV+rr");
            Vuforia.setInitParameters(mActivity, mVuforiaFlags, "" + getLicenseKey()); // Importante para o setLicenseKey.
            setAccessKey("f854427b00cf89cb4909cf3780a22f1fe6dd1daa");
            setSecretKey("16208b50224e2ff8d3c93f069d2c4adf739cea7a");

        } else if((latitude >= -22.899682) && (latitude <= -22.900006) && (longitude >= -43.178666) && (longitude <= -43.178197)){
            setNome("Outros");
            setLicenseKey("AULCxLD/////AAAAGa6JoRhAAk70lshljOUpGeN7XUgbJ/jA8ZGpdHb4EVUBTsJ5Z6C8FYvrRBtMsbePU6wI2DKgO3U7msQ9bMqY1+qn0SRY8K3raNYxd+cgBkbmiJDonnuvPr9Hd3RHo7ArwO1x8wGsA1sWw/Bo+q7HpjLbdKqM/ceI2IlnWJQTD+H47zlFuV63utnK/soPttLP+HmL1Lx/ko6uLLKe9yhuuAwpbkNR0UsNGYXlueTCOU/CfIot0VCBg2Kxpz4/cnlmCetedW0+bZypzh6gWfV9MS1Sh9n1LEYr8EXjpOEyHhaBPAgE3lX5khkVc3FRetD81WC7fRAQB5ozp6X1H4u04yWLbzWf8S8XSPK5a542gbNg");
            Vuforia.setInitParameters(mActivity, mVuforiaFlags, "" + getLicenseKey()); // Importante para o setLicenseKey.
            setAccessKey("6ad29c13cb8af364c7c7f893ca7651974a887f96");
            setSecretKey("370db33ce57acc73a84df1f6d19339da69e45235");

        }

    }
}

AboutScreen.java [O código não está completo, pois não precisa]:

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();

            /*
            *  Melhora a precisão do Resultado encontrado pelo GPS
            *  para (6) casas decimais com arredondamento.
            * */
            BigDecimal precisaoLatitude = new BigDecimal(latitude);
            BigDecimal precisaoLongitude = new BigDecimal(longitude);
            precisaoLatitude = precisaoLatitude.setScale(6, RoundingMode.UP);
            precisaoLongitude = precisaoLongitude.setScale(6, RoundingMode.UP);

            latitude = Double.parseDouble(String.valueOf(precisaoLatitude));
            longitude = Double.parseDouble(String.valueOf(precisaoLongitude));

Answer: Então galera, eu li a discusão e acredito que está tendo um equívoco por aqui.
Latitude/Longitude não deve ser comparada com maior ou menor, pois não são números, mas sim coordenadas.
Para delimitar um perímetro de coordenadas, você tem que não comparar entre as duas, mas sim determinar os bounds do lugar e ai sim comparar.
Esse bound tem que levar em consideraçao não somente uma parte da coordenada, mas sim a coordenada inteira (lat/long)
Um exemplo, tive um projeto onde tinha o ponto inicial da cidade, e depois tinha a área da cidade, e precisava saber se uma lat/long estava dentro da área da cidade. É mais ou menos essa a idéia o pedido do amigo, porém mais restrita a uma distância menor.
Até daria para verificar se a latitude/longitude está entre uma e outra, invertendo a ordem da consulta pois lat/long se mede da direita pra esquerda, a partir dos meridianos (https://stackoverflow.com/questions/21190923/is-a-lat-lon-within-a-bounding-box).
Então minha solução seria a seguinte:

Determinar o perimetro usando bounds, pela lat/long. Se for algum lugar, usuaria a consulta do google maps pra saber os bounds do estabelecimento, como referência https://stackoverflow.com/questions/27990985/how-to-check-if-latitude-and-longitude-of-a-specific-address-belongs-to-lat-and
Criar os bounds, referência: https://stackoverflow.com/questions/15319431/how-to-convert-a-latlng-and-a-radius-to-a-latlngbounds-in-android-google-maps-ap
Depois verificar se a lat/long está dentro do LatLngBounds criado no 3, usando o método contains(LatLng), referência: https://developers.google.com/android/reference/com/google/android/gms/maps/model/LatLngBounds;
Answer: estava observando o seu código do if e notei o seguinte.
latitude >= -22.899529 && latitude <= -22.89992
Isso nunca vai entrar, pois para a latitude ser maior que -22.899529, você estaria esperando um latitude como -22.899528 e para ela ser menor que -22.89992 você precisaria de uma latitude como -22.89993, então nenhuma latitude entraria no seu if.
O correto em minha opinião seria você inverter os sinais, sendo assim ficaria:
latitude <= -22.899529 && latitude >= -22.89992
Porque assim ficaria na faixa de "529" até "992", entendeu?
Comment: mas olha só neste meu raciocínio. -22.899529 é um número maior que -22.89992, pois este primeiro número está mais perto de ser positivo do que o outro, correto? Então ele não pode ser <= -22.899529 e nem >= -22.89992. Ou estou errado?
Comment: Está errado. Você quer que a posição esteja entre 2 valores: -xx.xxx920 e -xx.xxx529, então ela deve ser maior que -xx.xxx920 e menor que -xx.xxx529.
Comment: Mas então @ThiagoSaad, foi isso que respondi, latitude <= -22.899529 && latitude >= -22.89992. O seu está latitude >= -22.899529 && latitude <= -22.89992.
Comment: @VictorPettengillFernandes, ele não entra no if.. Eu li a API e diz para utilizar o Location.distanceBetween , porém ele só calcula  (Latitude do Usuario, Longitude do Usuario, latitude origem, latitude destino). Eu preciso que ele calculo 2 LAT e 2 LONG + a comparação da LAT e LONG do usuário.
Comment: @MárcioOliveira a resposta do Victor está correta. Como é número negativo, para números antes do -22.89992 são maiores mesmo.
Comment: Eu disse "Está errado" para o comentário acima do meu.


Find the joint probability density of the two random variables $X$ and $Y$

Question: Find the joint probability density of the two random variables X and Y whose joint
distribution function is given by
$F(x,y) =
\begin{cases}
(1-e^{-x})(1-e^{-y}),  & x>0 \text{ and } y>0 \\[2ex]
0, & \text{elshewhere (where is this exacty?)}
\end{cases}$
Use joint probability density to determine $P(1<X<3,1<Y<2)$.
In order to solve we use JDF Theorem
$F(x,y) = P(X\le x,Y \le y)= \int^{y}_{-\infty} \int^{x}_{-\infty} f(s,t) \text{ds dt}$
Yet what alludes me is how ones derives the correct answer from this.
Does one have to take the gradient of this to arrive at the right result?
Of This problem?
$(1-e^{-x})(1-e^{-y}) = 1-e^{-y}-e^{-x}+e^{-xy}$ ?
Comment: "Elsewhere" is $x \le 0$ or $y \le 0.$
Answer: The probability of the green region in the plot below is what you want. You could use
the joint CDF (your last equation, subject to limits) several times to get that probability.
Maybe, start by finding
$P(X \le 3, X \le 2).$ Piece it together by subtracting two probabilities
from that and then adding back another.
The plot is based on a simulation of a million points in R statistical software. This allows one
to find the approximate probability in the green rectangle.
<code>x = rexp(10^6);  y = rexp(10^6)
cond.x = (x > 1 & x < 3)
cond.y = (y > 1 & y < 2)
cond = cond.x & cond.y
mean(cond)
## 0.073555  # aprx answer
plot(x,y, pch=".", col="skyblue")
points(x[cond],y[cond], pch=".", col="darkgreen")
abline(v = c(1,3), col="red");  abline(h = c(1,2), col="red")
</code>
Comment: Not quite sure what the objective is: to find the joint PDF or to evaluate the probability. $X$ and $Y$ are iid $Exp(rate=1),$ so the joint PDF is $f(x,y) = e^{-x}\cdot e^{-y} = e^{-(x+y)},$ for $x, y > 0.$ Also, $P(1 < X < 3) = 0.3180924,\, P(1 < Y < 2) = 0.2325442,$ and by indep $P(1 < X < 3, 1 < Y < 2) = 0.07397052.$ I dealt with the joint CDF as you asked, but I'm not quite sure why it is part of the Problem.


Allow authenticated users to create taxonomy terms

Question: Currently I categorize content using nodes as categories, because authenticated users cannot create taxonomy terms.
What would be the way(s) to accomplish a term/add page for authenticated users?
Answer: Taxonomy Access Control provides finer control of taxonomy permissions, that sounds like what you need.
Comment: hm I wanted to prevent another access control module, but it probably the easiest way. Thanks


Polynomial, bounded functional

Question: In order to prove continuity of the functional $$\varphi: \mathbb{R}[X] \ni p \rightarrow p'(2011) \in \mathbb{R}$$ where $$||p|| = \sup \{|p(t), \ t\in [0,1]\}$$ I'd like to prove that this functional is bounded.
So I need to find an $M>0$ such that $|\varphi(p)| = |p'(t)| \le M ||p||$.
I thought that maybe I could use a Mean value theorem, but those theorems claim that there exists $c \in [a,b]$ such that $p'(c)= \frac{p(b)-p(a)}{b-a}$, whereas in my problem $c=2011$ is already given?
How can I prove boundedness of this functional?
Thanks in advance
Answer: In your definition of the functional $\phi$, what is $x$? Is it a given number in $[0,1]$?
In any case.
This functional is not going to be bounded. Take $p(x)=x^n$ for example. We have $||p||=1$ but $p'(x)=nx^{n-1}$, which take the maximum value $p'(1)=n$ (assuming the $x$ in your definition of $\phi$ is $1$).
Examples like this can be constructed no matter what is $x$ in your definition of $\phi$.
Comment: @Sasha Yes, the derivative of a small function can be large.
Comment: So this functional is not continuous?

Polynomial, bounded functional


Air is out in server closet, not going to be fixed until tomorrow... What to do?

Question: We are a small company, so we have a small closet with one server rack. This closet has very good ventilation, so that's not a problem - but today the air went out on this side of our company suite. It didn't occur to me until just now, that means the closet is very hot, and indeed I came in to find the servers all with fans on full blast and the temperature in there quite hot, and I haven't yet checked if all the servers are up.
I opened the door, but for security purposes I can't leave it open so I'll have to close it when I leave in an hour or so. All the servers are running Windows; there are a couple towers (those are probably cut off by now from the heat, I would imagine) and basically the rest of the rack is full of rack servers.
I need to keep these servers running in the morning. They contain all our vital functions - network data storage, email, intranet, accounting, etc. Not much can be done without them up.
What do I do??
Comment: For what comfort it may be worth the morning after - http://www.datacenterknowledge.com/archives/2008/10/14/google-raise-your-data-center-temperature/  - Servers can survive a remarkable amount of heat (and humidity changes) with "no consistent increase" in failure rates...
Comment: If you only have an hour to sort this solution out, and you can't leave the door open (which would be my first choice), then I doubt there's much you can do on such a limited time frame. Others opinions may differ though.
Answer: Your options are limited as you've painted yourself into a corner.  Here are your options.

Leave the door open and run numerous room fans on them to circulate air.  Leave servers running for access to everything.  Pray servers don't die or someone doesn't steal them.  Prepare for fitfull nights sleep.
Close door and leave servers running.  Pray harder that servers don't die. Prepare for not sleeping at all tonight.  At least servers won't be stolen, besides, who can carry something that hot?
Close door/power down servers.  You'll sleep well tonight.  Servers won't die and nobody will steal them.

To me your only real option is to power everything down.  If your company cannot operate in any way, shape or form without their computer systems up and running, then it's time for them to invest in redundancy.
You could also decide on leaving just one server running.  You could even mention that to management.  "I can leave one server running, which shall it be?" and it makes them feel like they're part of the solution.
Comment: +1. I especially like letting management make the hard choice. It will put you in a better place when you have the "server room REALLY needs cooling" discussion tomorrow. ;-)
Comment: I'm really curious to know how this morning went and if the servers survived the night.  I hope OP updates us.
Answer: We had a similar issue; server room ambient temperature was about 33 degrees if I remember.  Was like that for at least 2 or 3 days.  No issues with the servers, various temp readings on the server's chassis/core/etc. were maybe 8-10 degrees hotter than normal, but no errors, no shutdowns.  We ended up putting a big fan facing out from the server room to draw out the hot air, however.
Monitor the temperatures closely, react accordingly (turn them off or at least non-critical servers).
EDIT
Asked co-worker, he said the hottest it ever got was 33 (and dropped to 28-29 when we put the big fan in the door).
Comment: I just went and found a fan. The servers have been surviving for 7-8 hours without air, so they should be okay. Your story is much less extreme than the others, thanks for the reassurance, haha. :) - now I'll see if they stay up under load tomorrow...
Answer: You could look into renting a portable HVAC or you could just turn off all the servers before you leave. If they over heat and cause component failure, they will end up being down longer than if you risk leaving them up.
Answer: How long has the ventilation been out? If the time between it dropping off and when you opened the door is longer than you'll be gone, the temperature already found it's max and the servers may live the night.
Try to cut down heat where you can anyways:

Turn off any box you can
Turn off any software you can
ensure your backups are up to date

Bonus: find random lowly paid minion, offer pizza, overtime, and a sleeping back to stay with the open door.
Answer: They might turn themselves off.  Check to see if thermal shutdown is enabled (if you can get to that setting without rebooting.)
Answer: It's past your one hour deadline by now, but I would look into increasing the physical security of the office suite.  If you're lucky, you might be able to secure the space with just a bike lock or padlock, and that will allow you to leave the door open over night.  If possible, find a box fan or floor fan to point at the door.  Even better if the fan is in the room blowing warm air out.  The downside is this won't work if you have other staff there over night, locking cleaning staff out is likely the preferred option here.
Failing that, I would stay over night (or make my boss do it - who ever has ultimate responsibility for these machines should be the one holding the stick here).
In a nutshell: you would probably be okay letting them go in locked closet over night, but the odds that some could go really wrong are significant.  Do you really want to leave this to chance?
Answer:
What do I do??

Since your immediate options are limited to fanning the closet and hoping for the best, and you've done that, I would think about what to do tomorrow. If you have to keep the servers in a "closet", and assuming they do something important for your company, use the next week or so to work out a risk management strategy. Figure out what the worst case scenario would be (ie: servers stolen with credit card and social security numbers, liability exceeding 10M). Find small, affordable steps that can guard against whatever that worst-case is, while protecting the servers from damage. Some options might include backup power for a small HVAC system serving the closet. or even an installed ventilation fan connected to a thermostat (would do more than sitting a fan near the closed door). It may be a good time to talk to management about these things.
Answer: The inevitable answer, backported from the future when this will seem common-sense:

Use a public cloud such as AWS, Rackspace, etc.
Comment: Migrating to the "cloud" comes with it's own set of problems and issues, which could very well make the A/C going out seem like a walk in the park.
Comment: While humorous, this doesn't really help the OP.
Comment: No, but it is a suggestion for an action plan beginning the day after. Once this concrete problem is solved today, start migrating to a public cloud tomorrow.
Comment: The inevitable answer from a couple decades ago when everything was "cloud-based" in the sense of terminals on a mainframe: Use personal computers such as the Apple II or an IBM PC. (oh how we've come full-circle)


How can I test and quantify the change in distribution over multiple years?

Question: I have a data set of energy usage values taken every half hour for a year, for four years.
How can I test for, and quantify, an improvement (i.e. decrease) in energy usage, per-year?
I have initially assessed the data via histograms and the use of standard deviation. I initially assumed I could use a t-test, though from my current understanding it seems that that could test one year into the next, but not across all four?
I have a very strong understanding of excel (though no vba, yet), and a smattering of R. Provided there is a suitable test, I will be attempting to implement it in one of these two.
I'm looking for something related to change in distribution, standard deviation and mean, not only as I would understand it, but also this needs to be explainable to non-statisticians. Assume that the distribution of data across the year is normal (it practically is).
Comment: @whuber As it is data from buildings, they follow a regular yearly, seasonal cycle, so the data was split into individual years.
Initial analysis showed there was a difference between these groups, both in the mean, and distribution around it.
An ideal solution would be a method to quantify the change in the mean and distribution, which can then be applied to similar data sets from other buildings.
Comment: What does your initial assessment look like? Did you, for example, break the data into groups of contiguous times and explore the distributions?  Did that exploration give clear results?
Comment: That sounds like a good approach. You will need to decide which aspects of the distributions you want to compare in addition to their means and SDs.  You might also consider whether it would be more meaningful first to remove any secular trend (which would be captured by comparing the annual means) and consistent seasonal variation (which might mask interesting aspects of the shapes of the residual distributions). Normality is not an issue. Moreover, you might have little need for formal testing when means are clearly changing: maybe you just need good descriptive statistics.
Comment: @whuber from my googling of secular trends, I'm not sure removing them would be useful, or even possible with the available data, though worth baring in mind, thank you.

As for consistent seasonal variation, in our case this is a directly driving force (energy usage of buildings and annual weather cycles are intrinsically linked), what method would remove them? By removing them it seems like you may miss out on the variable that all this derives from?

As the end result is to quantify improvement, a comparison of distribution via box and whisker may suit? Any other suggestions?
Comment: Quantifying secular trends is as easy as making a robust fit of a simple function over time. The reasons to account for seasonal variation are plain, as you say: if you do not, then you confound that variation with other variations of interest. Of course I am not suggesting that you *ignore* either the secular trend or the seasonal variation--far from it!--but that it can be fruitful to analyze your data into these components. The resulting description of changes of distribution over time would then be comprised of a long-term trend, a seasonal cycle, *plus* other forms of variation.
Answer: Since you have time series data, your data is auto-correlated thus this means you have violated the independence assumption underlying the t test. I suggest that you build an ARMAX model at a higher level of aggregation say monthly. Use Intervention Detection schemes along with an ARIMA structure to identify to test for a possible mean shift or change in trend over the 48 months.
Comment: *Of course* there is a simple analysis. The real question is whether it will be helpful for the intended task and not potentially misleading.  Not every dataset has to be analyzed as an ARMAX model, even when it happens to be a time series.
Comment: Complex is in the eye of the beholder and a relative term.I agree that a simple answer/approach was requested but a simply wrong method like a t test deserved my warning.
Comment: Thanks for the quick (and detailed!) response. There is currently plan to apply ARIMA analysis to this data set at a later point, but the current objective is to find a simple analysis that can be simply understood with GCSE/A level maths.
Comment: There is no "simple analysis" in my opinion . One must identify and incorporate memory structure (ARIMA) and any needed deterministic variables such as pulses/level shifts/seasonal pulses/local time trends that are either user-suggested or empirically detected.
Comment: Thank's anyway. I would 'vote' you up for the help, but my rep isn't high enough to let me apparently :(
Comment: What you say is true if there is intermittent data otherwise please provide an example of a time series that doesn't fit the paradigm of an ARMAX model.
Comment: @DaveRGP As you get around to modelling half-hour data take a look at http://stats.stackexchange.com/questions/125587/how-to-predict-the-time-series-data/125597#125597 for some guidance with respect to modelling ...
Comment: That challenge sounds like the proverbial nail: whatever it is, if I produce it, you will hammer it! The point is that a time series is never ARMAX: it's *your model of it* that is ARMAX. And I don't question your ability to model any set of data--whether it's a time series or not!--using that tool. What does matter, though, is *how effective* and *how useful for a particular purpose* that model may be. In this case, the OP has signaled that a simple, readily interpretable (yet presumably accurate) analysis will have more value than a complex model.


Boas práticas com contract do bd Android

Question: Quais seriam as boas práticas em relação ao sqlite no Android?
Eu uso um único db contract para todas tabelas (cada tabela uma classe dentro da classe principal contract)?
<code>public final class FeedReaderContract {
    // To prevent someone from accidentally instantiating the contract class,
    // make the constructor private.
    private FeedReaderContract() {}

    /* Inner class that defines the table contents */
    public static class FeedEntry implements BaseColumns {
        public static final String TABLE_NAME = "entry";
        public static final String COLUMN_NAME_TITLE = "title";
        public static final String COLUMN_NAME_SUBTITLE = "subtitle";
    }

    public static class OutraTabela implements BaseColumns {
     ....
    }
}
</code>
Ou eu crio uma classe contract para cada tabela?
Answer: Da forma como você está fazendo está ótimo. Acredito que você também deve implementar um ContentProvider, então especificar as URI's de acesso para cada tabela no Contract é uma boa.
No mais, você só precisa de um arquivo de Contract. Se você tiver muitas tabelas mesmo, talvez possa separá-las em vários arquivos, agrupando as tabelas por assunto.
Esse treinamento da Google dá ótimos direcionamentos sobre o assunto:
https://br.udacity.com/course/android-basics-data-storage--ud845/
Comment: no caso eu tenho 12 tabelas (o que são muitas), eu fiquei confuso, pois nas documentações do google, não informa se eu devo colocar todas tabelas na mesma classe contract, eu pensei nisso pois.. São 12 tabelas, ou seja, 12 arquivos, não ficaria bagunçado?
Comment: Não existe um direcionamento pra isso na prática. 12 tabelas é pouco, até porque você só está criando constantes nas classes e alguns poucos métodos. Eu colocaria tudo numa só. Mas é a gosto do freguês, rs, o importante também é não "organizar" demais e dificultar a leitura.


How to change core's default services

Question: Dependency Injection is added to core, but there's no documentation to tell how developer can alter the default services. For example, I would like to change cache.bootstrap class to APC Caching.
Comment: Oh but [there is](https://drupal.org/node/2026959) :)
Comment: Aw, my fault. I am sorry.
Comment: No need to apologise, unless you know it's done using compiler passes I think that would be pretty hard to find. If you get a chance please do add an answer with the code you end up using, I'm sure it will be very useful to future visitors. If not I'll try to remember to come back and add something generic in
Comment: It's no longer done using compiler passes.
Comment: The answer by @chx is perfect, but note that your example is a special case. I suggest you open a separate question on how to provide a different cache backend and we can answer that in detail.
Answer: You can look at LanguageTestServiceProvider to see how alterations are made. Or I can offer my class:
<?php
namespace Drupal\mongodb;

use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;

/**
 * MongoDB service provider. Registers Mongo-related services.
 */
class MongodbServiceProvider implements ServiceProviderInterface, ServiceModifierInterface {

  /**
   * {@inheritdoc}
   */
  public function register(ContainerBuilder $container) {
  }

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    foreach ($container->findTaggedServiceIds('mongodb.override') as $id => $attribute) {
      $container->setDefinition(substr($id, 8), $container->getDefinition($id));
    }
  }

}

Basically, in alter you need to use the getDefinition method, do something with the definition and then use the setDefinition method to put it back.
and then here's the relevant parts of mongodb.services.yml:
services:
  mongodb.flood:
    class: Drupal\mongodb\Flood\MongoDBBackend
    arguments: ['@mongo', '@request']
    tags:
      - { name: mongodb.override }

Comment: Just wanted to mention it looks like you don't need to use `setDefintion()` if you've used `getDefinition()` - you can just update the definition.

How to change core's default services


How can I cache pages indefinitely?

Question: I'm upgrading a small site currently in Drupal 6 to Drupal 8, it's for a non-profit and doesn't receive all that much traffic. It's a relatively static site, content will be added regularly, but certainly not every day. While the amount of traffic is easily handled even on shared hosting, I'd like to keep the page loading times low. I used Boost for that on Drupal 6, but now with Drupal 8 I want to use the internal page cache.
From what I understand, Drupal 8 should be able to automatically invalidate the cache when nodes are edited. So what I'd like to do is to cache all pages of my site indefinitely until the data behind them actually changed. But the cache dialog on the performance admin page only allows a page cache maximum age of 1 day.
Is there a way to configure a stock Drupal 8 to cache pages forever? The cache should only be invalidated if nodes are edited and the page actually changes content. Ideally I'd like to automatically pre-warm the cache as well.
Answer: The setting on the performance page, unlike D6/7, does not affect the page cache module at all. The page_cache module always caches indefinitely, you can not configure it otherwise. Invalidation happens through cache tags, as you said.
The setting that you can see only affects external caching through the HTTP Cache-Control header, for example Varnish and in browsers. There are ways to invalidate caches in varnish using cache tags, but there is none to invalidate pages that are cached client-side in browsers, so I would recommend to not set that value too high.
Comment: Good to know. On looking closer the performance page actually mentions this, but it also mentions the page cache module directly above the settings, which is what mislead me.
Comment: Yes, I know, it is definitely confusing. If you have ideas on how to make this clearer, I think there are open issues about that UI that are trying to improve it.

How can I cache pages indefinitely?


Populate table view cells from XML file

Question: I have an array (quite big), and now i want to populate my table view from specific items from it (for specific key). Please take a look at part of my XML file:
</Shops>
    <Architecture>Архитектурные достопримечательности<place>
            <name>Старый английский двор</name>
            <description>Старый английский двор — архитектурно-историческая достопримечательность и музей Москвы (ул. Варварка, д. 4). Памятник гражданской архитектуры XV—XVII веков, резиденция английской торговой Московской компании, а во время посольских миссий — Английский посольский дом.</description>
            <webpage>http://ru.wikipedia.org/wiki/Английский_двор_(Москва)</webpage>
            <latitude>55.752297</latitude>
            <longitude>37.626897</longitude>
            <imageCell>https://dl.dropbox.com/s/gzbgtll5wzn9dox/StaryiAngliskyiDvor.jpg?dl=0</imageCell>
            <imageFirst>https://dl.dropbox.com/s/8abn9c6omb1qp3h/StaryiAngliskyiDvor.jpg?dl=0</imageFirst>
            <imageSecond>https://dl.dropbox.com/s/ihrdgys6nr1zsiz/EnglishCourt2.jpg</imageSecond>
            <imageThird>https://dl.dropbox.com/s/yt36zjdc1vqgb1k/EnglishCourt3.jpg</imageThird>
            <imageFourth>https://dl.dropbox.com/s/iu9upggjuafd8y5/EnglishCourt4.jpg</imageFourth>
        </place>
        <place>
            <name>Палаты Романовых</name>
            <description>Палаты Романовых находятся в Зарядье. Зарядье — так в старину называлась часть центра Москвы, расположенная «за рядами» торговых лавок, примыкающих к Кремлю. Район расположен к Востоку от Кремля, между Варварской улицей, в советские времена носившей имя Разина, и Москвой-рекой. Свое название он получил в XVI веке. И сегодня это место в центре Москвы. Палаты Романовых в Зарядье — это единственная постройка, сохранившаяся от большой усадьбы бояр Романовых.</description>
            <webpage>http://ru.wikipedia.org/wiki/Палаты_Романовых</webpage>
            <latitude>55.752717</latitude>
            <longitude>37.629189</longitude>
            <imageCell>https://dl.dropbox.com/s/d9ule0w6ps968ih/PalatiRomanovi.jpg?dl=0</imageCell>
            <imageFirst>https://dl.dropbox.com/s/tmyi71om08fbvhd/PalatiRomanovi.jpg?dl=0</imageFirst>
            <imageSecond>https://dl.dropbox.com/s/bnjjzqhdes7y1wj/PalatiRomanovih2.jpg</imageSecond>
            <imageThird>https://dl.dropbox.com/s/i64yhbwsduk1gem/PalatiRomanovih3.jpg</imageThird>
            <imageFourth>https://dl.dropbox.com/s/thx7en6i157nsng/PalatiRomanovih4.jpg</imageFourth>
        </place>

What i want is, for example, populate table view only for items of "Architecture" key. How could i do this?
At now, i do this very straightforward:
labelText.text = [[self.listOfPlaceDetails objectAtIndex:indexPath.row] objectForKey:@"name"];

Should i specify key in someway? Or separate my XML file for pieces?
Any advice would be appreciated, thanks!
Answer: The first step should be, change your xml to a Property List.(Other option is parse your xml I not recommend).
In new file -> Resource -> You find a blank property list file template.
Comment: I put much effort in that XML file and i think its not reasonable to change it in anyway.. And how property list help? It similar to XML.
Comment: Property list is a XML file, but with some tags than easily convert it to a NSArray or NSDictionary. In your xml the tags are the key, and Parse it (without third part code) is hard work.
Comment: plist files loads very fast while it takes so much more time to parse an XML file.But maybe he can't change his XML into plist because he get it from a webservice.
Answer: You have to parse your XML file in order to create an object representation of it.
To do so, you can use the NSXMLParser class (tuto by Apple), or use a faster library (look here for a good start).
Once you have your object representation, you can use it to fill your tableView.
Comment: I really wonder why there is no simple method, like objectForKey:@"key" and forChildNode:@"Node". XML files a good organised, but it feel painful to work with them.

Populate table view cells from XML file


How many ways are there to build a parser?

Question: I am learning about the ANTLR v4, which is a parser generator based on so-called Adaptive LL(*) algorithm. It claims to be a big improvement over LL(*) algorithm, but I also heard about some algorithm like LR.
What's the advantage/limitation of ANTLR's Adaptive LL(*) algorithm (over LR)?
Comment: Entire books have been written on this subject, I'm afraid this question is much too broad for SO.
Comment: The question is practically meaningless. Anybody can write their own parser generator or indeed invent their own (probably incorrect) parsing algorithm. There is no way to enumerate these and absolutely no point in doing so.
Comment: IMHO, the topic of creating various grammars and lexers/parsers is of more academic than practical interest. Most of the work done and time spent in a compiler is in the "optimizer".
Comment: Could u recommend some book on this topic? Thanks.
Comment: The ANTLR reference doesn't go into the guts of the algorithm as far as I remember, but I'm pretty sure Terrence Parr must have published a paper on  ALL(*). As for the classical LL, LR,  LALR and so on look for the "dragon book" (a note of caution: it's very mathematical/academic in nature).
Comment: @LucasTrzesniewski Thanks, I will try to take the challenge.
Comment: [Parsing Techniques: A Practical Guide](http://www.dickgrune.com/Books/PTAPG_2nd_Edition/). The first edition is available for free download. The literature reviee on the web page is invaluable.
Answer:
How many contemporary algorithms are there to build a parser?

To start with one can look at the list of the common parser generators.
See: Comparison of parser generators and look under the heading Parsing algorithm.
ALL(*)
Backtracking Bottom-up
Backtracking LALR(1)
Backtracking LALR(k)
GLR
LALR(1)
LR(1)
IELR(1)
LALR(K)
LR(K)
LL
LL(1)
LL(*)
LL(1), Backtracking, Shunting yard
LL(k) + syntactic and semantic predicates
LL, Backtracking
LR(0)
SLR
Recursive descent
Recursive descent, Backtracking
PEG parser interpreter, Packrat
Packrat (modified)
Packrat
Packrat + Cut + Left Recursion
Packrat (modified), mutating interpreter
2-phase scannerless top-down backtracking + runtime support
Packrat (modified to support left-recursion and resolve grammar ambiguity)
Parsing Machine
Earley
Recursive descent + Pratt
Packrat (modified, partial memoization)
Hybrid recursive descent / operator precedence
Scannerless GLR
runtime-extensible GLR
Scannerless, two phase
Combinators
Earley/combinators
Earley/combinators, infinitary CFGs
Scannerless GLR
delta chain

Besides parser generators, there are also other algorithms/means to parse. In particular Prolog has DCG and most people who have written their first parser from scratch without formal training typically start with recursive descent. Also Chart parser and Left corner parser.
In writing parsers the first question that I always ask myself is how can I make a grammar for the language at the highest type in the Chomsky hierarchy. Here lowest is Type-0 and highest is Type-3.
Almost 90% of the time it is a Type-2 grammar (context-free grammars), then for the easer task it is a Type-3 grammar (regular grammars). I have experimented with Type-1 grammars (context-sensitive grammars) and even Type-0 grammars (unrestricted grammars).

And what's the advantage/limitation of ANTLR's Adaptive LL(*) algorithm?

See the paper written by Terrence Parr the creator of Adaptive LL(*):
Adaptive LL(*) Parsing: The Power of Dynamic Analysis
In practical terms Adaptive LL(*) lets you get from a grammar to a working parser faster because you do not have to understand as much parsing theory because Adaptive LL(*) is, shall I say, nimble enough to side step the mines you unknowingly place in the grammar. The price for this is that some of the mines you unknowingly place in the grammar can lead to inefficiencies in the runtime of the parser.
For most practical programming language purposes Adaptive LL(*) is enough. IIRC  Adaptive LL(*) can NOT do Type-0 grammars (unrestricted grammars) which Prolog DCG can, but as I said, most people and most common programming task only need either type 2 or type 3.
Also most parser generators are for type 2, but that does not mean they can't do type 1 or possibly type 0. I cannot be more specific as I do not have practical experience with all of them.
Anytime you use a parsing tool or library there is a learning curve to learning how to use it and what it can and can not do.
If you are new to lexing/parsing and really want to understand it more then take a course and/or read Compilers: Principles, Techniques, and Tools (2nd Edition)
Comment: Yes, but what you really want is a parser generator engine that covers the broadest range of lanuages with the least amount of fuss.   As a practical matter, GLR does extremely well on this front (arbitrary context-free grammars) and is available in a number of tools.   GLL is equally good but pretty hard to find.   Earley is OK but not very efficient, at least its relatively easy to code.  Everything else has trouble with real grammars; you are only choosing between which parsing pit you fall into, and how much work it takes to climb out the pit for your particular grammar.  Including ANTLR.
Comment: I like the way @IraBaxter says it, `you are only choosing between which parsing pit you fall into, and how much work it takes to climb out the pit for your particular grammar. Including ANTLR`.


Running linux command in java

Question: I want to run "ls" command in java  and my code is-
 Note:- I am using WINDOWS.
import java.io.IOException;

public class Example
{
    public void fn()
    {
        Runtime run = Runtime.getRuntime();
        Process p = null;
        String cmd = "ls";

        try {
            p = run.exec(cmd);

            p.getErrorStream();
            p.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.out.println("ERROR.RUNNING.CMD");
        } finally {
            p.destroy();
        }
    }

    public static void main(String[] args) throws IOException
    {
        Example sp = new Example();
        sp.fn();
    }
}

but I am getting following error while running this code in eclipse-
java.io.IOException: Cannot run program "ls": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at Example.fn(Example.java:12)
    at Example.main(Example.java:28)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 6 more
Exception in thread "main" ERROR.RUNNING.CMD
java.lang.NullPointerException
    at Example.fn(Example.java:23)
    at Example.main(Example.java:28)

what needs to be corrected? what library, etc. should I add to execute this piece of code?
Comment: `I want to run "ls" command in java` Are you sure? Because if what you need is a listing of files on the system, this is one terrible way to do it for multiple reasons
Comment: Silly question, but you are running on Linux and the ls command works on there?
Comment: How are you running above program ?
Comment: try `run.exec("bash", "-c", "ls");`
Comment: Basically, your program seems to be correct - I was able to execute it on my system (Arch Linux) without errors.
Comment: As you've edited and added your operating system: On Windows, I'm not sure whether the `ls` command is even present. Have you tried `dir` instead?
Answer: If you want to run any command from Java ensure that executable of this file is present in PATH environment variable.
Or at least you have to set working directory to /usr/bin or similar.
One more solution is to use absolute path to executable, e.g.:
Runtime.getRuntime().exec("/usr/bin/ls");

But it is bad way to specify absolute path to any file.
Why don't you use File#listFiles()?

Running linux command in java


How to prove stochastic dominance of negative binomial random variable

Question: Let $X\sim NegBin(n_1,p)$ and $Y\sim NegBin(n_2,p)$ with $n_1>n_2$. How do I show that $X$ stochastically dominates $Y$ (i.e. $F_X(x)\le F_Y(x)\quad\forall\:x\in\Bbb R$)?
My try
Since a Negative binomial random variables is the number of tosses required before $r$ heads occur, where $r$ is the first parameter, we know that the minimum value it takes is at least $r$. Therefore, $0=F_X(x)\le F_Y(x)\quad\forall\:x<n_1$. However, I am finding it hard to prove it for $x\ge n_1$.
Also, intuitively it's clear. If we want to get more heads, then we have to perform more tosses, that's what I believe it says intuitively. But is there any way to show it algebraically?
Comment: **Hint:** construct an experiment where $X$ and $Y$ have the desired negative binomial distributions, but $Y \le X$ with probability 1. It would immediately follow from this that $F_X(x) \le F_Y(x)$ because $[X \le x] \subseteq [Y \le x]$.
Comment: @guy, Tossing a coin until we get $n_1$ heads will do? Then let $X$ be the number of tosses and $Y$ be the number of tosses until $n_2$'th head.
Comment: Seems good to me!
Comment: Post it as an answer @guy, I'll accept.
Answer: It is possible to show that $F_X$ stochastically dominates $F_Y$ if and only if there exists a probability space $(\Omega, \mathcal F, P)$ such that there are random variables $X \sim F_X$ and $Y \sim F_Y$ defined on this space such that $Y \le X$ holds everywhere. The if part of the implication is trivial, since $[X \le x] \subseteq [Y \le x]$ so that $F_X(x) = \Pr(X \le x) \le \Pr(Y \le x) = F_Y(x)$. While you don't need the second part, note that the only if part is also easy, as we can take $U \sim \text{Uniform}(0,1)$ and apply the probability integral transform with $X = F_X^{-}(U)$ and $Y = F_Y^{-}(U)$ where $F^-$ denotes taking the generalized inverse of the cdf.
In the case of negative binomial random variables, consider infinitely flipping a coin with heads probability $p$ and let $X$ the flip at which we hit heads $n_1$ heads and let $Y$ be the flip at which we hit $n_2$ heads. Then $Y \le X$, so we can apply the above observation.


Partial sum formula of the series $\sum_{n=2}^\infty \frac{1}{\sqrt{a_{n-1}} + \sqrt{a_n}}$, where $a_n$ forms an arithmetic sequence?

Question: I've been struggling with this series for a while, but I can't seem to figure it out.
Comment: Rationalize the denominator, $\frac{1}{\sqrt{x}+\sqrt{y}} = \frac{\sqrt{x}-\sqrt{y}}{x-y}$, and notice that $a_n - a_{n-1}$ is a constant. Telescoping.
Comment: Thank you very much for the quick and helpful response.
Answer: Since they form an arithmetic sequence, there exists $r\in\mathbb{R}$ such that $a_{n}= a_{n-1}+r$ for all $n\geq 2$. I assume $r>0$, otherwise, the answer is trivial (the series diverge to $\infty$).
Then,
$$
\frac{1}{\sqrt{a_{n}}+\sqrt{a_{n-1}}}
= \frac{\sqrt{a_{n}}-\sqrt{a_{n-1}}}{(\sqrt{a_{n}}+\sqrt{a_{n-1}})(\sqrt{a_{n}}-\sqrt{a_{n-1}})}
= \frac{\sqrt{a_{n}}-\sqrt{a_{n-1}}}{a_n-a_{n-1}}
= \frac{\sqrt{a_{n}}-\sqrt{a_{n-1}}}{r}
$$
(the trick of simplifying a fraction by multiplying numerator and denominator this way is called rationalization). Therefore, for every $N\geq 2$,
$$
\sum_{n=2}^N\frac{1}{\sqrt{a_{n}}+\sqrt{a_{n-1}}}
= \frac{1}{r} \sum_{n=2}^N (\sqrt{a_{n}}-\sqrt{a_{n-1}})
= \frac{1}{r} (\sqrt{a_{N}}-\sqrt{a_{1}})
$$
as we get a telescoping series. Can you conclude?


global namelist is not defined. Is only module variable

Question: Ok so using this code I ran some testing to see what the main problem was. I found there is a problem with the phone number input validation so i #'ed it ,so its inactive.(if your are able to fix that problem wil lgive you a sticker.
Anyway:
def main():

    name = []
    phone = []
    groupno = []
    score = []
    review = []

    q = input('Do you wish to Continue Y/N')
    while q != "Y":

        def data(name, phone, groupno, score, namelist, groupsizes,phonumber, mealscore):

            name =  input("Please enter the customer's name.")
        namelist.append(name)

        #phone = int(input("Please enter the customer's Phone Number."))
        #if len.str(phone) == 11:
        #    else: phone = int(input("Please enter the customer's Phone Number."))
        #phonumber.append(phone)

        sizeofgroup = int(input('Please enter the size of group: '))
        while sizeofgroup < 1 or sizeofgroup > 20:
            sizeofgroup = int(input('Please enter a valid group size: '))
        groupsizes.append(sizeofgroup)

        score = int(input('Please enter the rating of the meal: '))
        while score <= 1 or score >= 10:
            score = int(input('Please enter the rating of the meal- between 1 and 10: '))
        mealscore.append(score)

main()

And i get this error:

Do you wish to Continue Y/N?: y Traceback (most recent call last):
  File "\QRSTORAGE\SMCPupilData$\stirlim\Work\S5\Computing\Coursework
  Task\Program\code2.py", line 35, in  main() File
  "\QRSTORAGE\SMCPupilData$\stirlim\Work\S5\Computing\Coursework
  Task\Program\code2.py", line 16, in main namelist.append(name)
  NameError: global name 'namelist' is not defined

Not sure what the error means but ofc its something to do with declaration of variables
Answer: Because Python uses indentation for scoping, the assignment namelist has to be indented to line up with the assignment to name. Otherwise it is in the scope outside the function, and there is no variable called namelist there. A more helpful error message would be "line needs to be indented", but there's no way for Python to guess that.
Also, len.str(phone) fails because it tries to get the str attribute of len, and it hasn't got one. You mean len(str(phone)).
Comment: Thanks dude the namelist section works^^.Unfortunately the phone stuff does not atm but ty for trying ^^
Comment: Actually it is not about identation but about function definition. Python does not use identation for scoping. try to define a variable inside an if block: `if True: my_var=10; print(my_var)` will work ;)


backward selection but regression coefficients not significative?

Question: I'm running a logistic regression with backard selection method. I get coefficients with p-values>.10. Here's an example:
<code>    DF   Estimate   Error   Chi-Square  Pr > ChiSq  Estimate    Exp(Est)
Intercept   1   -30,32       11,48       6,97        0,01            -
v1  1    0,001       0,00        9,70        0,00        0,10        1,00
v2  1   -0,001       0,00        2,84        0,09       -0,07        1,00
v3  1    0,000       0,00        0,12        0,73        0,01        1,00
v4  1   -0,000       0,00        0,11        0,74       -0,01        1,00
v5  1   -0,000       0,00        0,74        0,39       -0,03        1,00
v6  1    0,000       0,00        0,58        0,45        0,02        1,00
v7  1   -0,005       0,00        3,98        0,05       -0,07        1,00
v8  1    0,002       0,01        0,04        0,84        0,01        1,00
v9  1   -0,016       0,05        0,09        0,76       -0,02        0,98
v10 1    0,014       0,03        0,29        0,59        0,03        1,01
v11 1    0,102       0,03        14,77       0,00        0,09        1,11
v12 1    0,009       0,01        1,27        0,26        0,05        1,01
v13 1   -0,017       0,01        2,39        0,12       -0,05        0,98
v14 1   -0,005       0,01        0,48        0,49       -0,03        1,00
</code>
My question is, if the algorithm selects best variables, how is it be possible that keeps the variables that have p-values greater than 0.1? I know that the effect is reflected in the value of the coefficient but the pvalue shows the probability that having that value in that coefficient is only a coincidence, and the coefficient is 0 (considering all the other variables). So why is still keeping those?
Comment: How were you doing the backwards elimination? What functions, what test statistic or selection method, AIC etc? How did you generate the table of "results" shown? These are important details.
Answer: Are you running this in R? If so R defaults the p-val to something, I am not quite sure but you can look it up in the help. Thus you can change what "significance" level you want to discard at. Backwards selection in my experience is usually not a good approach. Unless you are restricted to using backwards selection I would suggest using a different method of model selection.
Comment: Depends what you by "in R"? The default `step()` function doesn't explicitly use the $p$ value at all. Instead it uses AIC to do selection. That may well explain what the OP is seeing, as may other things. We need more details to answer this.


Maximizing $7x+12y$ over the set $2x^2+6xy+9y^2-2x-6y\le 24$

Question: By bounding the function, I need to find the maximum point of $7x+12y$ over the set $2x^2+6xy+9y^2-2x-6y\le 24$ (i.e., no Lagrange multipliers are allowed, etc.).
I am trying to show that $(7x+12y)^2\le C$ for a constant $C$. Then I will search for a point $(x_0,y_0)$ such that $7x_0+12y_0=\sqrt C$.
I did show that $(7x+12y)^2\le2944+18x^2+72xy$, but now I am stuck with $18x^2+72xy$.
Does anyone have some bright ideas? I am really stuck.
Comment: $7x+12y$ has constant gradient $(7,12)$. So, just keep swimming in that direction: $\max(t)$ such that $(7t,12t)$ satisfies the inequality.
Comment: @jyre The constraint is a shifted ellipse (not centered at the origin). Why is it going along the line through the origin makes the max at the intersection?
Answer: Inequality. Lagrange multiplier excluded.
$2x^2+6xy+9y^2-2x-6y\le 24$
$\implies x^2+(x+3y)-2x-6y^\le 24$
let $z=x+3y$, we have:
$x^2+z^2-2z\le24$
$\implies x^2+(z-1)^2\le25,$
which is a circle. And the function whose value is to maximized can be transformed to:
$7x+12y=7x+12\cdot\cfrac{z-x}{3}=3x+4z$,
let $c=3x+4z$, we have $z=\cfrac{-3x+c}{4}$, this is a line in xz plane with slope $-\cfrac 34$, and we want to maximize the y axis of the points of all lines with the given slope and intersect(or touch) to cirle. From the geometric interpretation of the problem, we know that the line pass the point on top-right  of the circle with direvative of -0.75. the value of $c$ associate with it, the maximum value required, can be arrived at accordingly.
Answer: Hint: complete the squares in the inequality to get $x^2+(3y+x-1)^2\le 25$, then change $y$ to $z=3y+x-1$ to maximize $3x+4z$ subject to $x^2+z^2\le 25$. Now the method in the comment @jyre works. Otherwise a parameterization of the circle and maximizing $3\cos\theta+4\sin\theta$ works as well.
Comment: Of course an ellipse is transformed into a circle under a change of coordinates and a linear map stays linear under this transformation. Tank you.


How to check if deleting Deployment will fail because of another resource without actually deleting it?

Question: Deleting deployment will fail if there's the resource in Deployment is used by another custom resource. I.e. Newly created Firewall linked to VPC deployment will prevent the deployment deletion process and therefore will causing error, with informative error message:

mynetwork has resource level errors

mynetwork:{"ResourceType":"compute.v1.network","ResourceErrorCode":"RESOURCE_IN_USE_BY_ANOTHER_RESOURCE","ResourceErrorMessage":"The network resource 'projects/myproject/global/networks/mynetwork' is already being used by 'projects/myproject/global/firewalls/mycustomfirewall'"}

To prevent this case, is there any way to get that kind of messages before actually deleting it?
Answer: In this link you will find how to list all deployments for a given project. By adding the parameters you can find in the documentation, you could retrieve information that may be useful to determine the use other resources in the deployment.
I also attach you the CLI command for have a better wrasp on its use.
Comment: Our system currently using that approach. By checking the most often used GCP resources and compare to deployments. But I'm afraid if user would add other type of GCP resources and linked to the network. This will cause above error.
Well that might be the worst case. I just hope there's an API from GCP that directly check resources dependencies


Suppose $a,b$ are real numbers and $0 < a < b$. Prove $ba^n + ab^n < a^{n+1} + b^{n+1}$

Question:
$a,b$ are real numbers and $0 < a < b$
Prove that for all $n ≥ 1$, $ba^n + ab^n < a^{n+1} + b^{n+1}$

My attempt:
By contradiction. Suppose
$$\tag{* }ba^n + ab^n ≥ a^{n+1} + b^{n+1}$$
Rearranging $(*)$ gives
$$\begin{align}
0 & ≥ a^{n+1} + b^{n+1} - ba^n - ab^n \\
  & ≥ a^{n+1} - ba^n + b^{n+1} - ab^n \\
  & ≥ a^n(a - b) - b^{n}(a - b) \\
  & ≥ (a - b)(a^n - b^n)
\end{align}$$
But since $0 < a < b$, we have $(a-b) < 0$ and $(a^n - b^n) < 0$, and thus  $(a-b)(a^n - b^n) > 0$.
Hence a contradiction. $\Box$

Is it correct?
Is there a better way? (Preferably direct proof)
Answer: Yes, it is correct. But it is more natural to apply the same idea to get a direct proof:$$a^{n+1}+b^{n+1}-ba^n-ab^n=(b^n-a^n)(b-a)>0.$$
Answer: According to the Rearrangement inequality:
$$0<a<b \Rightarrow 0<a^n<b^n\\
ba^n + ab^n < b\cdot b^n +a\cdot a^n=a^{n+1} + b^{n+1}.$$
Comment: second step is not clear


Attaching libraries to specific controllers

Question: I want to include the google charts js library to a specific (or set of) controller(s).  In my library file, gcharts.libraries.yml, I have the following:
google_charts:
  remote: https://developers.google.com/chart
  version: current
  license:
    name: apache 2.0
    url: http://www.apache.org/licenses/LICENSE-2.0
    gpl-compatible: true
  js:
    https://www.gstatic.com/charts/loader.js: { type: external, minified: true }
  dependencies:
    - core/jquery

Which, unless I copied something incorrectly, should be correct.
Question 1: is the dependencies tag allowed here?  The documentation isn't expressly clear on that.

My controller (GoogleChartsController) correctly instantiates and looks like:
<?php
array(
  '#theme' => 'custom_theme',
  '#attached' =>
    array(
      'library' =>
        array('company/google_charts')
    ),
  // For testing purposes
  '#cache' => array(
    'max_age' => 0,
  )
);
?>

However, when I look through the source I don't see the library that I told my controller has a dependency for.  My library never loads.
Question 2: Do I have have to use the hook_page_attachement or the hook_preprocess_page hooks?  If so, how do I limit it to use just my set of controllers I want (I don't need or want this loading on every page)?  Can I get the path, check to see that it is what I want and then add it conditionally, like so?  Or is there some other way?

My custom-theme.html.twig looks like:

Are we here?

The documentation isn't crystal clear as to when and where to include inline js.  From the google charts api, I'm to include something like:

Now, my intuition is that I can actually abstract each of the charts I want into their own "library" and add the dependency, because of the way I designed things, this will be fairly trivial.  But I'm not certain if this is the best way to do it.  But I've read that you can dump inline js into twig files; but I'm not 100% certain this applies here...
Question 3: Is adding the js into twig best practices or is libraries the way to go?  Assuming libraries, can I include several libraries into one library file and just include the one(s) that I want/need?  So I would have one library for customized_charts.libraries.yml and in there there would be declarations for pie_chart, bar_chart, etc.  And then I would load module/bar_chart when I wanted to display bar charts, etc?
Comment: Please show the route definition and the full controller callback.
Answer: You are not indenting parts of the yml file that you need to indent.
Look at this example from token.libraries.yml at /modules/contrib/token/token.libraries.yml:
jquery.treeTable:
  remote: 'http://plugins.jquery.com/treetable/'
  version: 3.2.0
  license:
    name: MIT
    url: https://github.com/ludo/jquery-treetable/blob/3.2.0/MIT-LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery.treetable.js: {}
  css:
    component:
      css/jquery.treetable.css: {}
      css/token.treetable.theme.css: {}
  dependencies:
    - core/jquery

Also, pay attention to colons, since they are part of YAML syntax.
use:
remote: 'remote: https://developers.google.com/chart'

not
remote: remote: https://developers.google.com/chart

Comment: I was going to say the same, but I ran it through an online YAML linter and it said it was okay.
Comment: That's because it's valid YAML, but it won't be parsed in the correct way, each row will be a separate array, instead of all being part of the same array.
Comment: ...smh, that is just an error in translation.  My actual `gcharts.libraries.yml` has the correct indentation.  I just mistyped the number of spaces.
Answer: To answer two of your questions:

Question 2: Do I have have to use the hook_page_attachement or the
  hook_preprocess_page hooks?

No, you can attach libraries to a controller.

Question 3: Is adding the js into twig best practices or is libraries
  the way to go?

It's not a good practice to add JS into a template. It should be added to whichever render array represents the data the script belongs to.
Comment: Yes, I discovered last night, that I was misinterpreting the documentation.  I didn't realized that it was `module_name.libraries.yml`.  I thought it was just `library_name.libraries.yml`.  I have it attaching to my render array in my controller just fine now.  As for #3: I have several different chart types, does it makes sense to just build a library for each of those and include them as needed?  That brings a whole host of other challenges, but it seems that it is the best Drupal compatible approach...
Comment: Yes, you'll want to build libraries for each of your chart types.


Tell subroutine that a CAAnimation has finished

Question: I have an instance method that will perform animation of a UIView on its shadowOpacity property forever(never stop).
So I just put the animation codes into a while loop. But the problem is that, the subroutine loop can not start until previous animation has finished.
Here I just make a simple sleep(0.5) system call. It certainly left some display problems.
My question is how to implement an NO-TIME-GAP repeat animation here?
- (void)animateShadowRepeatly
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowOpacity"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        while (YES) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                animation.duration = 0.5;
                if (_actionTarget2.layer.shadowOpacity <= 0.1) {
                    animation.fromValue = [NSNumber numberWithFloat:0.0];
                    animation.toValue = [NSNumber numberWithFloat:1.0];
                    _actionTarget2.layer.shadowOpacity = 1.0;
                } else {
                    animation.fromValue = [NSNumber numberWithFloat:1.0];
                    animation.toValue = [NSNumber numberWithFloat:0.0];
                    _actionTarget2.layer.shadowOpacity = 0.0;
                }
                [_actionTarget2.layer addAnimation:animation forKey:@"shadowOpacity"];
            });
            sleep(0.5);//here I must pasuse the while loop until animation on actionTarget2 finished.I think sleep(0.5) here is not a good implement,How to make an elegant implement for the dependency on animation purpose?
         }
    });
}

Answer: No, you can't do that. The sleep will prevent the animation from starting, since it blocks the main thread. And you can't run animations on a background thread.
What you want to do is set yourself up as the delegate of the animation and add a completion method. Then in the completion method you trigger the next animation.
I wrote a post here on SO That explains how to add a completion block to your animation and trigger THAT when the animation finishes. Check out this link.
Comment: thanks for your help.  I create a delegate method for receiving this event and inside it I make a call [self animateShadowRepeatly]. It works as my expectation.


Managing suspended/dehydrated instances when redeploying orchestrations

Question: Scenario:
A biztalk application is deployed with a receive port, orchestration and send port. Messages flow correctly.
At some point, a bug is found in the orchestration, causing messages to suspend. The orchestration must be fixed and redeployed.
Question:
Because you can't redploy an orchestration with suspended instances, how would you go about retaining those messages, terminating the instances, redeploying and then resending those messages through the fixed orchestration?  Is there a process or tool for this?
Answer: If the bug doesn`t require major modification - i.e no new orchestrations, no new schemas, no new promoted fields etc, then a short term 'hack' is possible, viz by simply reinstalling the fixed MSIs (and GAC) on your servers, and restarting the host instances (using NLB if applicable) (i.e. without importing the MSI's into BizTalk).
You should then be able to resume any suspended (resumable) orchs. Then schedule some downtime at a less busy time, put your app into partially stopped to prevent new orchs starting, wait for all running orchs to complete, and then import the fixed MSI (consider bumping up the buggy orch assembly version with the hotfix)
Building a custom tool with the ability to audit all messages going in and out of Biztalk is useful, so you can replay them. This will allow you to terminate orchs, reinstall, and then replay.
Comment: @Jeremy AFAIK you will still need to write the tool yourself, however, this is fairly simple - [Thiago's blog](http://connectedthoughts.wordpress.com/2008/04/02/3-ways-of-programatically-extracting-a-message-body-from-the-biztalk-tracking-database/) discusses different ways extracting tracked messages from DtaDB or archive (they are compressed and large messages are sharded). FWIW we use the SQL version on DtaTB  before they get purged.
Comment: Thanks,  will try this.  The custome tool you speak of, would that be a tool specific to the biztalk application, or would that be general to BizTalk itself?
Answer: You can as well fix the orchstration and while building it, increment the version of the assembly. This way you can have parallel deployment of the orchestrations. You can unenlist the existing one after deploying the newer versioned orchstration.


Color at Certain Pixel location inside Java Applet?

Question: I am currently making a paint like program with Java Applets. I want to simulate a bucket tool by using recursion and checking each pixel around a given point, however I am having trouble getting the RGB value at a given pixel.
Is there a way to do something such as
public void paint(Graphics g) {
    g.getPixelAt(X, Y);
}

Or something?
Answer: Graphics is virtual concept and does not support what you are trying to do
What you need to do is paint to a surface that you can interact with, something like a BufferedImage.
The basic idea would be painting all effects to this buffered image and using Graphihcs#drawImage to actually render the image to the screen.
From there you can us BufferedImage#getRaster which will provide you with a WritableRaster object which has get/setPixel methods.
Answer: You could use Applet.getLocationOnScreen() and java.awt.Robot.createScreenCapture() to find and capture the part of the applet you want.
This question poses a similar problem.


Convert .doc with images to .html using xdocreport

Question: i am converting doc to html using following code
private static final String docName = "This is a test page.docx";
private static final String outputlFolderPath = "C://";
String htmlNamePath = "docHtml1.html";
String zipName="_tmp.zip";
static File docFile = new File(outputlFolderPath+docName);
File zipFile = new File(zipName);

public void ConvertWordToHtml() {
    try {
        InputStream doc = new FileInputStream(new File(outputlFolderPath+docName));
        System.out.println("InputStream"+doc);
        XWPFDocument document = new XWPFDocument(doc);
        XHTMLOptions options = XHTMLOptions.create(); //.URIResolver(new FileURIResolver(new File("word/media")));;
        String root = "target";
        File imageFolder = new File( root + "/images/" + doc );
        options.setExtractor( new FileImageExtractor( imageFolder ) );
        options.URIResolver( new FileURIResolver( imageFolder ) );
        OutputStream out = new FileOutputStream(new File(htmlPath()));
        XHTMLConverter.getInstance().convert(document, out, options);
    } catch (Exception ex) {

    }
}

public static void main(String[] args) throws IOException, ParserConfigurationException, Exception {
    Convertion cwoWord=new Convertion();
    cwoWord.ConvertWordToHtml();

}

public String htmlPath(){
    return outputlFolderPath+htmlNamePath;
}

public String zipPath(){
    // d:/_tmp.zip
    return outputlFolderPath+zipName;
}

Above code is converting doc to html fine. Issue comes when i try to convert a doc file which has graphics
like circle (shown in screenshot), In this case, graphics doesn't show into html file.

Please help me out how can we maintain graphics from doc to html file as well after conversion. Thanks in Advance
Comment: Did you take a look at http://stackoverflow.com/questions/37745615/org-apache-poi-xwpf-converter-xhtml-xhtmlconverter-not-generating-images, but in general please note that this functionality is not provided by Apache POI, but rather https://github.com/opensagres/xdocreport, unfortunately they use the org.apache namespace which they should not!
Comment: @centic:Thanks for reply,i have already looked at given link,i am able to convert images inside doc, but not the graphics which is attached above
Answer: You can embed the images in the html by using the following code:
Base64ImageExtractor imageExtractor = new Base64ImageExtractor();
options.setExtractor(imageExtractor);
options.URIResolver(imageExtractor);

where Base64ImageExtractor looks like:
public class Base64ImageExtractor implements IImageExtractor, IURIResolver {

    private byte[] picture;

    public void extract(String imagePath, byte[] imageData) throws IOException {
        this.picture = imageData;
    }

    private static final String EMBED_IMG_SRC_PREFIX = "data:;base64,";

    public String resolve(String uri) {
        StringBuilder sb = new StringBuilder(picture.length + EMBED_IMG_SRC_PREFIX.length())
                .append(EMBED_IMG_SRC_PREFIX)
                .append(Base64Utility.encode(picture));
        return sb.toString();
    }
}


React and Websocket messaging to server

Question: So I'm having issues with a single component that displays a list pulled from a resource server. Then it uses Stompjs to establish a websocket and send messages. When I load the client, the Dev Console shows logs that it tries to call onConnected method() twice as my logs show two newUser messages sent from a single load of the component.
When I try to call the submitBid() method it throws a type error saying that
"TypeError: Cannot read properties of undefined (reading 'send')
at submitBid (AuctionList.js:76:1)"
Which I'm not sure why it would be undefined on that line when it's defined and running fine in the function on line 36 which runs before the method that fails. I've been stuck on this for several days so hopefully someone can tell me what I've got wrong in the code... Here is the component code....
import React from 'react'
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
import {useState, useEffect } from 'react';

function AuctionList({user, authCredentials, token}) {

 const [auctionItems, setAuctionItems] = useState([]);

 const [userData, setUserData] = useState({
                                            email: user.email,
                                            name: user.name,
                                            message: ''
                                          });

  const [bid, setBid] = useState(0.00);

  let stompClient;
  let socket;

const connect = async () => {
      socket = new SockJS('http://localhost:8080/ws')
      stompClient = Stomp.over(socket)
      stompClient.connect({}, onConnected, onError)
}

const onConnected = async () => {

  stompClient.subscribe('/topic/bids', onMessageReceived)

  stompClient.send("/app/socket.newUser",
      {},
      JSON.stringify({
          sender: user.name,
          type: 'NEW_USER',
          time: Date.now()
      })
  )
}

const onError = async (err) => {
  console.log(err);

}

const handleChange = async (e) =>{
  setBid(e.target.value);
}

const submitBid =  async (item) => {

  let newMessage = {
                type: "BID",
                newBid: {
                        itemId: item.id,
                        email: user.email,
                        bidPrice: bid,
                        bidTime: new Date().getTime()
                       },
                sender: userData.email,
                time: new Date().getTime()
      };

            try {
              stompClient.send("/socket.send", {}, JSON.stringify(newMessage));
            } catch(err){
              console.log(err); }
}

const onMessageReceived = async (payload)=>{
  console.log("onMessageReceived")
  console.log(payload)
}

const getAuctionList = async () => {

    const url = "http://localhost:8080/auctionlist";

    const init = {
      method: "GET",
        headers: {
            'Content-type': 'application/json',
            'Authorization': `Bearer ${token}`, // notice the Bearer before your token
        },
    };

    fetch(url, init)
    .then(response => response.json())
    .then(response => {setAuctionItems(response)})
};

useEffect( () => {
  getAuctionList();
  connect();
}, []);

return (

        {auctionItems.map( item =>  {
          return(

{item.name}

                {item.desc}
                Current Bid: ${item.itemStartingPrice}
                Minimum Bid: {item.itemMinBid}
                Time left

                <input type="number" id="bidInput_" name="bidInput" onChange={handleChange} ></input>
                <button type='submit' onClick={submitBid}>Submit bid</button>

)

        })}

  )
}

export default AuctionList

Also I realize I have a bunch of async functions that don't have any awaits. I tried adding those in, but it was no change.
Answer: The issue here is not with stompjs but with the scoping. You have stompClient inside React Component but the one from submitBid is different. You can do it in different ways.

Put stompjs in global stage as in example here: https://playcode.io/972045

You can use useRef to have the client inside the React Component and have React do the tracking of any modifications.

I personally think something like a "connection" should stay away from inside a React Component. You should have the connection configs in a different file and import an instance to the JSX file.

React and Websocket messaging to server


Ajax returning object instead of data

Question: What is the correct way to handle Ajax success callback events using jquery?
In my code, when I run instead of displaying data, it alerts object:object. However, if I use say msg.box it returns the data correctly.
I am trying to create an if statement where if text equals a certain word then the variable from json is placed in the html of the result div BA_addbox.
I cannot seem to get this to work and would be grateful if someone could point out my error. I have only included the relevant code as the form is posting the correct data and the php code is catching all the posts. Many thanks.
ajax code
$.ajax({
    type: "POST",
    url: "/domain/admin/requests/boxes/boxesadd.php",
    data: formdata,
    dataType: 'json',
    success: function(msg){
        if(msg == "You need to input a box") {
            $("#BA_addbox").html(msg.boxerrortext);
        }
        else {
            $("#BA_addbox").html(msg.box);
        }

        //alert(msg);
        console.log(msg);
        //$("#BA_addbox").html(msg.box);

        //$("#formImage .col_1 li").show();
        //$("#BA_boxform").get(0).reset();
        //$("#boxaddform").hide();
    }
});

boxesadd.php
$box = mysql_real_escape_string($_POST['BA_box']);
$boxerrortext = "You need to input a box";

if (isset($_POST['submit']))    {
    if (!empty($box)) {

        $form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised, 'submit'=>$submit);

        $result = json_encode($form);

        echo $result;

    }
    else
    {

        $error = array('boxerrortext'=>$boxerrortext);

        $output = json_encode($error);

        echo $output;
        //echo "You need to input a box";

    }
}

Comment: your msg in json format, you cant compare object to a string.
Comment: the object IS your data.
Answer: In javascript associative arrays are called objects, so there's no bug in the transmitted data.
Why do you compare msg to "You need to input a box"? You cannot compare object and string, this makes no sense.
if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
    $("#BA_addbox").html(msg.boxerrortext);
} else {
    $("#BA_addbox").html(msg.box);
}

Answer: Try this instead:
if(msg.boxerrortext) {
  $("#BA_addbox").html(msg.boxerrortext);
}
else {
  $("#BA_addbox").html(msg.box);
}

Hope this will help !!
Comment: `msg.boxerrortext` won't always exsist, you need to account for that

Ajax returning object instead of data


Baud rate in PIC18F4550

Question: for computing the baud rate for PIC18F4550, the following equation is used:
Baud = F_OSC/(4 * (SSPADD + 1))  ---------- eq.1
according to the data sheet:
SSPADD = 10 for 400k Baud at 20Mhz Fosc.
But by substituting the parameters into equation (1), the SSPADD will equal 11.5
so how is SSPADD = 10?
Comment: If this equation is correct you're right that 11 is closer to 400k...
Answer: Give this utility a shot. I came across it across it on microchip's forums while trying to get my dsPIC33f's uart working and it made my life much easier.
http://www.micromagicsystems.com/#/pic-baud/4523812801
Hopefully it will work with the particular chip you are using (it looks like it supports *16, *17, *18 and *24 PICs, in addition to the dsPICs).

Baud rate in PIC18F4550


Adicionar atributo a um elemento

Question: Em JavaScript podemos adicionar os atributos a determinado elemento com pelo menos duas maneiras:
var div = document.createElement('div');
div.id = 'meuId';

ou
var div = document.createElement('div');
div.setAttribute('id', 'meuId');

Existe alguma diferença em termos de desempenho e/ou compatibilidades entre navegadores, ou qualquer uma das formas serve perfeitamente?
Comment: tem um comparativo no jsperf: http://jsperf.com/setattribute-vs-property-assignment/7. Em termos de desempenho o acesso direto é mais rápido.
Answer: TL;DR
Os elementos HTML têm atributos. Quando representamos esses em JavaScript obtemos objetos com propriedades.

.setAttribute muda no HTML, é mais lento e cego
.prop muda diretamente no objeto do DOM, mais rápido

Partindo deste HTML:
<input type="text" value="Escreve o teu nome" />

Se eu escrever o meu nome nesse input, e fôr buscar o seu valor atual via JavaScript, repara no que obtenho:
input.value = 'Sérgio';
input.value;  // dá "Sérgio"
input.getAttribute('value'); // dá "Escreve o teu nome"

Ou seja o .getAttribute vai buscar a informação ao HTML que é estático, e não ao objeto do DOM que já mudou de valor.
Usar o setAttribute vai mudar o atributo do HTML e tem nalguns casos efeitos diferentes. Por exemplo input.setAttribute("disabled", false); vai fazer o contrário do esperado, vai bloquear o elemento enquanto que input.disabled = false; vai fazer o que é esperado.. Isto porque o browser detecta a presença do atributo disabled e não lê o valor desse atributo (só a sua presença). Mudando a propriedade .disabled muda diretamente o comportamento no elemento.
Um outro exemplo clarifica a diferença entre HTML e a representação no JavaScript do que se passa no DOM:
var input = document.querySelector('input');
input.setAttribute('dataA', 'foo');
console.log(1, input.dataA, input.parentNode.innerHTML);
// dá: 1 undefined "<input type="text" value="Escreve o teu nome" dataa="foo">"

input.dataB = 'foo';
console.log(2, input.dataB, input.parentNode.innerHTML);
// dá 2 "foo" "<input type="text" value="Escreve o teu nome" dataa="foo">

No primeiro caso o elemento HTML recebe um novo atributo dataa e não dataA pois o setAttribute é case-insensitive e o valor "setado" não é retornado por input.dataA, nem input.dataa.
No segundo caso o .dataB é adicionado como nova propriedade do objeto no JavaScript mas não é reproduzido no HTML. Fica somente do lado do JavaScript e não é escrito no HTML.
É boa prática alterar a propriedade diretamente e não misturar os dois no código pois pode gerar bugs bem dificeis de detetar.

À parte dos erros que podem ser gerados por setAttribute aceder à propriedade do objeto que representa o elemento do DOM é também mais rápido.
Comment: gostei dos exemplos `input.getAttribute('value')` e `input.setAttribute("disabled", false)`, realmente é bem bizarro,
Answer: O .setAttribute() possui problemas com compatibilidade com o IE até a versão 8.
Quanto a desempenho, segundo o teste no JSPerf, o acesso direto a propriedade é mais rapido.
Opera 28.0.1750.40
obj.title = 'This is a test';                 //1,096,233 ops/sec
obj.setAttribute('title', 'This is a test');  //  678,908 ops/sec
obj.custom = 'This is a test';                //  270,003 ops/sec
obj.setAttribute('custom', 'This is a test'); //  146,522 ops/sec
obj.dataset['custom'] = 'This is a test';     //   85,083 ops/sec

Adicionar atributo a um elemento


$L=p(x)y''+q(x)y'+r(x)$. Show that $ \overline{\overline{L}}=L $

Question:
Let $L$ be the linear operator defined by $$L[y]=p(x) \frac{d^2 y}{dx^2}+q(x) \frac{dy}{dx} + r(x) y .$$
  Define the adjoint linear operator $\bar{L}$ and hence show that $\overline{\overline{L}}=L$.

What I have already done is I calculated
$$\overline{L}=p(x)\frac{d^2 y}{dx^2}+(2 q'(x)-q(x))\frac{dy}{dx}+(p''(x)-q'(x)+r(x))y$$
When I calculated $\overline{\overline{L}}$ I got
$$\overline{L}=p(x)\frac{d^2 y}{dx^2}+(2p'(x)-2''q(x)+q(x))\frac{dy}{dx}+(2p''(x)-2p'''(x)+r(x))y$$
It was not said in the question to show that if $L$ is a self-adjoint operator then show that $\overline{\overline{L}}=L$. Any ideas?
Answer: By definition of the adjoint,
$$\langle L[y], f\rangle = \langle y, \overline{L}[f]\rangle$$
for all appropriate $f$. Then by integration by parts (assuming your functions and their derivatives have the right boundary conditions...)
$$\langle y, \overline{L}[f]\rangle = \left\langle y, \left((-1)^2 \frac{d^2}{dx^2}p(x) - \frac{d}{dx}q(x) + r(x)\right)f\right\rangle.$$
Doing product rules..
$$\overline{L}[f](x) = p''(x) f(x) + 2 p'(x) \frac{d}{dx} f(x) + p(x)\frac{d^2}{dx^2}f(x) - q'(x)f(x) - q(x) \frac{df}{dx} + r(x) f(x). $$
This gives
$$\overline{L}[f](x) = p(x)\frac{d^2}{dx^2}f + (2 p'(x) - q(x)) \frac{df}{dx} + (r(x) - q'(x) + p''(x))f(x).$$
It seems your mistake was in the first derivative term. You should have $2p'(x)$ - not $2q'(x)$. You also have one too many derivatives for $p$ in the last term in $\overline{\overline{L}}$.