Stochastic Processes

Question: I have a couple questions about stochastic processes. My professor didn't really give in depth explanations and non of his lecture slides do much explaining either.
Say S(x) is a stochastic variable whose properties depend on a 2-dimensional stochastic field. I know that this this is second order stationary if the mean stays constant over time and the variance does not depend on time (though may depend on lag). I understand that isotropy is the lack of a preferred direction over time, but what is the mathematical statement of the isotropic conditions?
The other question I have is given two processes:
$x_t = .1*x_{t-1} + \epsilon$ where epsilon is white noise ($\epsilon \sim N(0,1^2)$ and
$y_t = x_t^2$
What is the correlation between the two? I get that correlation is $E[(y_t - E[y_t] \cdot (x_t - E[x_t])]$, but every time I try to solve it I end up with 0 which doesn't make sense.
Comment: I understand both of these questions now. Not deleting since Aksakal helped me understand the second part.
Answer: Think of this: no matter what is $x_{t-1}$, $x_t$ will tend to be smaller in absolute value. So regardless of $x_0$, expectation of $x_t$ must be collapsing to 0.
Correlation of $x$ and $y$ is proportional to $E[xy]-E[x]E[y]=E[xy]=E[x^3]$. You know that $E[x\varepsilon]=0$, so $E[x^3]$ must be the skewness of the normal distribution.
Comment: Yeah, I knew $E(x_t)$ was tending to 0, assuming there were enough observations. And since the skewness of the normal distribution is 0, the correlation is 0? edit: Ah. This makes sense, sorry I was thinking about a linear pattern, not an AR(1) pattern. I get that correlation is 0 now. Thanks!

Stochastic Processes


Convergence or divergence of the sum series with $\sum_{n\ge 1} \frac{(1-2^{1/n})^6}{(n+3)^p}$, $p\in \Bbb R$

Question: I am stuck on finding the convergence or divergence of $$\sum_{n=1}^{\infty} \frac{(1-2^{1/n})^6}{(n+3)^p}$$ depending on p with p being in R. I tried to compare it and say its general term is smaller than $$\frac{1}{{(n+3)^p}}$$ and then consider that $$\frac{1}{{(n+3)^p}}$$ is convergent for ( p > 1 ) (comparing it with a harmonic series), so the given series is convergent for ( p > 1 ).
I attempted to use the logarithmic criterion to prove that $$\sum_{n=1}^{\infty} (1-2^{1/n})^6$$ is divergent (I don t think I calculated the limit correctly). Then, using the limit comparison test with $$(1-2^{1/n})^6$$, I obtained that the given series is divergent for ( p <= 0 ).
I think that my approach is flawed since I still haven't determined the nature of the series for ( 0 < p <= 1 ).
Answer: lets use integral test
$$ \int_1^\infty \frac{(1-2^\frac{1}{x})^6}{(x+3)^p} dx$$
put $y=\frac{1}{x}$ then we get the integral
$$ \int_0^1 \frac{y^{p-2}}{(3y+1)^p} (1-2^y)^6 dy=\int_0^1 \frac{y^{p+4}}{(3y+1)^p} \left(\frac{1-2^y}{y}\right)^6 dy $$
for the function
$$f(y)=\frac{y^{p+4}}{(3y+1)^p} \left(\frac{1-2^y}{y}\right)^6  $$
its defined for $y\in(0,1]$  and $\lim_{y \to 0} f(y)$ does exist only if $p>-4$
for that the integral is converge for $p+1>-4$ So the series converge for $p>-5$
Answer: For $n\geq1$, it can be shown by Maclaurin series of $2^x$ that$\frac{\ln2}n<2^{\frac1n}-1<\frac{2\ln2}n$. Therefore the given series has the same character of the series $\sum_{n=1}^{\infty}\frac1{n^6(n+3)^p}$. İt converges for $p+6>1$.


Is every multiplicative function from the matrix ring $\text{Mat}_n(R)$ to $R$ a function of $\text{det}$?

Question: Suppose that $R$ is a commutative ring with $1$, and for $n \in \mathbb{N}$, let $\text{Mat}_n(R)$ be the set of $n \times n$ matrices with entries in $R$.
It is well known that the determinant function $\text{det} : \text{Mat}_n(R) \rightarrow R$ is multiplicative, i.e.
$$
\text{det}(AB) = \text{det}(A) \text{det}(B)
$$
$\text{det}$ is certainly not unique in this respect; there are lots of functions $g : \text{Mat}_n(R) \rightarrow R$ which are multiplicative. For a start, there are the constant $1$ and constant $0$ functions, as well as the indicator function of "is invertible". More strangely, for $R = \mathbb{R}$, are the functions
$$
g(A) =
\begin{cases}
e^{f(\log(\left|\det(A)\right|))} &\text{if} \det(A) \neq 0 \\
0 &\text{if} \det(A) = 0
\end{cases}
$$
where $f : \mathbb{R} \rightarrow \mathbb{R}$ is any solution of the Cauchy functional equation $f(x+y) = f(x)+f(y)$ : non-continuous solutions to this equation are really badly behaved.
However, I have not found any examples of multiplicative functions which are not themselves a function of $\det$.
Is there any such function which is not a function of det?
That is, is there a ring $R$, an $n \in \mathbb{N}$ and $g : \text{Mat}_n(R) \rightarrow R$ which is multiplicative, and not a function of det, i.e. there exist $A,B \in \text{Mat}_n(R)$ such that
$$
\begin{align}
\det(A) &= \det(B) \\
g(A) &\neq g(B)
\end{align}
$$
Comment: Here's one observation. If you restrict your multiplicative function to $\mathrm{GL}_n(R)$ you get a group map $\mathrm{GL}_n(R)\to R^\times$. If you assume further that $R$ is a field with at least three element then this follows from the fact that the derived subgroup of $\mathrm{GL}_n(R)$ is $\mathrm{SL}_n(R)$.
Comment: @AlexYoucis, good point, however, I don't think the OP asks for $g(Id)$ to be $1$ so we might not get a group map... The only thing we know is that $g(Id)^2=g(Id)$ (it could be $4$ if we are working modulo $6$ for instance).
Comment: It's still fine with the assumption that $R$ is a field, though.
Answer: Suppose $R$ satisfies the following conditions.

$R$ has an element $x\neq 1$ with $x^2=1$.
There is a surjective ring homomorphism $q:R\to\mathbb{F}_2$.

For example, $R=\mathbb{Z}$ and $x=-1$, or $R=S\times\mathbb{F}_2$ where $S$ has an element $s$ of multiplicative order $2$, and $x=(s,1)$.
Then $q$ induces a ring homomorphism $\text{Mat}_2(R)\to\text{Mat}_2(\mathbb{F}_2)$,
which I'll also denote by $q$.
An element $X$ of $\text{GL}_2(\mathbb{F}_2)$ acts on the three non-zero vectors of $\mathbb{F}_2^2$, and I'll say $X$ is even or odd depending on whether it acts by an even or odd permutation.
There is a multiplicative function $g:\text{Mat}_2(R)\to R$ with
$$g(A)=
\begin{cases}
0&\mbox{if $q(A)$ is not invertible}\\
1&\mbox{if $q(A)$ is invertible and even}\\
x&\mbox{if $q(A)$ is invertible and odd.}
\end{cases}$$
But $g(A)$ is not a function of $\det(A)$, since for $A_1=\begin{pmatrix}1&0\\0&1\end{pmatrix}$ and $A_2=\begin{pmatrix}1&1\\0&1\end{pmatrix}$, $\det(A_1)=\det(A_2)$ but $g(A_1)=1\neq x=g(A_2)$.
Comment: @SamCappleman-Lynes By the way, I think the example I've given is about the simplest, but it's very specific to $n=2$. There are more interesting and sophisticated examples based on calculations in algebraic $K$-theory (about which I'm far from an expert). For example, a famous example is $R=\mathbb{R}[x,y]/(x^2+y^2-1)$, whose "reduced Whitehead group" $SK_1(R)$ is known to be cyclic of order $2$. It turns out that this implies that for any $n>1$ there's a multiplicative function of the kind you're asking about, taking values of $0$ (for non-invertible matrices), $1$ and $-1$.
Comment: Wonderful, intuitive example!


Asymptotic order of the convergence $\lim_{n\to\infty}\left(1-\frac{x}{n}\right)^n$

Question: For $x>0$ and $n\in\mathbb{N}$, we have
$$
\lim_{n\to\infty}\left(1-\frac{x}{n}\right)^n=e^{-x}.
$$
I would like to study the asymptotic order of the convergence. By a Taylor expansion, I think
$$
\left(1-\frac{x}{n}\right)^n=e^{-x}+\mathcal{O}\left(\frac{x}{n}\right)^{2n}\;\mbox{as}\;n\to\infty.
$$
Does anyone please give me some help or hints (or references)? Thanks so much!
Answer: Consider
$$a_n=\left(1-\frac{x}{n}\right)^n\implies \log(a_n)=n \log\left(1-\frac{x}{n}\right)$$ Using Taylor expansion
$$\log(a_n)=n\left(-\frac{x}{n}-\frac{x^2}{2 n^2}-\frac{x^3}{3n^3}+O\left(\frac{1}{n^4}\right)\right)=-x-\frac{x^2}{2 n}-\frac{x^3}{3n^2}+O\left(\frac{1}{n^3}\right)$$
Continue with Taylor
$$a_n=e^{\log(a_n)}=e^{-x}-e^{-x}\frac{ x^2}{2 n}+e^{-x}\frac{ x^3 (3 x-8)}{24
   n^2}+\cdots$$
Comment: Thanks for your help.
Answer: We have that
$$\left(1-\frac{x}{n}\right)^n=e^{n\log\left(1-\frac{x}{n}\right)}$$
then use Taylor's expansion

$\log(1-t)=t-\frac12t^2+O(t^3)$ as $t =\frac x n\to 0$

and therefore
$$e^{n\log\left(1-\frac{x}{n}\right)}=e^{n\left(-\frac xn-\frac12 \frac {x^2}{n^2}+O\left(\frac1{n^3}\right)\right)}=e^{-x}\cdot e^{-\frac12 \frac {x^2}{n}+O\left(\frac1{n^2}\right)}=e^{-x}\left(1-\frac12 \frac {x^2}{n}+O\left(\frac1{n^2}\right)\right)$$
that is
$$\left(1-\frac{x}{n}\right)^n=e^{-x}-e^{-x}\frac12 \frac {x^2}{n}+O\left(\frac1{n^2}\right)$$


How to upload large files using SAPUI5 FileUploader

Question: I am using the FileUploader in SAP WEB IDE to upload text files to SAP back end database through OData Services.
I am able to upload small files with size around 10-20 KB but my requirement is to be able to upload files with size 100-150 MB.
Code for FileUploader in controller:
var oFileUploader = this.getView().byId("fileUploader1");

oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
    name: "slug",
    value: oFileUploader.getValue()
}));

oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
    name: "x-csrf-token",
    value: data
}));

oFileUploader.setSendXHR(true);
oFileUploader.setUploadUrl(serviceUrl);
oFileUploader.upload();

alert("Upload Successful");

Code for XML View:
<Page title="{i18n>appDescription}" showNavButton="true" navButtonPress="onNavBack">

    <Button
        text="Upload File"
        press="handleUploadPress" />
</Page>

For some time I see the status as pending and then failed: ERR_CONNECTION_RESET in the Network tab of browser console.
Note: I am able to upload same 101 MB text file into SAP back end system directly.
Comment: I have tried directly uploading the file into gateway, initially it was also not taking the file but later when we increased the memory for it, then it was successfully uploading the TEXT file. I'll check for timeout settings and update.
Comment: @SunilBN I am able to upload files upto 100MB but not beyond that. I have asked the BASIS team to look into link you have mentioned. They have made some changes but still not able to upload bigger files, so i have found a workaround by zipping the file and sending.
Comment: are you using netweaver gateway to connect to backend? if yes, check https://help.sap.com/saphelp_nw73ehp1/helpdata/en/48/ad5afa8bc96744e10000000a421937/content.htm
Comment: @SunilBN I am using OData Services to connect to Netweaver Gateway from SAP webide.
Comment: Netweaver Gateway will have timeout setting for calls.. so check the timeout parameters as mentioned in the above link..
Comment: Did you try from gateway client? if that works, then I am sure its some settings in Gateway system.. http://help.sap.com/saphelp_nw73ehp1/helpdata/en/48/ad76299eff35b7e10000000a42189d/content.htm
Comment: @MatthiasGünter No i couldn't solved the problem, but found two solutions, first compress the files, it reduces the size to a great extent. Second we split the file into smaller files then uploaded using macro written in excel. I used the first solution to compress and upload.
Answer: There is a default limitation of 102400 KB on the HTTP server-side.
The limitation can be checked and changed through SMICM > go to Parameters.
Check the SAP official document before some changes :
https://help.sap.com/docs/SAP_NETWEAVER_731/0c333adb55cd4dbf8e92a5175703224c/483e87b3ca6b72d0e10000000a42189c.html?locale=en-US&version=7.31.25


I can't hide the window in MVVM

Question: I have the startup window in a WPF application, and I have this code in my view:
     <Window x:Class="MyView"
                Name="ucPrincipal"
                Title="{Binding Titulo}"
                Visibility="{Binding EsUpdaterVisible, Mode=TwoWay}">

    <Window.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="../Recursos/Diccionarios/Converters.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Window.Resources>

<Button Content="Aceptar" HorizontalAlignment="Left" Margin="10,145,0,0" VerticalAlignment="Top" Width="75">

                    <cmd:EventToCommand Command="{Binding AceptarCommand}" PassEventArgsToCommand="True" />

        </Button>

My ViewModel:
private RelayCommand _aceptarCommand;
        public RelayCommand AceptarCommand
        {
            get { return _aceptarCommand ?? (_aceptarCommand = new RelayCommand(aceptarCommand)); }
        }

        private void aceptarCommand()
        {
            try
            {
                EsUpdaterVisible = false;

                Titulo = "Después de aceptar.";
            }
            catch { throw; }
        }

private bool _esUpdaterVisible = true;
        public bool EsUpdaterVisible
        {
            get { return _esUpdaterVisible; }
            set
            {
                if (_esUpdaterVisible != value)
                {
                    _esUpdaterVisible = value;
                    base.RaisePropertyChangedEvent("EsUpdaterVisible");
                }
            }
        }

        private string _titulo = "Inicio";
        public string Titulo
        {
            get { return _titulo; }
            set
            {
                if (_titulo != value)
                {
                    _titulo = value;
                    base.RaisePropertyChangedEvent("Titulo");
                }
            }
        }

When I click the aceptar button, the title of the window is changed, but the windows is still visible.
I would like to hide the window in some cases from the view model. How I could do that?
Thanks.
Comment: Your `EsUpdaterVisible` is of type bool, but `Window.Visibility` property to which you bind is of type `Visibility`.
Comment: I have change the type from bool to Visibility (System.Windows enumeration). But With Visibility.Hidden doesn't hide the window.
Answer: If you wouldn't like to use converter, just xaml part:
<Window x:Class="MyView"
            Name="ucPrincipal"
            Title="{Binding Titulo}">
    <Window.Style>

       </Style>
    </Window.Style>

Answer: Visibility is not a boolean type.
You can use a converter to accomplish that.
Converter:
[ValueConversion(typeof(bool), typeof(Visibility))]
public class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Than your XAML will look something like this:
<Window x:Class="MyView"
                Name="ucPrincipal"
                Title="{Binding Titulo}"
                Visibility="{Binding EsUpdaterVisible, Converter={StaticResource visibilityConverter}}">

Comment: I get an error in the line
        Visibility="{Binding EsUpdaterVisible, Mode=TwoWay, Converter={StaticResource BooleanToVisibilityConverter}}"
Comment: Why do you use a two-way binding, when the converter does not implement ConvertBack?
Comment: The error the exception StaticResourceExtension. I have tried removing the twoway mode, but the error is the same.
Comment: I have mode the converter to the app.axml, so I correct the problem, however, the window is still not hidden.

I can't hide the window in MVVM


3 vectors making equal angles with each other in 3d space?

Question: Say we have three vectors in 3d dimensional space which make equal angles with each of the other vectors. How do we go on about finding the maximum angle they can make with each other?
Ie- If each of those vectors make an angle of ∅ with each other, then are there some limitations or upper bound to the value of ∅.

More importantly how can we generalise this problem by  having k vectors in N dimensions making equal angles with every other vector and then finding an upper limit on the angle between them?

For 2 vectors, the answer seems to be 180° since 2 vectors would be coplanar always.
Comment: The vectors have the same angle with each other
Comment: Let me rephrase: What's the maximum value of ø such that 3 vectors in space make an angle of ø with each other.
Comment: If I understand what you mean, ø=120°.
Comment: How did you arrive at that?
Comment: 360°/3. If the three vectors are not coplanar the angle they form is smaller.
Comment: Also idk how much of chemistry you're in touch with but think the tetrahedral structure of methane having 4 H atoms around a C atom and all the C-H bons make an angle of 109° 28' with each other and we can treat those bonds as outward vectors (from C to H). I'm asking is there a limit (or some condition) on 'that' angle
Comment: @Aretino Can you guide me to some proof of this fact. Because this would practically solve my problem.
Answer: If the three vectors lie in the same plane, then obviously any two of them form an angle of $120°$.
If they are not coplanar, such as unit vectors $\vec{OA}$, $\vec{OB}$ and $\vec{OC}$ in diagram below, let $\angle AOB=\angle BOC=\angle COA=\theta$ and let $H$ be the projection of $O$ onto plane $ABC$. By symmetry we have $\angle AHB=\angle BHC=\angle CHA=\theta'$ and moreover $\theta<\theta'$. To justify the last statement notice for instance that
$$
AB=2\,OA\sin{\theta\over2}=2\,HA\sin{\theta'\over2},
$$
and $OA>HA$ entails $\theta<\theta'$.
The largest angle is then obtained when all three vectors are coplanar.

This obviously generalises to $n$ dimensions: you can have at most $n+1$ vectors all making the same angles one another. Their coordinates, and thus the angle they form, can be found as described in the answers to this question.


Is $\varnothing^0 = \varnothing^\varnothing$?

Question: As per the title, is $\varnothing^0 = \varnothing^\varnothing$, assuming $ \varnothing $ is the empty set? If this is the case, how is it so?
Comment: I guess $\,\emptyset^\emptyset\,$ is just the set of all functions from the empty set to itself. What do you mean by $\,\emptyset^0\,$ ?
Comment: Let us wait until the OP posts an explanation of his post, shall we? The least one should expect from a student at high school leve and up (!) is *at least* to understand and be able to explain the different parts of his own questions...
Comment: @DonAntonio: some solid fraction of questions that I was going to ask here I didn't post. Reason: while trying to make the question formulation clear to others, I was realizing the solution :)
Comment: I'm more curious about what the OP intended by using $\equiv$.
Comment: Regardless of what $0$ means here, the answer is yes... since both $\emptyset^0$ and $\emptyset^\emptyset$ are going to be $\{\emptyset\}$.
Comment: Good point, @Ilya. Even when a post's meaning  "seems" to be clear (from the context or whatever), the poster must be able to provide explanations on request. I think that as long as there some unaddressed  logical, sound and well intentioned such requests, no answers should be posted whatsoever.
Answer: The superscript notation in use here has a variety of different related uses. Usually it will be clear from the context which one is meant, but there's not really enough context here to be sure. That said,
$\varnothing^0$ would most commonly mean an empty product of no copies of the empty set. No matter which set it is we have no copies of, this is the set $\{\langle\rangle\}$ whose only element is the emtpy tuple.
$\varnothing^\varnothing$ would most commonly mean the set of all functions $\varnothing\to\varnothing$, that is, functions $f$ such that $f(x)$ is defined exactly if $x\in\varnothing$ (so: never) and $f(x)\in\varnothing$ whenever $f(x)$ is defined. There is exactly one function with this property: the empty function.
The empty function is represented by the empty set of pairs from $\varnothing\times\varnothing$ so $\varnothing^\varnothing=\{\varnothing\}$.
Is $\{\langle\rangle\}$ the same as $\{\varnothing\}$? They are at least morally different, in that it usually pays to be clear about whether we're working with sets of tuples or with sets of functions, and not care whether one of the things happen to be represented by the same object when everything is reduced to axiomatic set theory.
On the other hand, a fairly common formalization of tuples (when their length isn't fixed) is that a tuple is a map from the first few natural numbers to whatever the elements of the tuple is. Under this formalization, in particular the empty tuple is represented by the empty map!
So in this sense, $\varnothing^0$ and $\varnothing^\varnothing$ (and in fact $A^0$ and $A^\varnothing$ for any set $A$) do indeed denote the same mathematical object.
However, this identity depends on representational choices along the way that one really should try not to let anything substantial depend on, so if you try to use $\varnothing^0 = \varnothing^\varnothing$ for anything, that's a sign that your plan is either confused or at last confusING.


JavaScript function not recognizing correct password

Question: I was playing an online game where you have to find the password by viewing the page source (or inspect element). I am confused my this line if(el.value == ""+CodeCode+""). el.value is my guess, and it says I can continue if my guess is: ""+CodeCode+"". "+CodeCode+" is defined as: "+CodeCode+" == "0xf.at_hackit"; but i tried "0xf.at_hackit" (with and without quotes but it is not working). I have been stuck on this for 2 hours so please help!
Here is  the  code of the game which has a javascript function:

Level 10

Try not to be fooled

        <input id="pw" type="password" />

<input type="button" value="OK" onClick="checkPW()"/>

Comment: No, `==` is not defining. `CodeCode` is defined as `"moo6be"`. That equality check doesn't do anything.
Comment: yes enter the password as: moo6be
Comment: @Xufox `"moo6be"` worked! Can you explain how?
Comment: `var CodeCode = "moo6be";`
Comment: @RohanShake Didn't I already explain it in my comment?
Comment: So, what is your specific programming question here? What kind of answer do you actually expect?
Answer: The code is assigned right after the

Comment: Thank you, because of you and JohnD's answers, I understand that `""+CodeCode+""` is `"" + CodeCode + ""`. I will accept asap
Comment: It's the same as using just the variable `CodeCode` (it would also cast it to string, but it was already a string, so its equal).
Comment: I know but when I first looked at it I was confused by: `"+CodeCode+" == "0xf.at_hackit"` and i frankly didn't see: `var CodeCode = "moo6be";`
Answer: ""+CodeCode+"" is the same thing as: "" + CodeCode + ""
CodeCode is assigned right after the  tag:

Answer: The answer is moo6be.
This is because "+CodeCode+" == "0xf.at_hackit"; has double equals, which just means it is a comparison statement (which will just evaluate to false). It is important to note that this is unrelated to the rest of the program.
The main line here is: if(el.value == ""+CodeCode+"").
Which is: "" (empty string) + CodeCode (moo6be) + "" (empty string).
Comment: Have no any idea... I answered first and exactly the same as other answers after me. It happens, I think.
Comment: Your formatting is kinda confusing - but i think a high rep user was probably trying to answer the question themselves... Everything on SO gets down-voted these days
Comment: Rep is overrated ;) Glad that you get the answer anyway.


PHP - website e-commerce, gerar UUID para Cada carrinho de compras

Question: Bom dia antes de mais, estou a tentar criar um código único para cada carrinho de compras, qual a melhor maneira, eu estava a pensar em usar UUID, mas não tenho a minima ideia de como o fazer, se alguem souber um bom forum que fale sobre isso estao a vontade obrigado ;)
Comment: coincidência.. é quase relacionado a isso: http://pt.stackoverflow.com/questions/80604/qual-%C3%A9-a-l%C3%B3gica-de-um-carrinho-de-compras
Answer: Algo simples e funcional é usar a informação do timestamp
$token = microtime();

Retornará algo assim
0.13287600 1460718460

Se não quiser o caracter de espaço pode gerar assim também:
$token = microtime(true);

Retornará algo como: 1460718491.9867
Claro que se esse uuid/token for acessível publicamente, é recomendável encriptá-lo pelo menos para impedir de alguém entender como o token é gerado.  Nesse exemplo, usando timestamp qualquer programador consegue advinhar que o formato é um timestamp e com isso pode conseguir fazer um sequestro de token. Por isso, se usar um sequência muito óbvia, criptografe-a.
$token = hash('sha256', microtime(true));
//gera algo como `6d20018cf7023becaf77a2e0dc5d4034894aebdde9febb093f83dbcc3744bce0`


In a $\Delta ABC$ whose sides are $a,b,c$, if $\tan A/2=\frac 56, \tan B/2 =\frac 25$, then prove that $a,b,c$ are in a geometric progression

Question: Using
$$\tan \frac A2 +\tan \frac B2 +\tan \frac C2=1-\tan \frac A2 \tan \frac B2 \tan \frac C2$$
Substituting the given values
$$\frac 56 +\frac 25  +\tan \frac B2=1-\frac 56 .\frac 25 \tan \frac B2$$
$$\tan \frac B2=\frac{-7}{40}$$
But I don't know what to do with this information. How do I prove they are in GP?
Comment: What are $a,b,c$ ?
Comment: Be careful: are $\;a,b,c\;$ the same as $\;A,B,C\;$ ? Use the same symbols for the same things all the time. And what is $\;c\;$ ...or $\;C\;$, anyway?
Comment: You mean ABC is a triangle
Comment: @DonAntonio yes I am sorry I forgot to mention. The sides and angles are according to standard notation ie. a is opposite A
Comment: Where did you get the first equation? It seems to me it is not true for a general triangle with interior angles $A, B,C.$
Comment: If $C$ is an interior angle then we should find that $0 < C/2 <\pi/2$ and $\tan(C/2)>0.$ So the fact you get a negative number is an indication something is wrong.
Comment: @DavidK since $A+B+C=\pi$, then $\frac{A+B+C}{2}=\frac {\pi}{2}$. Then $\tan \pi/2 =\frac 10$ and then I used the formula for $\tan {P+Q+R}$
Comment: See https://math.stackexchange.com/questions/3450441/in-a-triangle-if-tana-2-tanb-2-tanc-2-are-in-arithmetic-progre/3451324?r=SearchResults#3451324
Comment: @DavidK I realised that the number shouldn't be negative, but unless there is something wrong with my arithmetic, I don't see a problem
Comment: @Aditya - It appears that the sides are in arithmetic progression, not geometric.
Comment: First, you need to be careful anytime you write $1/0.$ It's not clear if you did the sum-of-three-angles formula correctly (see https://math.stackexchange.com/questions/177640/prove-tanaby-frac-tan-a-tan-b-tan-y-tan-a-tan-b-tan-y1-tan-a-tan), but if you got your formula by setting the numerator equal to $1,$ that's a mistake. Your final formula is clearly incorrect for an equilateral triangle, so we know there's a mistake somewhere.
Answer: Your question appears to be wrong. Or my arithmetic could be, but I keep staring at it looking for the reason why.
Since $\sin A=\frac{2\times\frac56}{1+\frac{25}{36}}=\frac{60}{61}$ and similarly $\sin B=\frac{20}{29},\,\cos A=\frac{11}{61},\,\cos B=\frac{21}{29}$,$$\sin C=\sin(A+B)=\sin A\cos B+\cos A\sin B=\frac{1480}{61\times 29}.$$By the sine rule, what matters is whether the sines of $A,\,B,\,C$ are in geometric progression. Well, they're not.
Comment: I rechecked, but I typed out the question as it is.
Comment: The progression is arithmetic, not geometric.
Comment: @DavidK That explains a lot!
Answer: From the given $\tan \frac A2 = \frac56$ and $\tan \frac B2 = \frac25$, we have
$$\sin A = \frac{2\tan \frac A2}{1+\tan^2 \frac A2}=\frac{60}{61}, \>\>\>\>\>\cos A = \frac{11}{61}$$
$$\sin B = \frac{2\tan \frac B2}{1+\tan^2 \frac B2}=\frac{20}{29}, \>\>\>\>\>\cos B = \frac{21}{29}$$
Then,
$$\frac{a+b}{2c}=\frac{\sin A +\sin B}{2\sin (A+B)}
=\frac{\sin A +\sin B}{2(\sin A\cos B + \cos A\sin B)}$$
$$=\frac{\frac{60}{61} +\frac{20}{29}} {2(\frac{60}{61}\cdot\frac{21}{29}+ \frac{11}{61} \cdot\frac{20}{29})}=\frac{60\cdot29+61\cdot20 }{2(60\cdot21+11\cdot20)}=1$$
Thus, $a$, $b$ and $c$ are in arithmetic progression (not geometric).
Comment: Could you provide the values you got which resulted into 1? Because I checked it and I cant seem to get an AP
Comment: @Aditya - I plugged in the values to arrive at the result 1 in the answer.
Answer: Use $$\tan(\alpha/2)=\sqrt{\frac{(s-b)(s-c)}{s(s-a)}}$$
$$\tan(\beta/2)=\sqrt{\frac{(s-a)(s-c)}{s(s-b)}}$$
since we have
$$\tan(\pi/2-\frac{\gamma}{2})=\frac{\frac {5}{6}+\frac{2}{5}}{1-\frac{5}{6}\times\frac{2}{5}}$$ we get
$$\cot(\gamma/2)=\frac{20}{37}$$ so
$$\tan(\gamma/2)=\sqrt{\frac{(s-a)(s-b)}{s(s-c)}}$$
Solving this system for $a,b,c$ we get
$b=\frac{61}{87}a,c=\frac{74}{87}a$
Answer: $Cos A=\frac{1- tan^2(A/2)}{1+tan^2(A/2)}=\frac{11}{61}$
$Cos B=\frac{1- tan^2(B/2)}{1+tan^2(B/2)}=\frac{21}{29}$
$$ a^2=b^2+c^2-2bc Cos A$$
$$ b^2=a^2+c^2-2ac Cos B$$
Summing these relations we get:
$$2 c^2=2ac Cos B +2bc Cos A$$
Plugging values of (Cos A) and (cos B) we get:
$$1189 c=319 b+ 1281 a$$
It does not show any geometric progression.
Answer: I would like to derive how the values of $\tan\dfrac A2,\tan\dfrac B2$ are decided
Method$\#1:$
Like Quanto's method $$\dfrac{a+b}{2c}=\dfrac{\sin A+\sin B}{2\sin C}=\dfrac{2\sin\dfrac{A+B}2\cos\dfrac{A-B}2}{4\sin\dfrac C2\cos\dfrac C2}=\dfrac{\cos\dfrac{A-B}2}{2\cos\dfrac{A+B}2}=\dfrac{\cos\dfrac A2\cos\dfrac B2+\sin\dfrac A2\sin\dfrac B2}{2\left(\cos\dfrac A2\cos\dfrac B2-\sin\dfrac A2\sin\dfrac B2\right)}$$
If this $=1,$ $$3\sin\dfrac A2\sin\dfrac B2=\cos\dfrac A2\cos\dfrac B2\iff\tan\dfrac A2\tan\dfrac B2=\dfrac13$$
Method$\#2:$
Here In a triangle, if $\tan(A/2)$, $\tan(B/2)$, $\tan(C/2)$ are in arithmetic progression, then so are $\cos A$, $\cos B$, $\cos C$,
we have derived $\sin A,\sin B,\sin C$ will be in Arithmetic Progression iff $\cot\dfrac A2,\cot\dfrac B2, \cot\dfrac C2$ are so.
Using In a triangle ABC, prove that cot(A/2)+cot(B/2)+cot(C/2) =cot(A/2)cot(B/2)cot(C/2),
$$\cot\dfrac A2+\cot\dfrac B2+\cot\dfrac C2=\cot\dfrac A2\cot\dfrac B2\cot\dfrac C2$$
Now if $\cot\dfrac A2+\cot\dfrac B2=2\cot\dfrac C2,$
$$3\cot\dfrac C2=\cot\dfrac A2\cot\dfrac B2\cot\dfrac C2$$
As $\cot\dfrac C2\ne0,$ the result follows.


ImportError: Module not found but sys.path is showing the file resides under the path

Question: When I print sys.path in my code I get the following as output:
['C:\Netra_Step_2015\Tests\SVTestcases', 'C:\Netra_Step_2015\Tests\SVTestcases\TC-Regression', 'C:\Python27\python27.zip', 'C:\Python27\DLLs', 'C:\Python27\lib', etc.]
Now, when I write "import testCaseBase as TCB" where testcaseBase.py is in this path:
C:\Netra_Step_2015\Tests\SVTestcases\Common\shared
I get an error: "ImportError: No module named testCaseBase"
My code is in C:\Netra_Step_2015\Tests\SVTestcases\TC-Regression\regression.py. My code goes ahead with compilation, but testcaseBase.py which is residing in a parallel directory fails to compile.
What might be the reason?
Answer: Perhaps I'm missing something, but this file path...
C:\Netra_Step_2015\Tests\SVTestcases\Common\shared

...isn't in your sys.path, so it's not surprising you got an error. You have several options though. Changing your project structure or, if Common and shared are actual packages with __init__.py defined inside of them, do:
import Common.shared.testCaseBase

You can also just append the path in your calling script, so:
sys.path.append('\SVTestcases\Common\shared')

Or, actually just add the following path to your ENV variable (PYTHONPATH)
C:\Netra_Step_2015\Tests\SVTestcases\Common\shared

But it's not necessarily a good habit to substitute good directory structure and importing techniques with editing your PYTHONPATH each time. You'll be much better off if you resolve this another way.
Comment: Thanks Eithos, appending the path in sys.path worked for me, I am going to try other solutions given by you too
Comment: @user3565150: For more info on how to set up a package structure see the official Python docs on [Packages](https://docs.python.org/2/tutorial/modules.html#packages). That link's for Python 2, here's the [Python 3 version](https://docs.python.org/3/tutorial/modules.html#packages).
Answer: put
C:\Netra_Step_2015\Tests\SVTestcases\Common\shared
in your PYTHONPATH env
Comment: I don't use Windows, but shouldn't that be `PYTHONPATH` ?
Comment: So, if there is another folder under Common, I have to put it in PATH env explicitly or just adding till common will include all the subfolders under it ?
Answer: Please dont use ~/ in the path . it does not work. Use the full path.


Someone seems to be redirecting to my site

Question: I'm playing around with a new startup concept. I've built a node application and popped up a limited access version of it on the www. I've noticed recently that someone else seems have copied it, or perhaps redirected to it with their own domain.
I'm not really sure what I can do about it, or with what purpose they are doing it.
My domain: http://mycalories.ca
Their domain: http://xmit.io
I looked them up and it seems like it's a legitimate domain associated with a company in the US:
Domain : xmit.io
Status : Live
Expiry : 2016-02-27

NS 1 : dns1.p04.nsone.net
NS 2 : dns2.p04.nsone.net
NS 3 : dns3.p04.nsone.net
NS 4 : dns4.p04.nsone.net

Owner : Jeffrey Arnold
Owner : PhotoShelter, Inc.
Owner : 33 Union Square West FL2
Owner : New York
Owner : NY
Owner : US

Why would someone overlay their domain like this?
Comment: My _guess_ is that that is the _former_ user of your IP address.
Comment: http://serverfault.com/q/444217/126632
Comment: The second one makes a lot of sense. I'll reach out to them. Could you put it as an answer?
Comment: *I'm not really sure what I can do about it* - why do you care? Why would you want to do anything about it?
Comment: Actually that's part of my question. "Should I care?". It seems the answer to that might be no.
Answer: So, your domain points to the IP Address 188.8.131.52 which is obviously your web server. The admin for the other domain (xmit.io) has pointed their domain to the same IP Address. This is probably not anything malicious; it could be that they used to have a server with your web host so they used to have the IP Address you now use, or someone has just fat-fingered the address and not noticed.
You can try contacting the company and highlighting the issue to them.
Ultimately it shouldn't be a huge problem for you. You can do one of 2 things:

Setup virtual hosts on your web server. Serve your site from your domain, and return a 404 (or similar) to requests for their domain. This will keep "their" traffic separate to yours.
Rewrite requests for the non-canonical host of your domain to the canonical host. In other words, if you want your site to be www.mycalories.ca (as opposed to mycalories.ca) then rewrite requests for anything that doesn't match that to redirect to www.mycalories.ca. This will bring visitors to xmit.io into your site instead of giving them an error.

Personally I would go with the former; people looking for the 'xmit.io' website aren't nessecarily particularly interested in your website, so keep your genuine traffic "real" instead of mixing the 2 sources.
Answer: xmit.io is the former user of your IP address.
Here is the simple proof:
By looking at the DNS SOA record it is often possible to tell when the most recent change was made to a domain's DNS records. The SOA record for xmit.io is currently
xmit.io has SOA record dns1.p04.nsone.net. hostmaster.nsone.net. 1402347696 43200 7200 1209600 3600

Notice the third field, the serial number 1402347696. It is easy to recognize this as a UNIX timestamp, and converting it we get Mon, 09 Jun 2014 21:01:36 GMT. Thus, we can be confident that the last time a change was made to this domain's DNS was approximately a year ago.
But your domain was only registered last March. And the serial of your SOA record uses the other common format of encoding a date:
mycalories.ca has SOA record ns1.linode.com. brandon.bertelsen.ca. 2015051190 14400 14400 1209600 86400

Indicating that the last change to your DNS records took place on May 11. Presumably this is around the time that you obtained the VPS from Linode.

This being the case, I wouldn't bother contacting the company. They are probably out of business and the domain's DNS is only still up because it was paid in advance, or as part of the domain registration.
My usual recommendation is to set up a virtual host on your web server to feed traffic for that site a 404 page, or redirect it to goatse, or whatever. I wouldn't redirect it to your site, though, just in case someone is still watching that domain, so that they will have no cause to complain about their own error.


Number of ways to pick $d$ disjoint $k$-subsets out of $n$ elements

Question: How many ways are there to pick $d$ disjoint subsets of $k$ elements out of a set of $n$ elements? I got
$${n \choose dk}\prod_{i=0}^{d-1} {(d-i)k \choose k}$$
Is there a closed form? Does this require the dreaded... multinomial coefficient?
Comment: When $k=1$ and $d=2$ your formula gives $2\binom n2$ from which I guess you want an ***ordered*** set of $d$ disjoint $k$-subsets. Is that what you intended? If not, then you're off by a factor of $d!.$ What's so scary about multinomial coefficients?
Comment: @bof You're right, also multinomial coefficients can't be put in closed form generally so it would be scary to me because I need a closed form :)
Comment: @bof Would you mind taking a look at the answer I just posted?
Answer: For an ordered set of $d$ $k$-subsets ($dk\le n$), it should be
$$\frac{n!}{(k!)^d(n-dk)!}.$$
Thus, the number of unordered $d$ $k$-subsets is simply
$$\frac{n!}{(k!)^d \,d!\,(n-dk)!}.$$
Comment: I can see now what is missing: each  (unordered) set of $d$ $k$-subsets defines a *partition* of the set of $n$ elements  into $d+1$ subsets ($d$ if $n$=kd$). So your computation is about a given partition, not about all possible partitions of this type.
Comment: In my opinion too, yes. So divide my answer by $d!$.
Comment: Could you explain me why my answer is wrong, then? I would appreciate it :)
Comment: But I'm not  sure they're really different. I don't see how to compute the factorial of a binomial.
Comment: Ah. Yes. I should have had the ${n \choose dk}$ as a factor out to the left and then I would have $dk$ on top. Then we have the same answer except for $(k!)^d$.... Hm... And when I think about it you're right about that. So I now concurr with your answer. Except... See my answer. I think I still may disagree. Is it possible to transform my answer into your answer just by def of binomial coefficient?
Comment: Ya. I'm certain you need to divide by $d!$. You're counting all permutations of the subsets.
Comment: You want to change the definition of binomial coefficients to make the formulae agree? :o) . More seriously, your answer f=differs from mine only a $d!$ in the denominator, which corresponds to an *unordered* set of $d!$ $k$-sets.
Comment: Ya. I mean the question was "ways to pick d disjoint subsets of k elements out of a set of n elements". So shouldn't it be unordered sets?
Comment: Why don't you edit your answer and then I'll accept it? Then I can delete mine and you can have the rep, since really you solved it.
Answer: Wait, this is actually really easy. Also, the formula I gave in my question is wrong.
Namely. All you have to do is take all the permutations of the $dk$ elements, and then divide by $(k!)^d$, since each subset gets permuted, and then by $d!$, since the ordering of the subsets gets permuted. So it's
$${n \choose dk}\frac{(dk)!}{(k!)^dd!}$$
Comment: Your answer is fine if by $dk!$  you mean $(dk)!.$
Comment: @bof Thanks filllllll
Comment: Of course your answer is equivalent to @Bernard's answer, if you rewrite the binomal coefficient in terms of factorials. $$\binom n{dk}=\frac{n!}{(dk)!(n-dk)!}.$$


Improve performance by creating light and heavy versions of a class

Question: I finished some time ago an application, and I've started with the optimizations , but a couple of things that still have not been optimized , for example the save process , many will say that this is so simple you do not need to optimize it.
now my application has some specific requirements , all is exposed through JSON API . This led me to select a tool like JMSSerializer for the job serialization of objects. the problem is that I have several closely related entities , because the serialization recursively visit each property , this can become a big problem especially when you begin to aunmentar records . 50K , 100K or 1M . the JMS serialization becomes heavy and application response becomes slow .
JMS now provides tactics of exclusion , I am currently using the groups, but this has come back to hell, my question is: Is it bad to have two entities ( Light and Heavy ) for a table ? and is this possible ?
my question is focused on some properties of entities are edited through forms but most of the fields are not ( primarily those relationship with other entities )
may be that all this is mere stupidity that occurred to me in a moment of mental fatigue, but if I would like to read some opinion or proposal of how to avoid this without having to create complex rules of exclusion
hopefully so that solutions are focused and designed to work with the components of symfony and Doctrine
Answer: Well, there is (part of) your answer:
% app/console doctrine:schema:update --dump-sql
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'foo.foo' already exists.

It might work in some cases (probably if not using any of the Schema/SchemaTool related stuff), however in many other cases it will get you into trouble.
A more conventional way would be to split the entity into two separate entities, one with only the "Light" parts, and the other with only the additional "Heavy" parts, and connect the two via a one-to-one relation. Then use serializer groups on the "Light" entity to control whether the "Heavy" parts will be serialized.
Answer: We had the same problem with serialization groups getting out of control and considered a couple of options. We ended up creating a naming scheme and using arrays to attempt to control the proliferation  of serialization groups.
In our entities, we name the serialization groups after the relationship. All of the base entity fields are just named after the entity (maybe abbreviated).
* @Groups({'EntityA_EntityB'})

Then we create arrays of serialization groups in the entity based on the usage
static $lightView = array('EntityA','EntityA_EntityB', 'EntityA_EntityC');

Then in the controller we can get the groups easily
private $viewGroup = array_merege(EntityA::$lightView, EntityC::$lightView);

It is really just a thin layer over the standard serialization groups, but it means we don't have to create so many groups, and they are all managed in one place (no scrolling through the entity adding to the annotation). All of our entities are serialized to json and sent to the client to be rendered in knockout.js, so I feel your pain trying to manage a growing list of serialization groups..
Comment: when you mean you do not have to scroll through the entire entity, you mean you only do it once right?
Comment: Right. If we want to add one of the relationships to the serialization group we just add it to the static array, not create a new group to add to the entity (and maybe other entities as well).


Save data with 3 relations eloquent

Question: I am trying to save data with eloquent relationship.
I have following three tables: User Table, Category Table and Post Table.
Post Table
Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->string('heading');
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('categories');
        $table->foreign('user_id')->references('id')->on('users');
});

Relations:
Category:
public function posts() {
    return $this->hasMany('App\Post');
}

Post:
public function user() {
    return $this->belongsTo('App\User');
}

public function category() {
    return $this->belongsTo('App\Category');
}

User:
public function posts($category) {
    return $this->hasMany('App\Post');
}

My Problem is that, how can I save post just by passing the Heading in create function. I want to use the relationship. As an example I want to use this kind of code:
$data = ['heading' => $heading];
$user->posts()->category()->create($data);

Is this possible to do this kind of stuff ?
Or any another simple way to achieve this.
EDIT
I need to create post by using this kind of relationship.
As per the process:

user will fill up the form from which I will get the data along with
the category id.
Now I need to create data for that user related with the given category id.
Answer: It's because after you call posts() method you won't get to the model's relation (only the query builder) so you will not access category() relation method. It's because posts are one-to-many relation and you don';t know exacly which record you refer to create data.
EDIT
If you want to create new post entry the the best way to sole this is:
$data = ['heading' => $heading, 'category_id' => $putHereCategoryId];
$user->posts()->create($data);

You'll need to obtain somehow the id of the desire category for the new post's entry.
Comment: Actually I need to create the post not category. User will submit the form of post from where I will get the post data and category id
Comment: Is it possible to save post by using category object? I do not want to send category id in the data array. I want to send only `heading` in `data`
Comment: But how? Where do you have information about the category if the `Post` object does not exists jet? :) You have to pass it somehow... How application can know which category you pick for the post?

Save data with 3 relations eloquent


linker command failed

Question: My xcode stopped responding so I forced it to close, after i opened it and tried to build the program again it gives me the following error, Any can help please, Iam using Xcode 4.5 note that i built this app on xcode 4.4 and it worked before !

ld: warning: directory not found for option '-L/Users/../../../Downloads/RestKit-RestKit-991bd5c/Examples/RKDiscussionBoardExample/DiscussionBoard/Libraries/three20'
  ld: warning: directory not found for option '-L/Users/../../../Downloads/RestKit-RestKit-991bd5c/Specs/Runner/OCMock'
  ld: warning: directory not found for option '-L/Users/facebook-ios-sdk-lib'
  ld: warning: directory not found for option '-L/Users/../../../../Downloads/TestFlightSDK1.0'
  ld: warning: ignoring file /Users/omars/Library/Developer/Xcode/DerivedData/Build/Products/Debug-iphoneos/libSSToolkit.a, file was built for archive which is not the architecture being linked (armv7s): /Users/omars/Library/Developer/Xcode/DerivedData/Build/Products/Debug-iphoneos/libSSToolkit.a
  ld: file is universal (3 slices) but does not contain a(n) armv7s slice: /Users/omars/Desktop/libTestFlight.a for architecture armv7s
  clang: error: linker command failed with exit code 1 (use -v to see invocation)
Comment: The entire rest kit build-folders (including its sub-libraries) should be removed and rebuild from the scratch. You may do that manually by simply removing its `build`-folder.
Comment: Not sure if this heps but "armv7s" is the instruction set supported by the new ARM processor in the iPhone 5. Xcode 4.5 by default generates binaries for armv7 and armv7s.
Comment: ..and by the way; combining an ugly monster like restkit with another nasty monster like three20 seems to be a certain way of getting into trouble. But then again, that is unrelated to your specific issue and just my personal opinion.
Comment: Thanks guys the problem was in the reskit itself, i have to get  the newer version of it to fix this issue because the current version does not support the armv7s
Answer: Did you move any folders in your project, maybe by accident?  If rsswtmr's answer doesn't help, check the real location of some of the files/folder mentioned above (like OCMock) with the setting as seen in the project.  You can see where the project thinks they are by opening the "utilities" view (the right most of the 3 view buttons) in XCode 4.5.  Also, see if any filenames are displayed in red (indicating Xcode can't find them).
Answer: You can check to see if the project build settings were somehow munged, but when this happens the first thing I always do is do a complete clean (shift-cmd-option K) and re-build. That solves the issue 90% of the time.
Answer: The problem was the restkit needs update to work on xcode 4.5 , after i reinstall the new version of it every thing works well

linker command failed


Elliptic partial differential equations notation

Question: in the context of elliptic equations of the form
$$\text{div}(Df(Du))= 0,$$
where $f,u\colon\mathbb{R^n}\to\mathbb{R}$, $D$ denotes the gradient of $f,u$, and $f$ is a convex function (which implies that the Hessian $D^2f$ is positive semidefinite), I have recently come across the following notation
$$C_1 Id \leq D^2f\leq C_2 Id,$$
where $C_1>0,C_2>0$ denote positive constants, and $Id$ is the identity matrix. Does this notation basically mean that the smallest Eigenvalue of $D^2f$ is strictly positive? Or is it understood in the sense that $(D^2f-C_1 Id)$ is still a positive semidefinite matrix? Even so, what does the second inequality $D^2f\leq C_2 Id$ denote?
Furthermore, what has the preceding inequality to do with ellipticity?
Thanks for the help!
Answer: The general notation here is the partial order on symmetric $n \times n$ matrices.  This is defined as follows.  Given two symmetric matrices $S, T \in \mathbb{R}^{n \times n}$ we write $S \le T$ if and only if their quadratic forms are ordered, i.e. $Sx \cdot x \le T x \cdot x$ for all $x \in \mathbb{R}^n$.  It's easy to check that $S \le T$ if and only if $0 \le T-S$ if and only if $S-T \le 0$.  Now, all symmetric matrices are diagonalizable, and there is a connection to this partial order.  Indeed, upon writing
$$
Sx \cdot x = \sum_{k} \lambda_x |(x,v_k)|^2
$$
for $S v_k = \lambda_k v_k$ and $\{v_1,\dotsc,v_n\}$ an orthonormal basis, it's simple to see that $S \ge 0$ if and only if $\lambda_k \ge 0$ for all $k$.
When we have $S \le T$ we can get some crude information from the Rayliegh quotients:
$$
\lambda(S)_{min} = \min\{ S x \cdot x : |x|=1\} \text{ and } \lambda(S)_{max} = \max\{ S x \cdot x : |x|=1\}.
$$
This and $S \le T$ yield
$$
\lambda(S)_{min} \le \lambda(T)_{min} \text{ and } \lambda(S)_{max} \le \lambda(T)_{max}.
$$
In fact, there is a stronger version of the Rayleigh quotient called the Courant minimax theorem that yields a precise ordering of all of the eigenvalues: $\lambda(S)_k \le \lambda(T)_k$ for all $k$, when the eigenvalues are increasing in $k$.  This extra information isn't so useful in this context, though.  In the particular case of $c I \le S \le CI$ our crude work tells us that
$$
c \le \lambda(T)_{min} \le \lambda(T)_{max} \le C,
$$
which then gives useful information on where the spectrum of $T$ lies.  The converse is also true here: $c \le \lambda(T)_{min} \le \lambda(T)_{max} \le C$ implies that $c I \le T \le C I$.
What does any of this have to do with elliptic PDE?  For second order elliptic operators with constant coefficients,
$$
L u = \text{div}(S \nabla u)
$$
for $S$ a symmetric $n \times n$ matrix, ellipticity is equivalent to $S \ge c I$ for some $c >0$.  When we have non-constant coefficients, then ellipticity is defined as
$$
L u = \text{div}(S \nabla u)
$$
where now $S(x) \ge c I$ for every $x$ in the domain under consideration. In this situation we often play games with the quadratic form
$$
Q(u,v) = \int S \nabla u \cdot \nabla v,
$$
and when doing so it is extremely convenient to assume that $S \le C I$ as well since this means $Q$ will be well-defined on standard $L^2-$based Sobolev spaces.  For your nonlinear operator
$$
N(u) = \text{div}(DF(Du))
$$
what's going on is that ellipticity can be enforced / defined by the condition that $D^2 F \ge c I$ since then the linearization around any background $u_0$ yields the linearized operator
$$
L_{u_0} v = \text{div}(D^2F(u_0) Dv)
$$
and we're guaranteed ellipticity since $D^2F(u_0) = S \ge c I$.  The corresponding upper bound $D^2F \le C I$ is added for the same reason as above.


Pegar tamanho da string dentro do array com PHP

Question: Estou com o seguinte problema, no programa abaixo, eu pego os formulários de um site, mas tenho que especificar o tamanho exato da linha que possui o formulário(96), teria a possibilidade de pegar esse número sem ter que especificar manualmente.
<?php
         $url = file_get_contents('site.com');
         if(!$url) {
           trigger_error('Não foi possível ler a url', E_USER_NOTICE);
         }

         $var1 = explode("<form", $url);
         $string = array();

         // Pega o formulário do arquivo HTML.
         for($i = 0; $i < 96; $i++) {
            $string[0][$i] = $var1[1][$i];
         }

?>

Tentei usar o foreach, Mas não retorna o número certo.
$i = 0;
foreach($var1 as $valor => $detalhes) {
    foreach($detalhes as $detalhes => $saida) {
        $i++;
     }
}

Grato!
Comment: A função pra pegar tamanho do array é `count( )`, e tamanho de strings tem `strlen( )` e `mb_strlen( )`
Comment: Acostume-se a dar uma lida no [manual do PHP](http://php.net), boa parte tem opção de português. Se der uma lida geral, vai pegar uma noção boa. Não falo só de pesquisar a função que você precisa, mas sim de uma lida geral pra saber onde achar o que precisa.
Comment: Não entendi esse 96... seria oq?
Comment: É o tamanho linha do formulário html, ex: .
Comment: No total da 96 caracteres
Comment: Tenta assim `strlen($var1[1])`
Comment: Opa, a função strlen funcionou! no caso ela pega até a ultima linha do arquivo html, mas resolvo com um if. Brigadão!
Comment: Sim, realmente ajuda muito. Vou tomar como total referência. Muito obrigado!
Answer: No seu caso não é pegar o tamanho da array, mas do índice da array que está selecionando.
Como o índice [1] da array $var1 é uma string, você pode contar seu tamanho com a função strlen():
for($i = 0; $i < strlen($var1[1]); $i++) {
   $string[0][$i] = $var1[1][$i];
}


Separar valores a partir de uma lista de sumários no R

Question: Da pergunta anterior Como executar um looping no R e guardar os resultados de um sumário num vetor tenho como resposta uma lista com 20 sumários com valores calculados a partir de um modelo especificado. Uma das respostas obtidas é da forma
 smry_list[[2]]

 Model Chisquare =  188.6337   Df =  59 Pr(>Chisq) = 1.797041e-15
 Goodness-of-fit index =  0.9272667
 RMSEA index =  0.07420728   95% CI: (0.06013725, 0.08844767)
 Bentler-Bonett NFI =  0.9916955
 Bentler CFI =  0.9942733

Preciso separar os valores de RMSEA, GFI, NFI e CFI em vetores separados para efetuar uma análise de cada um. O algoritmo utilizado, com alterações propostas na resposta da pergunta citada acima, segue abaixo
library(sem)
cfa<-specifyModel("...................txt")
dados <- read.table("...............txt", h=T)  # Amostra Original com 485 observações
p<-300  #Quantidade de observações retiradas aleatoriamente da amostra original
sem_smry <- function(dados, cfa, p)
{
  inx <- sample(nrow(dados), p)
  dados_p <- dados[inx, ]
  dataCor <- cov.wt(dados_p, method = c("ML"), cor = TRUE)
  dataCor <- as.matrix(dataCor[[1]])
  cfaOut <- sem(cfa, dataCor, N = p, objective = objectiveGLS)
  summary(cfaOut, conf.level = 0.95, fit.indices = c("GFI", "RMSEA", "NFI", "CFI"))
}
smry_list <- lapply(seq_len(20), function(i) sem_smry(dados, cfa, p))

Answer: Creio que isso pode ser feito com aplicações sucessivas de lapply. A função a aplicar é a função de extração [[.
No caso de RMSEA, nos meus testes deu uma matriz com 4 linhas, portanto tive de transformar a sua transposta em data.frame antes de criar a data.frame final.
RMSEA <- sapply(smry_list, `[[`, "RMSEA")
RMSEA_df <- as.data.frame(t(RMSEA))
names(RMSEA_df) <- sprintf("RMSEA_%02d", seq_len(ncol(RMSEA_df)))

GFI <- sapply(smry_list, `[[`, "GFI")
NFI <- sapply(smry_list, `[[`, "NFI")
CFI <- sapply(smry_list, `[[`, "CFI")

indices <- cbind(RMSEA_df, GFI, NFI, CFI)

Comment: Usei outro caminho que também funcionou
RMSEA<-c(1:20)
GFI<-c(1:20)
NFI<-c(1:20)
CFI<-c(1:20)

for(i in 1:20)
{
  RMSEA[i]<- smry_list[[i]][["RMSEA"]][1]
  NFI[i]<-smry_list[[i]][["NFI"]]
  GFI[i]<-smry_list[[i]][["GFI"]]
  CFI[i]<-smry_list[[i]][["CFI"]]
}

indices <- cbind(RMSEA, GFI, NFI, CFI)
print(indices)                                                                                É claro que seu algoritmo é mais profissional. Muito obrigado por toda sua ajuda sem a qual não conseguiria alcançar meus objetivos. Até a próxima pergunta....


How do you get joint probability of two events conditional on the same event?

Question: I want to get the joint probability of two independent events, both conditional on another event.
What I know:
Probability of A is 0.2375.
Probability of B given A is .8.
Probability of C given A is .5.
Now, I know that B and C is a joint probability (B * C). I'm also fairly certain that the "un-conditional" probabilities of B and C separately (let's call them Bu and Cu) are (A * B) and (A * C). My question is, is the joint probability of B and C calculated as (A * Bu * Cu), or is it ((A * Bu) * (A * Cu))?
Answer: Are you told that events $B$ and $C$ are "independent", or are they "conditionally independent given $A$"?

If $B$ and $C$ are independent, then, by definition: $\mathsf P(B, C)=\mathsf P(B)\,\mathsf P(C)$.  However you do not appear to have enough information to find this, since you cannot use the Law of Total Probability without the conditional probability of $B$ given the complement of $A$, nor without that for $C$.

$$\mathsf P(B)=\mathsf P(B\mid A)\,\mathsf P(A)+\mathsf P(B\mid A^\complement)\,(1-\mathsf P(A))\\\mathsf P(C)=\mathsf P(C\mid A)\,\mathsf P(A)+\mathsf P(C\mid A^\complement)\,(1-\mathsf P(A))$$

On the other hand, if $B$ and $C$ are conditionally independent given $A$, then you can at least find their joint conditional probability given $A$. This is $\mathsf P(B, C\mid A)=\mathsf P(B\mid A)\,\mathsf P(C\mid A)$.  However you still cannot find their joint probability unconditionally for the same reason.

$$\mathsf P(B,C)=\mathsf P(B,C\mid A)\,\mathsf P(A)+\mathsf P(B,C\mid A^\complement)\,(1-\mathsf P(A))$$


Convergence of $\sum_1^\infty \frac{nx^n}{n^3+x^{2n}}$

Question: $$\sum_1^\infty \frac{nx^n}{n^3+x^{2n}}$$
Here is what I've done :
$$|\frac{nx^n}{n^3+x^{2n}}|<|\frac{nx^n}{n^3}|=|\frac{x^n}{n^2}|$$$
Since series on $RHS$ would converge for $|x|<1$, then whenever $|x|<1$ is satisfied $LHS$ would converge. However answer is
LHS converges $\forall \epsilon R$ real numbers.
Comment: Try some things: $x=1,2$ for example.
Answer: Case 1. Assume $|x|\le1$, then
$$
\sum_1^\infty \left|\frac{nx^n}{n^3+x^{2n}} \right|\le \sum_1^\infty \frac{n|x|^n}{n^3} \le \sum_1^\infty\frac{1}{n^2} <\infty
$$ and the given series is absolutely convergent.
Case 2. Assume $|x|>1$, then
$$
\sum_1^\infty \left|\frac{nx^n}{n^3+x^{2n}} \right|\le \sum_1^\infty \frac{n|x|^n}{|x|^{2n}} = \sum_1^\infty \frac{n}{|x|^{n}}  <\infty
$$ and the given series is absolutely convergent, where we have used this standard result.
Comment: For $|x|>1$  a very elementary finish can be: When $n\geq 3$ and $|x|=1+y $ with $ y>0$ we have:  $|x|^n=(1+y)^n\geq 1+y\binom {n}{1}+y^2\binom {n}{2}+y^3\binom {n}{3}>y^3 \binom {n}{3},$  so $0<n/|x|^n<ny^{-3} /\binom {n}{3}=6y^{-3}/((n-1)(n-2))$...............+1


Convert normal random variable into beta random variable in STATA

Question: I need to generate two random variables - lognormal and beta distributed - while ensuring that the correlation between the two variables is -0.3.
I generated two normal random variables with -0.3 correlation as follows;
matrix C = (1, -0.3 \ -0.3, 1)
drawnorm x y, mean(0.921, 0) sds(0.174,1) corr(C)
// Here x is normal rv with mean 0.921 and sd 0.174 while y is a standard normal rv.

Converting x to lognormal is simple. I do this
gen price = exp(x)
// price is now the lognormal(0.921, 0.174)

Problem is in converting y~$N(0,1)$ to $beta(\alpha,\beta)$. Is there a way to do it?
Comment: Some ideas [here](https://stackoverflow.com/questions/32718752/how-to-generate-correlated-uniform0-1-variables).
Comment: Are you aware that when you begin with two Normal variates of correlation $\rho$ and transform at least one of them nonlinearly--as will be necessary here--the correlation of the transformed variables is unlikely to equal $\rho$?  In light of this fact, is your question really about how to transform a Normal variate into a Beta variate or is it about how to create a lognormal, Beta pair with a desired correlation?
Comment: There are many different ways to do this.  Perhaps you can get the most control over them by using a [tag:copula].
Comment: Cross-posted on [SO](https://stackoverflow.com/questions/52194343/convert-normal-random-variable-into-beta-random-variable-in-stata).
Comment: @whuber good point! Eventually I need lognormal and beta pair with desired correlation. I was hoping that I will adjust the correlation between normals (using trial and error) to get the desired correlation between lognormal and beta. I have been trying to understand copulas and how to implement this in Stata but things seem to not make sense so far.
Comment: Your approach sounds like it's tantamount to using a Gaussian copula.
Comment: @whuber I read a bit about Gaussian copula and I think I have the basic idea now. Do you have any idea how would I implement this in Stata? I am trying to avoid writing a program for this and probably use some canned program for this. Any leads?
Comment: See https://stats.meta.stackexchange.com/a/794/919.
Answer: This is how I was able to generate these variables;
matrix      C = (1, -0.32 \ -0.32, 1) // Matrix defining the correlation between two vars
drawnorm    x y, mean(0.921, 0) sds(0.174,1) corr(C) // Generate two multivariate normal vars with specified dependency
// Here x is normal rv with mean 0.921 and sd 0.174 while y is a standard normal rv.

Converting x to lognormal is simple. I do this
gen price = exp(x)
// price is now the lognormal(0.921, 0.174)

To convert y (a standard normal rv) I generated a normal cdf of y as follows;
gen         z2 = normal(y)

Then I used invibeta function to generate beta density with parameters a and b as follows;
gen yield = invibeta(a, b, z2)

The above process generates price (lognormal) and yield (beta) with correlation of -0.30.


Why Linux server closed the SSH client unexpectly and killed all the process started by the me?

Question: I'm using a CentOS(CentOS release 6.4 (Final)) to upload data to cluster, the bandwidth reached to about 100MByte/s (and the net usage is full). Also, a redis(v=3.2.1) server (0.0.0.0:6379) running to maintain the uploading state. I run the redis-server at backend(not quit after SSH exited):
$ (redis-server redis.conf &)

By login the CentOS from another Linux (name jump-server), sometimes(not always happen, but often), the CentOS will close the SSH client:
Connection to <CentOS-ip> closed by remote host.

with -vvv option added for ssh -vvv root@centos-ip, I get more message when the connection closed by the server:
$ debug3: Wrote 64 bytes for a total of 11549
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
#0 client-session (t4 r0 i0/0 o0/0 fd 4/5 cc -1)

debug3: channel 0: close_fds r 4 w 5 e 6
Connection to <CentOS-ip> closed by remote host.
Connection to <CentOS-ip> closed.
Transferred: sent 8520, received 82248 bytes, in 474.0 seconds
Bytes per second: sent 18.0, received 173.5
debug1: Exit status -1

and the redis-server also gone! I greped the redis.log (DBEUG level), there is no error or crash hint. And I started a sleepy process on the server:
# sleep.py
import time
while 1:
    time.sleep(1)

# run as (python sleep.py &)

after SSH closed, the process gone too!
Why this happen? The messy truth is, all the process I started gone! why?
There may be a lot of reason lead this issue, please give me some hints, and I can supply other info to debug the issue if required. Thanks a lot.
Answer: Some TCP/IP Stacks in the middle of the route, like the hops in the middle , between your server and your endpoint client, actually cause the connection to be closed if keepalive is not used and connection keeping KeepAlive packets are not sent:::::
Try:::
ssh -o TCPKeepAlive=yes -o ServerAliveInterval=15 -i ~/MYDIR/id_rsa    ec2-user(or--root)@myserver.com

Does that help you keep the connections??


A property of projection on a convex and closed set

Question: Let $S$ be a convex and closed set. The projection onto $S$ is defined as $P_S(x) = argmin_{y \in S} ||x-y||_2$.
I want to show that if $x \in S$, then for any $y$,
$$
\langle P_S(y) -x,P_S(y) -y\rangle \leq 0
$$
where $\langle.,.\rangle$ is the inner product. Any suggestion? What does this statement imply?
Comment: @RobArthan If $y \in S$ then $P_S(y)=y$, so the statement holds.
Comment: @angryavian: of course! thanks.
Answer: Hint: if $y \in S$, then $P_S(y) = y$ and $\langle P_S(y) -x,P_S(y) -y\rangle =0$
If $y \not\in S$, then let $z = P_S(y)$, let $H$ be the hyperplane orthogonal to the line segment $yz$ and passing through $z$ and let $U$ be the closed halfspace with $H$ as its boundary that does not contain $y$. Then you can show that $S \subseteq U$ (because if $x \in S \setminus U$, there is a point on the line segment $xz$ that is nearer to $y$ than $z$). But
$$
U = \{ x \mid \langle z - x, z -y\rangle \le 0 \}.
$$
(The geometric implication of the inequality is that $x$ and $y$ are separated by $H$.)
Answer: Rough sketch of proof:
Find the directional derivative of the function $z \mapsto \|z - y\|_2^2$ at the minimizer $z=P_S(y)$ in the direction $x - P_S(y)$. It will be related to the inner product you have written.
Intuitively, the directional derivative along such directions $x - P_S(y)$ (from $P_S(y)$ to other points of $S$) must be nonnegative. If such a directional derivative is negative, you could take a tiny step away from $P_S(y)$ in that direction and decrease the value of the function $z \mapsto \|z - y\|_2^2$, contradicting the definition of $P_S(y)$ being the minimizer.

Geometric intuition:
You can draw a picture of the two vectors in the inner product. The inequality means that the angle between these two vectors is obtuse.


Erro ao tentar buscar a ID do SQLite através do Spinner

Question: Objeto Livro
public class Livros {
private int id;
private String nome;

public Livros() {}

public Livros (int id, String nome) {
    this.id = id;
    this.nome = nome;
}
public int getId () {
    return id;
}
public int setId (int id) {
    return id;
}
public int getNome () {
    return nome;
}
public int setNome (String nome) {
    return nome;
}

Classe do openHelper
public List<Livros> buscarLivros() {
    SQLiteDatabase sqLiteDatabase = getReadableDatabase();

    List<Livros> listLivros = new ArrayList<>();
    Cursor cursor = sqLiteDatabase.rawQuery(ConsultasSQL.getRegistrosTabLivros(), null);

    if (cursor.moveToFirst()) {
        do {
            Livros livros = new Livros();
            livros.setId(cursor.getInt(0));
            livros.setNome(cursor.getString(1));

            listLivros.add(livro);
        } while (cursor.moveToNext());

    }
    sqLiteDatabase.close();
    return listLivros;
}

Main
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dataBase baseDeDados = new dataBase(this);
    SQLiteDatabase connection = baseDeDados.getWritableDatabase();

    Spinner spnLivros = (Spinner) findViewById(R.id.spinnerLivros);

    ArrayList<Livros> arrayLivros = (ArrayList<Livros>) baseDeDados.buscarLivros();

    ArrayAdapter<String> adpLivros = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
    adpLivros .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spnLivros.setAdapter(adpLivros);

    for (Livros livros : arrayLivros) {
        adpLivros.add(livros.toString());
    }
}

Método select do Spinner
public onItemSelected (AdapterView<?> parent, View view, int p, long id) {
    Livros livros = (Livros) parent.getSelectedItem();
    String buscaIdNome = "ID:" + livros.getId() + "Nome:" + livros.getNome();
    Log.i("TESTE:", buscaIdNome);
}

Erro:
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.Livro

Antes de postar essa minha dúvida verifiquei inúmeros sites, inclusive este, mas nenhum deles achei a solução para este meu problema.
Answer: O seu Adapter gere objectos do tipo String, ele é declarado como ArrayAdapter<String>.
Por isso, quando faz
Livros livros = (Livros) parent.getSelectedItem();

está a tentar converter um objecto do tipo String em Livros, daí o erro:

java.lang.ClassCastException: java.lang.String cannot be cast to com.example.Livros

Para que o método parent.getSelectedItem() retorne Livros, o Adapter deve ser declarado como ArrayAdapter<Livros> e o array que ele gere ser do tipo ArrayList<Livros>.
Esse array deve ser passado ao construtor ao criar o ArrayAdapter.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ....
    ....
    ArrayList<Livros> arrayLivros = (ArrayList<Livros>) baseDeDados.buscarLivros();

    ArrayAdapter<Livros> adpLivros =
        new ArrayAdapter<Livros>(this, android.R.layout.simple_spinner_item, arrayLivros);

    adpLivros.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spnLivros.setAdapter(adpLivros);

    //Não é necessário, foi passado o array com os livros ao Adapter
    //for (Livros livros : arrayLivros) {
    //    adpLivros.add(livros.toString());
    //}
}

O ArrayAdapter usa o método toString(), da classe a que se refere o Array, para obter o valor de cada item do Spinner.
Por isso, a classe Livros tem de sobrescrever esse método de forma retornar esse valor.
Adicione à classe Livros:
@Override
public String toString()
{
    return nome;
}

Agora que o Adaptar gere objectos do tipo Livros, já é possível fazer o cast do objecto retornado por parent.getSelectedItem() para Livros.
Nota: A classe Livros deveria chamar-se Livro, já que é um livro que ela representa e não um conjunto/lista deles.
Comment: ramaral, após fazer as alterações que foram levantadas, agora ele funciona com cast. No entanto, após eu retirar o laço, o meu spinner não apresentou mais nenhuma informação. Como se os dados não fossem mais carregados.
Comment: Você está a passar o array `arrayLivros` ao construtor do `ArrayAdapter` desta forma: `new ArrayAdapter(this, android.R.layout.simple_spinner_item, arrayLivros);` ?
Comment: ramaral, acabei esquecendo de passar o arrayLivros ao final. Muito obrigado!


Variance of $Y = a \cdot e^X$ if $X$ is Gussian random variable

Question: I have the following function
$$Y = a e^X$$
where $X$ is a normally distributed random variable. I would like to compute the variance of $Y$. So far I did the following
\begin{eqnarray}
\text{Var}(Y)
&= \text{Var}(ae^X)\\
&= a^2 \text{Var}(e^X)\\
&\approx a^2 e^{2E(X)} \text{Var}(X)
\end{eqnarray}
Where I used information I have found on this site on variance propagation. I would like to know if this calculation is correct and if there are better and more correct ways to compute $\text{Var}(Y)$? So far, this is only an approximation, if what I did is right.
Comment: I have never used or seen such a variance approximation formula.  I would not worry about memorizing it.  Nevertheless your modified approximation makes sense, I can see it being justified (for any random variable $X$ with $m=E[X]$ and with $X$ "typically close" to $m$) by $$ Var(a e^X) = a^2Var(e^X) = a^2Var(e^me^{X-m}) = a^2e^{2m}Var(e^{X-m}) \approx a^2 e^{2m}Var(1+(X-m)) = a^2e^{2m}Var(X)$$ Of course this approximation may be "infinitely bad" in the sense that $E[X]$ and $Var(X)$ is finite but $E[e^X]$ and $Var(e^X)$ can be infinite.
Comment: Your approximation does not make sense because $Var(Y)$ is a number, but your approximation is a function of $X$.  So you approximate it as the wrong type of thing ("type error").  In general, for the expectation of a function of $X$ you can use $E[g(X)] = \int_{-\infty}^{\infty} g(x)f_X(x)dx$.  And $Var(g(X))=E[g(X)^2]-E[g(X)]^2$.
Comment: @Michael Yes, you are absolutely right. I think it should be $\text{Var}(Y) \approx a^2e^{2E(X)}\text{Var}(X)$, right? Would that make more sense? Does this also hold for random variables that are not normally distributed?
Answer: If $X\sim N(\mu;\sigma^2)$ then $Y=e^X\sim\text{LogNormal}$ thus you can calculate $\mathbb{V}[Y]$ exactly
Lognormal distribution
$$\mathbb{V}[Y]=a^2\cdot e^{2\mu+\sigma^2}(e^{\sigma^2}-1)$$
Comment: Cool, I didn't know that. What if $X$ is a random variable where the distribution is not know? Does my approach work then?


Excel VBA - select a dynamic cell range

Question: I want to be able to dynamically select a range of cells (the heading row), where the row is 1 but the columns with be for 1 to last column, where "A" is the first Column and where "M" is the last column. I know how to find the last column, but I don't know how to modified the below range to input the first and last column as "A" and "M".
 Range("A1:M1").Select

Answer: If you want to select a variable range containing all headers cells:
Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")

'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST

sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select

...as long as there's no other content on that row.
EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference.
Answer: sub selectVar ()
    dim x,y as integer
    let srange = "A" & x & ":" & "m" & y
    range(srange).select
end sub

I think this is the simplest way.
Comment: Thanks this worked perfectly for me in Excel 2016
Answer: So it depends on how you want to pick the incrementer, but this should work:
Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)
If you want the beginning to be dynamic as well, you can try this:
Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

Answer: I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

End Sub

Excel VBA - select a dynamic cell range


using inner class in Java

Question: I am now working on a recommending system. I designed a class Recommend like:
class Recommend{
    Path path; //recommended path, self-defined class. This is the problem!
    //some parameters and Models
    private Map<Integer, List<Integer>> Model1;
    //...other pram and models

    //methods
    public void getPath();
    public double score(int place);//
}

Here is my problem: I construct a instance of Recommend, loading the models. Then I search a path by calling getPath method of that instance. My path is time sensitive which contains a list of locations along with the right time:
class Path{
    List<Integer> path;
    List<Integer> times;
    double socre;

    public void add(int place, double time);
}

I want to call add(int, double) to add a place and the correspond time to a path, meanwhile update the score of the new path. So here I want to call score(int), which is a method of Recommend
How should I design Path, should it be an inner class of Recommend?
UPDATE
getPath(int place, double startTime);
//try greedy searching to find a time sensitive path that scored highest,
//go through all possible places and scored them.

socre(int place, double time);
//In fact there are multiple score methods correspond to different models,
//**and notice here I modify the param to int place from Path path**
//This function evaluates the score of current place and time(used in greedy searching)

add(int place, double time);
//add a new place and time(which is proved by greedy searching to be the best)
//I want this update the score of place itself...okay maybe I should place this function in Recommend

Comment: Why don't you make the `score` method belong to the `Path` class
Comment: It would be fit for [programmers.stackexchange.com/](http://programmers.stackexchange.com/)
Comment: @RC. @rai.skumar I've considered this practice. The code above is a demo, in practice the there is whole bunch of models that need to be initialized in Recommend. And Recommend is kind of stable, which may have only one instance in runtime. In contrast, Path is NOT, so if I place `score` in that class(which is strongly depend on those models), whenever I want to instantiate a new instance of Path, I need to initialize the models, that's inefficient.
Answer: Your "getPath()" method is part of the problem; it "doesn't do anything".  Your "Recommend" class appears to be designed to score the path--and the path doesn't appear to be actually exposed outside of Recommend.  What you might consider doing is expose a new method on Recommand, which is "add(int place, double time)", and have that method update the path, and then call a PRIVATE "scorePath()" method. Then path should be an inner class, as it's only function is to hold the data structure.
You can clarify what you're trying to do by writing down the purpose of each class within a JavaDoc.  Each class should have 1 clear purpose. If, for e.g., once you've done that you discover that "Path" doesn't need to appear outside of "Recommend", then you can make it a private member.
Comment: thanks for your relevant advice, I am trying to do that.
Answer: Weather you use Inner Class or Composition(as you have done), you can achieve your goal. I think things are more complicated because you are not following Separation of Concern principle.
Think on lines of why do you need getPath() and score() methods inside Recommend class. Like add() method, your getPath() should also be part of Path class.
Comment: I explained this in the comment to RC. please refer to that.

using inner class in Java


Return type of wrapper function C++11

Question: I have re-arranged an example regarding the std::forward with template.
I have used a wrapper function and everything is fine, if i declare it as void function. It works as expected.
 #include<iostream>
 using namespace std;

 template <typename T, typename U>
 auto summation(T const &a,  U const& b) -> decltype(T{}, U{})  {
    cout << "call by lvalue" << endl;
      return a+b;
 }

 template <typename T, typename U>
 auto summation(T&& a, U && b) -> decltype(T{},U{}) {
    cout << "call by rvalue" << endl;
      return a+b;
 }

 template<typename T,typename U> void func(T&& a, U && b)  {
  summation(forward<T>(a), forward(b));

 }

 int main() {

 int x = 10;
 double y = 20;

 func(x,y);
 func(10,20);

 }

but if I want to return a type from a wrapper function, no matter what I used, I got error on lvalues function call ONLY, fund(x,y),   stating "....function does not match the arguments"... the other fund(10,20) works.
 template<typename T,typename U> auto func(T&& a, U && b) -> decltype(T{}, U{})  {
 return summation(forward<T>(a), forward(b));

 }

and even using c++14 decltype(auto) for deducing the return type of forwarding functions and similar wrappers
 template<typename T,typename U> decltype(auto) func(T&& a, U && b) {
 return summation(forward<T>(a), forward(b));

 }

it does not work either, stating "decline(type) is C++o1 extension..." that, thank you compiler, but it does help.
One non sense horrible solution is declare the return type or T or U as return type. This  compiles even if I got a warning stating "Reference to stack memory associated to local variable returned"
 template<typename T,typename U> U func(T&& a, U && b)   {
 auto res =  summation(forward<T>(a), forward(b));
 return res;

 }

the return type of std::forward given (t) the object to be forwarded is
 static_cast<T&&>(t)

therefore it the first solution with auto should work but it does not.
Any suggestion on this ?
Thanks for any help
Comment: Are you sure that `decltype(T{}, U{})` is a useful construct?
Comment: "decline(type) is C++o1 extension..." ?! decline?
Comment: Your second `summation` overload is **not** just for rvalues, it will also be called for non-const lvalues. You do not need two overloads, read http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers
Comment: Why don't you simply use `template auto func(T&& a, U && b) -> decltype (summation (forward(a), forward(b))) { return summation(forward(a), forward(b)); }`? It should handle all cases correctly.
Comment: Yes JohnB this works fine, and it works decltype(a+b) suggested by Jonathan but only if I use auto res = summation((forward(a), forward(b)). if I use return summation(forward(a), forward(b)) it fails to compile stating "no const lvalue reference to type double cannot bind a temporary of type decltype(int() + double());
Answer: decltype means the type of the expression given in its argument. So
decltype(T {}, U {})

will be the type of the expression T{}, U{}. You have the comma operator here, and so the type of the expression is the type of the expression after the comma, which is U{}, hence decltype (T{}, U{}) gives you type U (more precisely, U &&, I guess, since it is an rvalue).
What you want is
decltype(T{} + U{})

or
decltype(a+b)

(thanks to Jonathan Wakely, see comments).
Comment: `decltype(a+b)` would be better, the point of late-specified return types is they can refer to function arguments.
Comment: Thank you Jonathan, it compiles using your suggestion.
Comment: But decltype(T{}+U{}) does not, what is the difference using a+b ?

Return type of wrapper function C++11


If $x^2-1$ is a factor of $p(x)=ax^4+bx^3+cx^2+dx+e$, prove that: $a+b+c=b+d=0$

Question:
If $x^2-1$ is a factor of $p(x)=ax^4+bx^3+cx^2+dx+e$, prove that: $a+c+e=b+d=0$.

My Working.
Here, $x^2-1$ is a factor of $p(x)$
$$x=+/- 1$$. When $x=1$, $$p(1)=a+b+c+d+e$$
$$0=a+b+c+d+e$$. When $x=-1$, $$p(-1)=a-b+c-d+e$$
$$0=a-b+c-d+e$$.
What should I do next?
Comment: You might have a mistake in you question :It should be $a+c+e=b+d=0$ right?
Comment: Have you tried setting $0=0$? It would be the obvious next step.
Comment: @Nij, Doing that, I get $b+d=-(b+d)$.
Answer: Now $$a+b+c+d+e=a-b+c-d+e$$ so $$2b+2d=0 \Rightarrow b+d=0$$ and immediately $$a+b+c+d+e=a+c+e+(b+d)=0 \Rightarrow a+c+e=0$$ Similarly $$a+b+c+d+e+a-b+c-d+e=0+0=0$$ so $$2(a+c+e)=0 \Rightarrow a+c+e=0$$
Comment: @user354073 Not quite. You ask for $a+b+c=0$, while so far only the sums of all five, the odd-indexed and the even-indexed, elements is zero.
Comment: Are we done with this?
Comment: Then what should be done further to get the proof?
Answer: What you did so far is good. Now compute
$$p(1) - p(-1)$$
and
$$
p(1) + p(-1)
$$
using the expressions you have for each one. What do you get and what can you conclude?
Answer: $p(x)$ has the form $$k\cdot (x-x_0)\cdot(x-x_1)\cdot(x^2-1)=\\kx^4-k(x_0+x_1)x^3+k(x_0x_1-1)x^2+k(x_0+x_1)x-kx_0x_1$$
for some $k,x_0,x_1$. Hence, we have
$$a=k\\
b=-k(x_0+x_1)\\
c=k(x_0x_1-1)\\
d=k(x_0+x_1)\\
e=-kx_0x_1$$
So unless I'm mistaken something's wrong here. We do get $b+d=0$, but we get $a+b+c=k(x_0x_1-x_0-x_1)$.
Comment: @Nij Did you downvote? Because the conclusion I drew is the same as yours. The question asked to show $a+b+c=0$, which is not generally true, while my answer also finds that $a+c+e=0$.
Comment: No, I didn't downvote. I reread question to check my own as well; I believe OP wrote the question wrong and your answer supports that thought.


InputStream from a pipe to another process remains blocked

Question: I'm trying to do some basic piping in Java. I wrote a very simple program for testing, but the code keeps getting blocked in the while loop because there seems to be no input from stdout of cat. Which part did I do wrong?
public static void main(String[] arguments) throws Exception{
    Process p=Runtime.getRuntime().exec("cat");
    PrintStream out=new PrintStream(p.getOutputStream());
    Scanner in=new Scanner(p.getInputStream());
    out.println("hello");
    while(in.hasNextLine()){
        System.out.println(in.nextLine());
    }
}

Comment: what happens if you stop cat. Do you get anything printed ?
Answer: By default PrintStream doesn't flush automatically.  You can either construct it using new PrintStream(p.getOutputStream(), true); to enable autoFlush or add a call to out.flush() after your out.println("hello"); to manually flush the string after writing to it.  Either results in in reading in what you printed to out.
Answer: in.hasNextLine() requires end of line, this may be the problem. Try if following works
    InputStream in = p.getInputStream();
    for (int c;(c=in.read())!= -1;) {
        System.out.print((char)c);
    }


Create array from nested array with php

Question: Is it possible to create array like that:
Array
        (
            [Name] => John
            [Last Name] => Doe
            [Age] => 19
        )

from nested array like that:

    [1] => Array
        (
            [Name] => John
        )

    [2] => Array
        (
            [Last name] => Doe
        )

    [3] => Array
        (
            [Age] => 19
        )

Nested array is created when adding values in array while making a loop
foreach ($users as $user) {
        $users[] = array($user['title'] => $user['value']);
    }

Comment: Do you want to alter the final array or the part where the array is build?
Comment: I need final array
Answer: More simplified @NigelRen's solution is using array_column:
$output = array_column($users, 'value', 'title');

Comment: It's too early in the morning for me to come up with this, but yes it is a better answer!
Comment: I don't understand how I miss this :+1|
Answer: You should change the way the array is built rather than process it further.  You are currently adding new arrays each time...
$output = [];
foreach ($users as $user) {
    $output[$user['title']] = $user['value'];
}

Comment: Thank you! This is exactly that I wanted
Answer: You could use array_walk_recursive it will also work if you have nested array
array_walk_recursive($a, function($v, $k) use (&$new){ $new[$k]=$v;});

DEMO :- https://3v4l.org/UGQou
Answer: You can use array_reduce
$result = array_reduce(array(
    array("Name"=>"John"),
    array("Last Name" => "Doe"),
    array("Age" => 19)
),function($a,$b){return array_merge($a,$b);},[]);
print_r($result);

Create array from nested array with php


Get All Controls of winform?

Question: I have a form with many table layout panel, Group Box and Flow Layout Panel, One inside another. I have set a string value to the Tag of each Textbox, label and some controls. How can i get all the controls where tag value is string ?
Comment: The word you're look for is `recursion`.
Comment: How to use that, because each Panel has its on type of ContainerContols ?
Comment: I have made an [API Proposal: Add Descendants property for Control](https://github.com/dotnet/winforms/issues/5195) on github.com/dotnet/winforms for this. If you like it, please upvote it there.
Answer: The form's Controls property is an Array of all controls reside in the form.
At the same way, each Container control, like Panels, TabControl, etch. Has it's own Controls property.
So you can use a statement like this:
<code>Dim Control As Windows.Forms.Control
For Each Control In Me.Controls
'Your logic Here

If Control.GetType Is GetType(System.windows.Forms.Panel) Or ... 'Any Other Container Type control
Dim Nested As Windows.Forms.Control
For Each Nested In Control... 'Your logic Here
End
</code>

Get All Controls of winform?


Additive set function properties

Question: I am reading an introduction to measure theory, which starts by defining $\sigma$-rings then additive set functions and their properties which are given without proof. I was able to prove two of them which are very easy $\phi(\emptyset)=0$ and $\phi(A_1\cup \ldots\cup A_n)=\displaystyle\sum_{i=1}^nA_i$.
There are three more which I couldn't do which are :
1- $\phi(A_1\cup A_2)+\phi(A_1 \cap A_2)=\phi(A_1)+\phi(A_2)$ for any two sets $A_1 $ and $A_2$.
2- If $\phi(A) \ge 0$ for all $A$ and $A_1 \subset A_2$ then $\phi(A_1) \le \phi(A_2)$.
3- If $A_1 \subset A_2$ and $|\phi(A_1)|< + \infty$ then $\phi(A_2-A_1)=\phi(A_2)-\phi(A_1)$.
Where $\phi$ is an additive set function.
I need some hints on how to proceed.
Comment: Hmmm.... $A_2\ne A_1\cup(A_2\backslash A_1)$
Comment: For 1 and 2, write $A_2=A_1\sqcup(A_2\setminus A_1)$. For 3, write $A\cup B-(A\setminus A\cap B)\sqcup (B\setminus A\cap B)\sqcup A\cap B$. Then apply $\phi$ observing the unions are disjoint.
Comment: @julien I was able to solve them and wrote the answer below. Are they correct?
Answer: I was able to use the third proposition to prove the first.
Let $A \subset B$. We have $(A \setminus B) \cap B = \emptyset$ then since $\phi$ is additive we have $\phi(A \setminus B) + \phi(B)=\phi((A-B) \cup B)=\phi(A) $ . Then $\phi(A \setminus B)=\phi(A)-\phi(B)$, this proves the second one.
Now for the first : $A \cup B= A\setminus (A\cap B) \cup B \setminus (A\cap B) \cup(A \cap B)$. Then $\phi(A \cup B)=\phi(A\setminus (A\cap B) \cup B \setminus (A\cap B) )= \phi(A)-\phi(A\cap B)+\phi(B)- \phi(A\cap B) + \phi(A \cap B)$
Hence upon adding $\phi(A \cap B) $ to both sides we get $\phi(A \cup B) + \phi(A \cap B)= \phi(A) + \phi (B)$. Can anyone help with the second one?
Edit: Here's the second one. Since $\phi(A) > 0$ for all sets then $\phi(A\setminus B)>0$ hence by the second property $\phi(A)-\phi(B) > 0$ when $B \subset A$.
Comment: Your union formula is not correct. You miss a $A\cap B$.
Comment: @julien Thank you, I edited it in.
Answer: I'm reading the same book I guess :). This is my try:
The core point is that $\phi (A_1 \cup A_2) = \phi [A_1 \cup (A_2 - A_1)]$ implies $\phi (A_2 - A_1) = \phi (A_1 \cup A_2) - \phi (A_1)$, by the properties you stated.
3 follows immediately, since
$A_1 \subset A_2$ implies $\phi (A_1 \cup A_2) = \phi(A_2)$.
2 follows from
$
0 \leq \phi(A_2 - A_1)
=
\phi (A_1 \cup A_2) - \phi (A_1)
=
\phi (A_2) - \phi (A_1)
$.
1 is a little more involved:
$
\phi(A_1 \cup A_2) + \phi(A_1 \cap A_2)
=
\phi[(A_1 - A_2) \cup A_2] + \phi[A_1 - (A_1 - A_2)]
=
\phi(A_1 - A_2) + \phi (A_2) + \phi[A_1 \cup (A_1 - A_2)] - \phi(A_1 - A_2)
=
\phi (A_2) + \phi[A_1 \cup (A_1 - A_2)]
=
\phi (A_2) + \phi(A_1)
$.
Comment: Do you know where the $|\phi(A_{1})| < +\infty$ part comes into play?

Additive set function properties


Override Domain-Restricted Content in a View

Question: I have a site running Domain Access, which is restricting content to the domain it was created on. Using Domain Views, I've created two types of views:

views displaying content for the current domain.
views displaying content for all domains.

However, #2 displays as #1 for anyone without the "Administer Content" permission. How can I set this up so anonymous users on one.mysite.com can see linked content on two.mysite.com ?
In addition, when they click links to other domains, I want them to be transfered to the other domain to view the content.
How can this be done?
Answer: I posted this on the Domain Access issue queue as a support request and got this helpful answer:
You can only accomplish #2 under three conditions:

The content is marked "Send to all affiliates"; or
The view is a page marked as a Special Page Request (which disables Domain Access rules); or
The view is set to ignore node access control -- this is an advanced Views configuration.

Option 3 can create security issues if you are using other node access modules.
To make the content link to the appropriate domain, use Domain Source, which lets you specify a canonical URL for each node. If you don't use Domain Source, the canonical URL is calculated for you.
Comment: Nice work and round up mtro. But all the conditions made in the issue queue answer to how it could work lead me to the question that it seems to be quite impossible to have 2 almost same views on the same internal path, but domain depending if they show up. Hm, interesting question maybe for another post ...


Multiple XAMPP Sites

Question: I've installed XAMPP on my Mac, and am trying to set up multiple virtual hosts.
I've changed the system hosts file to include the line 127.0.0.1 seo-reports.local and i've added the following to the XAMPP vhosts file
<VirtualHost *>
    DocumentRoot "/Users/Alex/Documents/Software Development/Web/seo-reports"
    ServerName seo-reports.local
    <Directory "/Users/Alex/Documents/Software Development/Web/seo-reports">
    Order allow,deny
    Allow from all
</VirtualHost>

When I go to http://seo-reports.local the file automatically redirects to http://seo-reports.local/xampp - the xampp control page which doesn't seem right.
If i go to an example file, eg: http://seo-reports.local/index.html - i get an error:

Object not found!
The requested URL was not found on this server. If you entered the URL
  manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
  Error 404 seo-reports.local Sun Sep 4 14:02:13 2011 Apache/2.2.14
  (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2.0.4
  Perl/v5.10.1
Answer: You have to delete the entire "xampp/htdocs" folder (well, only what's inside it). Can you post your "error.log" file please?
This is my configuration:
#vHosts Config:

NameVirtualHost *:80

<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^([^\.]+\.[^\.]+)$
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
<Directory "C:/xampp/htroot">
    AllowOverride All
    Options Indexes FollowSymLinks Includes ExecCGI
    Order allow,deny
    Allow from all
</Directory>
    ServerAdmin email@example.com
    DocumentRoot "C:/xampp/htroot/"
    ServerName my-ip
    ServerAlias my-ipaddress
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin email@example.com
    DocumentRoot "C:/xampp/htdocs/"
    ServerName u4ik.us
    ServerAlias www.u4ik.us
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    DocumentRoot "C:/xampp/htdocs2/"
    ServerName u4ik.info
    ServerAlias www.u4ik.info
</VirtualHost>

Comment: I'm a bit confused. I don't think I should need to delete the contents of that file because I'm not using it as the directory to store my files.
Comment: You need the "Name virtual host" part, and properly formatting the vHost directives/tags. Try also using direct paths to the files... "C:/xampp/..." or "C:/users/user/docs/path/to/pages/" and remember the trailing slash.
Comment: Yeah, that bit's there, I just included the individual config. Every single config I add just seems to revert to the default localhost one, any idea why?
Comment: What are you using? Xampp? Your config should never "change" by itself unless you have syntax errors.
Answer: To fix this you need to uncomment the include directive:
# Virtual hosts
# Include etc/extra/httpd-vhosts.conf

in /opt/lampp/etc/httpd.conf
Another way to debug your vhosts file is to run:
/opt/lampp/bin/httpd -S

If you do not see your vhosts being parsed you have not uncommented the above Include Directive

Multiple XAMPP Sites


Comparar inteiro e ponteiro

Question: Boas, tenho uma questão, eu estou a tentar copiar uma linha para um ficheiro mas aparece um erro que diz que não posso comparar um integer com um pointer, alguem consegue me ajudar?
O erro está na linha ch = getc(file1); e while(ch != EOF)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#define GetCurrentDir getcwd  //get the path of file
#define BUFFER_LEN 1024

int main(){

    char cCurrentPath[FILENAME_MAX];  //get
    char line[BUFFER_LEN];  //get command line
    char* argv[100];        //user command
    char* path= "/bin/";    //set path at bin
    char *ch;
    char progpath[20];      //full file path
    int argc;               //arg count
    FILE *file1, *file2;    //Files for history
    int delete_line, count=0;   //line to delete and counter

while(1){

    file1 = fopen("fileOne","w");
    if(GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
    {
        printf("%s",cCurrentPath);
    }
    printf("/SimpleShell>> ");                    //print shell prompt

    if(!fgets(line, BUFFER_LEN, stdin))
    {                       //get command and put it in line
        break;                                //if user hits CTRL+D break
    }
    else if(line, BUFFER_LEN, SIGQUIT){
            fopen("fileOne.c","r");
        ch = getc(file1);
        while(ch != EOF){
            printf("%s",ch);
        }
    }

    if(count<20)
    {
        fputs(argv[100] ,file1);
    }
    else{
        fclose(file1);
        file1 = fopen("fileOne.c","r");
        rewind(file1);
        file2 = fopen("repicla.c","w");
        ch = getc(file1);
        while(ch != EOF){
            ch = getc(file1);
            if(ch != "\n"){
                count++;
                if(count != 20){
                putc(ch, file2);
                }
            }
        }
        fclose(file1);
        fclose(file2);
        remove("fileOne.c");
        rename("replica.c","fileOne.c");
        fputs(argv[100] ,file1);
    }

Answer: getc() retorna um int, não um char *. Neste int está o valor ASCII do próximo caracter no ficheiro. E, realmente, quando dizes while (ch != EOF), estás a comparar o valor desse caracter com o valor EOF que marca o fim do ficheiro, isto é, já não há mais caracteres a recuperar.
Então deves declarar ch como int, não char *. Assim teu programa deve funcionar corretamente.
Comment: Obrigado, percebi a explicação mas mesmo assim esta linha de código dá o mesmo erro if(ch != '\n')
Comment: No código, está `if (ch!="\n")`; nota as aspas duplas, não simples. Isso faz com que `"\n"` seja do tipo `const char []`, então ele está tentando comparar `int` com `char *`.

Comparar inteiro e ponteiro