Prior for the coefficients of a linear regression model

Question: I have a linear regression model $\bf Y=\bf{X}\bf{\beta}+\epsilon$. I want to assign a prior on $\bf\beta$ in order to derive the posterior predictive model $p(y_{predictive}|\bf{y},\bf{X},\beta)$. How do I decide which prior I assign to the regression coefficient $\bf{\beta}$ ? Is there a literature that discusses this?
Comment: The short answer is "use Zellner's g-prior". It is described in our book, [Bayesian Essentials](http://www.amazon.com/gp/product/1461486866/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1461486866&linkCode=as2&tag=chrprobboo-20&linkId=ECRF5DUWCQMBF6PQ).
Answer: In practice, the prior that you select should come from domain expertise. Furthermore, a common practice is to select the prior based on your knowledge of the mean and then determining the variance based on your certainty.
For example, if your variables are economic variables for individuals (e.g. unemployed, level of education, GDP of country of residence, age) you might take hints from economic theory for predicting, for example, annual income; at the very least, you would at least have guidance for the signs of the means of the components of the $ \beta $ vector.
As for the variance, you would choose a higher variance for your prior if you're less sure about the effect of each component. You may also want to think about possible interaction effects between your variables (which would manifest in covariance between different $ \beta_i $ coefficients). Here it could be beneficial to impose additional assumptions, such as constant variance or a diagonal covariance matrix for your $ \beta $ prior, for computational simplicity.
At the end of the day it's kind of an art, but there are some cases for which you can obtain reasonable conjugate priors on $ \beta $ if you assume, for example that $ \beta $ has a multivariate Normal prior, and $ \epsilon $ is also some flavour of multivariate normal.
I would recommend Bayesian Data Analysis for more details on Bayesian Linear Regression.
Answer: A nice document with general advice on choosing priors (with links to papers with more detail) is here: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations.


Mounting MS DFS with support for referrals on CentOS

Question:
Possible Duplicate:
Mount a Windows DFS Namespace in Linux

We have a domain-based DFS namespace that refers to redundant (replicated)  file servers shares. With Windows client, failing over are (relatively) transparent.  However, we have a CentOS 6.3 box that needs to access the DFS shares, and this is where it becomes problematic.
Initially,  CentOS couldn't mount a share under the DFS UNC (ie: \\example.com\dfsNamespace\share). Adding cifs.upcalls in /etc/request-key.conf as such made it mountable: http://mikemstech.blogspot.ca/2012/10/how-to-mount-dfs-share-in-linux.html. But upon further testing, it will only attempts to mount the first referral even if it is down while other referrals available, making the use of DFS moot.
Is it possible to make use of the redundancy feature DFS on CentOS?
Right now, I'm trying to work around the DFS mount problem by using autofs' multi-mount map feature to provide the real file shares to autofs, and hoping it will be able to pick the servers that are available. But I'm not having much luck with multi-mount map for CIFS. Seems like a NFS only feature?
Answer: I'm no Linux guy, but it seems like you're not the only one having this issue... this blog post seems to indicate recognition of the problem, a submitted bug, and a wish for an upstream kernel patch.
https://www.centos.org/modules/newbb/viewtopic.php?topic_id=38326
You might be SOL for the time being. He also recommends uninstalling the samba package completely and reinstalling with the newest available, just to ensure that you're still having the issue.
Comment: I was afraid this would be the answer. It seems strange to me that with so many large DFS deployments, this doesn't come up more often.
Comment: Even more unfortunately, it seems as though its a bigger problem for CentOS users specifically than it is for other distro users. Either that, or most shops who have this problem have made custom kernels to address the problem. I couldn't tell you for sure.
Comment: Hey, check this out. Maybe this will work for you? Shot in the dark. http://pinchii.com/home/2011/02/mounting-dfs-to-redhat-linux-enterprise-5-centos-5/
Comment: I installed the latest of packages required, did the /etc/request-key.conf change, but nothing changed. CentOS is only mounting to the first referral in the referral list, and if the first referral is down, then it gives up.
Comment: Have you made your way through this blog post? Maybe it applies to you as well! https://bugzilla.redhat.com/show_bug.cgi?id=513410 -- yes, its red hat... i know. Still, kernel versions and such like that may apply.
Comment: Yep. Looks like most posts indicated that mounting DFS shares works, but very few indicated that referrals are selected appropriately. Meaning - yes mounting a DFS shares will work under normal conditions, but if your first referral is offline, linux doesn't try other referrals, unlike Windows.  Btw I can confirm the same behavior on Ubuntu 11.10 Desktop as well.
Comment: Insert sad news here...
Comment: Link in the answer is broken


Example of "practical" applications of Donaldson Invariants

Question: I'm studying Donaldson Invariants from chapter 9 of The wild world of 4-manifolds by Scorpan, and I'm looking for an example where they're used to distinguish two 4-manifolds which are homeomorphic but not diffeomorphic.
I know that these invariants are quite hard to compute, and honestly I don't even know where to start in order to find such manifolds; are there any "famous examples" well-known in the literature?
Thank you.
Comment: See https://arxiv.org/pdf/0812.1883.pdf
Comment: 'are there any "famous examples" well-known in the literature?' - examples of 4-manifold pairs that are homeomorphic but not diffeomorphic? If the answer is yes, you can cook up very easy examples. I think what you're interested in are 4-manifold pairs that are both smooth but have different smooth structure. Please correct me if I'm mistaken.
Comment: Yes, I'm interested in smooth 4-manifolds that do not admit smooth structures such that they are diffeomorphic, but that are homeomorphic; in the question when I write manifold I always mean "smooth" manifold.
Answer: Within the first three pages of this [1] you can find many examples from algebraic geometry that are homeomorphic but not diffeomorphic.
[1] 4-manifolds Which are Homeomorphic but not Diffeomorphic by David Gay


Let $K$ be a simplicial complex (that need not be finite). Prove $|K|$ is Hausdorff.

Question: As the title makes clear, I'm trying to solve a question which asks me to show the topological realisation of a simplicial complex is Hausdorff.
The question reminds me that a subset of $|K|$ is open if it intersects every simplex in an open set, and hints that the standard simplex has a natural metric as a subset of $\mathbb{R}^n$.
This is the first problem on simplicial complexes I'm facing, and so I'm struggling to think of how I can go about constructing disjoint open sets containing two different points in $|K|$.
I'd really appreciate it if someone could help me get started with this.
Answer: The space $|K|$ can be modelled in this way: $|K|$ is the set of maps $f$ from $V$
(the vertex set) to $\Bbb R_{\ge0}$ with the properties that
$\{v\in V:f(v)>0\}$ is the vertex set of a simplex in $K$ (and so finite)
and $\sum_{v\in V}f(v)=1$.
In this model, $|K|$ has a metric $d$ defined by $d(f,g)=\max_{v\in V}|f(v)-g(v)|$.
In general, the topology of $|K|$ is not the metric topology induced by $d$
(it is when $K$ is finite; it may not be if $K$ is infinite). But the open sets
of $|K|$ with respect to this metric are open in the standard topology on $|K|$
(the standard topology is finer than the metric topology).
Metric topologies are Hausdorff; topologies finer than Hausdorff topologies
are also Hausdorff.


How to successfully transfer GCP projects from personal account to Cloud Identity-enabled GCP account?

Question: Currently I have a personal GCP account with various projects. But I want to have my projects associated with an organization, therefore I created a new Clound Identity-bound GCP account. Next I attempted to transfer GCP projects from my personal GCP account to the new Cloud Identity enabled GCP account, using the tool here.
While I was able to successfully send a project migration request from the new Cloud Identity-backed GCP account to my personal GCP account, when I get to the "Review Migrate Screen -> Select Projects" dialog it shows no projects to be selected. Simply the text "No projects available for migration" is displayed.
Review Migrate Request dialog
Having a hard time finding any documentation whatsoever that details what to do in this situation. Any feedback or ideas would be greatly appreciated.
-Mike
Answer: I replicated your scenario, read the documentation but I had the same issue.
However, I was able to migrate a project, all I did was add my GCP personal account into Cloud Identity and grant the project creator role, then I switched to my GCP personal account and went to the Manage Resources Page, clicked on the three little dots of the project I wanted to migrate, select migrate and I chose my organization.
Edit: After trying again, I found out that you need to wait at least 5 min so the projects to migrate can be displayed, of course that the documentation doesn't mention it, I suggest you to send a feedback so it can be improved.
Comment: Thanks kornshell93. If I understand you correctly, instead of migrating from one account to another (personal GCP account to a Cloud Identity account), instead you converted your GCP personal account (which had the projects to migrate) to a Cloud Identity account? And then initiated a transfer?
Comment: No, basically I added my gcp personal account as a member of my cloud identity organization and  granted the role project creator, then I switched to that personal account and went to the manage resources page and chose the project I wanted to migrate.
Comment: However as I mentioned in the edit section, it seems you need to wait around 5 min before accepting the migration request.


Search API path make SEO friendly

Question: I am using Search API. I make a view of all the indexed entities and uses Taxonomy term as Contextual Filter. But the path of view is not SEO friendly. The path is like http://www.example.com/en/Real%20Estate.
I want to make this path SEO friendly and convert this space(%20) to dash.
In views I am getting configuration "Convert dashes into spaces" for contextual filter.
I tried to alter the views  and implement hook_views_pre_render, hook_views_post_render, hook_views_post_build and hook_views_post_execute. This time it is not showing the results.
Can anyone help me regarding this?
Comment: Did you find a solution for that?
Answer: Facet Pretty Paths module to the rescue https://www.drupal.org/project/facetapi_pretty_paths
Comment: I think Facet Pretty Paths module is only used to make changes in the parameters of facets in URL.
Answer: I managed to do that with the following code:
<code>/**
  * Implements hook_views_pre_view().
  */
 function hook_views_pre_view(&$view, &$display_id, &$args) {
   /* Search page view */
   if ($display_id == 'search_page' && !empty($args[0])) {
     $args[0] = strtr($args[0], '-', ' ');
   }
}
</code>
You should also adjust the search form ofcourse..

Search API path make SEO friendly


Erro ao ordenar GridView com coluna de linha vazia

Question: Está dando um erro aqui que eu não estou sabendo contornar, como meu programa lê um site, algumas vezes o site pode fugir do padrão e acabar saindo umas coisas vazias, então quando meu GridView tenta ordenar, se tiver algum item vazio pelo visto ele está bugando...
Aqui oque está acontecendo:
Comment: Se você colocar o código talvez alguém que entenda possa te ajudar. Do jeito que está fica difícil adivinhar seu problema.
Comment: Forneça mais detalhes para podermos analisar o problema
Answer: Sua pergunta não esta clara o suficiente, então vou chuta por cima o que possa esta acontecendo baseado no seu erro.
Ou seja, interface IComparable
Essa interface é implementada por tipos cujos valores podem ser ordenados ou classificados.Ele requer que os tipos de implementação definem um único método, CompareTo(Object), que indica se a posição da instância atual na ordem de classificação é antes, depois, ou o mesmo que um segundo objeto do mesmo tipo.
A  implementação da instância IComparable é chamada automaticamente por métodos, como Array.Sort e ArrayList.Sort.
A implementação de CompareTo(Object) método deve retornar um Int32 que tem um dos três valores, conforme mostrado na tabela a seguir
Resumindo seu objeto deve ser nulo e não implementa a interface IComparable e não pode ser comparado com o objeto da instância atual.


Change what print(Object) displays in Swift 2.0

Question: I am trying to make my class Digit display the num variable whenever print is called on that object, in Swift 2.0. I thought this might be done with a description variable, but no luck.
class Digit {

  var num: Int
  var x: Int
  var y: Int
  var box: Int
  var hintList: [Int] = []
  var guess: Bool = false

  var description: String {
    let string = String(num)
    return string
  }
}

Answer: It isn't enough to just add a description variable. You need to also state that your class conforms to CustomStringConvertible (formerly known as Printable in earlier Swift versions).
If you command click the print function, you find the following description.

Writes the textual representation of value, and an optional newline,
  into the standard output.
The textual representation is obtained from the value using its protocol
  conformances, in the following order of preference: Streamable,
  CustomStringConvertible, CustomDebugStringConvertible.  If none of
  these conformances are found, a default text representation is constructed
  in an implementation-defined way, based on the type kind and structure.

The part of which that matters here being that objects passed to print are not checked for whether or not they have a description method, but instead checked for things like whether or not the conform to protocols like CustomStringConvertible which offer data to be printed.
That being said, all you need to do in this case is specify that your class conforms to CustomStringConvertible since you've already added a description variable. If you hadn't already added this, the compiler would complain because this protocol requires that the description variable be implemented.
class Digit: CustomStringConvertible {
    var num: Int
    var x: Int
    var y: Int
    var box: Int
    var hintList: [Int] = []
    var guess: Bool = false

    var description: String {
        let string = String(num)
        return string
    }
}


Proof of the power rule for logarithms

Question: What is the proof for the power rule for logarithms? And are there different ways to prove it?
Answer:
$$\log_a(M^p)=p\log_a(M)$$

Proof : Let $t=\log_a(M)$. Then, by definition, we have $a^t=M$. So, we have
$$M^p=(a^t)^p=a^{pt}.$$
Hence, we have
$$\log_a(M^p)=\log_a(a^{pt})=pt=p\log_a(M).$$
Comment: @Gtexx Because $\log_a(a^x)$ is $x$, by the definition of $\log_a$.
Comment: Hello, I have a doubt: how did you go from $\log_{a}a^{pt}$ to $pt$ without using the identity itself?
Answer: Here is one way to show the identity.  Define the natural logarithm as
$$\log x=\int_1^x \frac{dt}{t}$$
for $x>0$.  Then, we have
$$\log x^n=\int_1^{x^n} \frac{dt}{t}=\sum_{k=1}^n\int_{x^{k-1}}^{x^k}\frac{dt}{t} \tag 1$$
Now substituting $t=x^{k-1}u$ in $(1)$ reveals that
$$\begin{align}
\log x^n&=\sum_{k=1}^n\int_{1}^{x}\frac{du}{u}\\\\
&=n\log x
\end{align}$$
as was  to be shown!
Comment: @integratethis It's a standard linear substitution.  There isn't any way to elaborate.  What is the point of confusion?
Comment: Can you elaborate on that substitution I am a bit confused.
Answer: $$e^{a \cdot \ln(x)}=\left( e^{\ln(x)} \right)^a=x^a$$
$$e^{a \cdot \ln(x)}=x^a$$
The logarithm of the left part can be done easily using the definition.
$$\ln \left( e^{a \cdot \ln(x)} \right)=a \cdot \ln(x)$$
Thus,
$$\ln(x^a)=a\cdot \ln(x)$$
(Posted on mobile)
Answer: It depends on how you define the logarithm function. If you define it as the inverse function of the exponential function, then this isn't hard to prove.
Let $x\in\mathbb{R}^+$ and let $a\in\mathbb{R}$.
We want to show that $\ln(x^a)=a\ln(x)$. So first let $y=\ln(x^a)$. What is $\exp(y)=e^y$? Then calculate $e^{a\ln(x)}$. Do you find the same result?
Answer: Hint.
If you define $$\ln x =\int_1^x \frac{dt}{t}$$ you can make an integration by substitution to prove the identity you mention.
Answer: My approach:
$$\log_a(x^n)=n\log_a(x)$$
Proof : Let $λ=\log_a(x)$, thus $a^λ=x$
$$\log_a(x^n)=k$$ Hence we have $a^k = x^n$
Using $a^λ=x$, we have $a^k = a^{λn}$
$$a^k = a^{λn} \implies k = λn \implies k = n\log_a(x)$$
$$\therefore k = n\log_a(x) \implies \log_a(x^n) = n\log_a(x)$$
Comment: Your answer is basically the accepted one.
Comment: @JoséCarlosSantos Yeah its similar but not quite same, as I was not satisfied with the accepted one. You could see my comment on the accepted one to understand the rationale for the answer.

Proof of the power rule for logarithms


How to make 4608 combinations with these choices? (Probability, permutations/combinations)

Question: This problem has been giving me a lot of trouble...

Freeze King claims to offer 4,608 different ice cream cups. A customer can choose from 3 sizes, 4 flavors; a waffle cone, sugar cone, or cup; and any combination of their toppings. How many toppings must Freeze King offer in order to match its claim?

I start out with 3*4*3 because there are 3 sizes, 4 flavors, and 3 cones. But you can pick more than one topping... I'm thinking you would use combinations and have to add them together to equal 128 but I'm not sure where to proceed from there. Is my thinking correct, and how would I proceed from here?
Comment: Out of curiosity, where did the number $96$ come from?  I think you accidentally calculated $\frac{4608}{3\cdot 4\cdot 4}$ instead of $\frac{4608}{3\cdot 4\cdot 3}$
Comment: That's exactly how I got 96. My apologies, I just edited the OP.
Answer: Hint:
for each topping you either use or don't use it on your icecream (for a total of 2 choices).

Further hint: $4608 = 2^9\cdot 3^2$ so $\frac{4608}{3\cdot 4\cdot 3} = 128 = 2^7$


Android drawBitmap 5x performance difference

Question: I've been fighting with android performance all night and possibly solved the issue I've been dealing with, however I'm still very confused and could use some help. Consider the timing differences between these two samples.
The first sample loads in a drawable bitmap and creates a mutable copy of it
Bitmap cacheBitmap;
Canvas cacheCanvas;
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    if (cacheBitmap != null) {
        cacheBitmap.recycle();
    }
    Resources res = getContext().getResources();
    Bitmap blankImage = BitmapFactory.decodeResource(res, R.drawable.blank);

    /* copy existing bitmap */
    cacheBitmap = Bitmap.createScaledBitmap(blankImage, w, h, false);
    /* copy existing bitmap */

    cacheCanvas = new Canvas();
    cacheCanvas.setBitmap(cacheBitmap);
    cacheCanvas.drawRGB(255, 255, 255);
}
public void onDraw(Canvas canvas) {
    canvas.drawBitmap(cacheBitmap, 0, 0, null); // draws in 7-8 ms
}

The second sample creates a new bitmap without copying the original blank image.
Bitmap cacheBitmap;
Canvas cacheCanvas;
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    if (cacheBitmap != null) {
        cacheBitmap.recycle();
    }
    Resources res = getContext().getResources();
    Bitmap blankImage = BitmapFactory.decodeResource(res, R.drawable.blank);

    /* create fresh bitmap */
    cacheBitmap = Bitmap.createBitmap(w, h, blankImage.getConfig());
    /* create fresh bitmap */

    cacheCanvas = new Canvas();
    cacheCanvas.setBitmap(cacheBitmap);
    cacheCanvas.drawRGB(255, 255, 255);
}
public void onDraw(Canvas canvas) {
    canvas.drawBitmap(cacheBitmap, 0, 0, null); // draws in 40 ms
}

The first sample draws 5-6 times faster then the second sample, why is this? I'd like to be able to write this code in some way that doesn't even rely on the blank image, but no matter what I do I end up with a slow bitmap draw without having it available to copy initially.
Answer: Check the format of the bitmap. In older versions of Android, there was a bug (feature?) that would always use 565 for bitmaps without alpha and 8888 for bitmaps with alpha when creating the bitmap using certain functions.
I'm tempted to say that somehow one version uses 8888 while the other one uses 565, giving you the speed gain.
Use getConfig to investigate both bitmaps.
Comment: The thing is, when I call
cacheBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565) my draw calls take 30 ms and when I use
cacheBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) my draw calls take 40 ms, so it's not just that.
Comment: @Romain: I know :) I followed that bug closely. Kinda funny to hear you talk about Android, ever since I started following you on Google+, it feels like you spend all day traveling the world and taking pictures :)
Comment: @Romain: Okay, I was thread-jacking a bit here. Seeems like the problem is not necessarily 565/8888 alone, as per the first comment here. Since you're the man for all things rendering in Android, do you have any idea where this performance difference is coming from? @seanalltogether: What do you get for `getConfig` when you try it on the first code snippet?
Comment: Sounds very much like a configuration issue.
Answer: Couldn't it be that the createScaledBitmap() actually creates a new bitmap with exactly the proportions needed for the screen, giving a 1:1 pixel draw internally and probably allowing for a faster drawing routine, where the second just creates a new bitmap which contains ALL of the information for the original resource (probably a lot of extra pixels) and each call to draw the bitmap results in an internal scaling between the pixels in the internal bitmap and the canvas that is being drawn to?


Is it possible to compute $\int_{0}^{\infty} \frac{1}{x^a + 1} dx$ without the residue theorem or Euler's reflection formula.

Question: I've been trying to find a way to compute the integral
$$\int_{0}^{\infty}\frac{1}{x^a + 1} dx, \quad a > 1$$
without having to resort to the heavy machinery of complex analysis. I've found two methods to compute this integral but they both use complex. One way is just to use contour integration on the slice of pie with angle $2\pi/a$ and apply the residue theorem, the other method uses u-substitution to turn this integral into the beta function
$$\frac{1}{a}B\left(1/a,1-1/a\right) = \frac{1}{a}\Gamma(1/a)\Gamma(1-1/a)$$
and from here you can use Euler's reflection formula to get the solution. Is there any way to analyze this integral without referencing either the residue theorem or Euler's reflection formula?
Comment: Euler's reflection formula does not require complex analysis.  See the appendix of [THIS ANSWER](https://math.stackexchange.com/questions/1913325/real-analysis-methods-to-evaluate-int-0-infty-fracxa1x2-dx-a1/1913576#1913576).
Answer: First we can write
$$\int_0^\infty \frac1{x^a+1}\,dx=\int_0^1 \frac1{x^a+1}\,dx+\int_1^\infty \frac1{x^a+1}\,dx\tag1$$
Enforcing the substitution $x\mapsto 1/x$ in the second integral on the right-hand side of $(1)$ reveals
$$\int_0^\infty \frac1{x^a+1}\,dx=\int_0^1 \left(\frac{1+x^{a-2}}{x^a+1}\right)\,dx\tag2$$
Next, we expand the denominator of the integrand on the right-hand side of $(2)$ in a geometric series to find that
$$\begin{align}
\int_0^\infty \frac1{x^a+1}\,dx &=\sum_{n=0}^\infty (-1)^n \int_0^1 (x^{na}+x^{(n+1)a-2})\,dx\\\\
&=\sum_{n=0}^\infty (-1)^n \left(\frac1{na+1}+\frac{1}{(n+1)a-1}\right)\\\\
&=1+\frac1a\sum_{n=1}^\infty (-1)^n \left(\frac1{n+1/a}-\frac{1}{n-1/a}\right)\tag3\\\\
&=\frac\pi a \csc(\pi/a)\tag4
\end{align}$$
where in going from $(3)$ to $(4)$ we made use of the result posted in the Appendix of THIS ANSWER with $y=1/a$.  Note that this result relied on real analysis only, including using the Fourier series.
Comment: Interesting, I had only known of complex analytic proofs of Euler's reflection formula before.
Comment: @daniel Have you taken a look at the referenced post?  In the question of that post, I mention the complex analysis and the partial fraction expansion of the secant function.  And in my answer, I show that Euler's Reflection Formula does not require complex analysis.  I also derive the partial fraction expansion of the secant function using Fourier Series analysis.
Answer: For any $b\in(0,1)$, let
$$ f(b) = \int_{0}^{+\infty}\frac{dx}{x^{1/b}+1} = b\int_{0}^{+\infty}\frac{x^b}{x(x+1)}\,dx=b\int_{0}^{1}\frac{x^b+x^{1-b}}{x(x+1)}\,dx. $$
From the representation in the middle it is clear that $g(b)=\frac{f(b)}{b}$ is a log-convex function on $(0,1)$; from the last representation it is clear that $g(b)=g(1-b)$. For any $c\in\left(-1,1\right)$, let
$$ h(c) = g\left(\frac{1+c}{2}\right) = \int_{0}^{1}\frac{x^{1/2-c/2}+x^{1/2+c/2}}{x(x+1)}\,dx \stackrel{x\mapsto x^2}{=} 2\int_{0}^{1}\frac{x^{c}+x^{-c}}{1+x^2}\,dx\stackrel{x\mapsto\exp(-u)}{=}\int_{0}^{+\infty}\frac{\cosh(cu)}{\cosh(u)}\,du.$$
We have that $h(c)$ is an even function and an analytic function over $(-1,1)$. For any $n\geq 0$ we have
$$ h^{(2n)}(0)=\int_{0}^{+\infty}\frac{u^{2n}}{\cosh(u)}\,du=2\int_{0}^{+\infty}u^{2n}\sum_{k\geq 0}(-1)^k e^{-(2k+1)u}\,du = (2n)!\sum_{k\geq 0}\frac{(-1)^k}{(2k+1)^{2n+1}} $$
and
$ \frac{h^{(2n)}(0)}{(2n)!} = \beta(2n+1)$. In particular if we know the ordinary generating function for the Dirichlet $\beta$ function we know $h(c)$ (then $g(b)$ and $f(b)$) and vice-versa. Luckily the OGF of $\beta$ is related to the EGF of Euler zig-zag numbers, which is fairly well-known (thanks to robjohn) and leads us to
$$ h(c)= \frac{\pi}{2\cos\frac{\pi c}{2}}\quad\Longrightarrow\quad f(b)= \frac{\pi b}{\sin(\pi b)}\quad\Longrightarrow\quad \int_{0}^{+\infty}\frac{dx}{x^a+1} = \frac{\pi}{a\sin\frac{\pi}{a}}.$$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{{\displaystyle #1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\sr}[2]{\,\,\,\stackrel{{#1}}{{#2}}\,\,\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
Since $\ds{{1 \over 1 + x} = \sum_{n = 0}^{\infty}\Gamma\pars{1 + n}{\pars{-x}^{n} \over n!}}$:
\begin{align}
& \color{#44f}{\left.\int_{0}^{\infty}{\dd x \over x^{a} + 1}\right\vert_{\Re\pars{a}\ >\ 1}} =
{1 \over a}\int_{0}^{\infty}x^{1/a - 1}\,\,\,{1 \over 1 + x}\dd x =
{1 \over a}\ \overbrace{\Gamma\pars{1 \over a}\
\Gamma\pars{1 - {1 \over a}}}^{\substack{\ds{Ramanujan's}\\[0.5mm] \ds{Master}\\[0.5mm] \ds{Theorem}}}
\\[5mm] = & \ \bbx{\color{#44f}{\pi\,{\csc\pars{\pi/a} \over a}}}
\\ &
\end{align}
Comment: I wonder if there is a formal proof of the RMT that doesn't depend on complex analysis.


Html.ActionLink object parameters + MVC4

Question: I am calling Edit action from my view that should accept an object as parameter.
Action:
[HttpPost]
    public ActionResult Edit(Organization obj)
    {
        //remove the lock since it is not required for inserts
        if (ModelState.IsValid)
        {
            OrganizationRepo.Update(obj);
            UnitOfWork.Save();
            LockSvc.Unlock(obj);
            return RedirectToAction("List");
        }
        else
        {
            return View();
        }
    }

From View:
 @foreach (var item in Model) {

 cap = item.GetValForProp<string>("Caption");
 nameinuse = item.GetValForProp<string>("NameInUse");
 desc = item.GetValForProp<string>("Description");

        <input type="text" name="Caption" class="txt" value="@cap"/>

        <input type="text" name="NameInUse" class="txt" value="@nameinuse"/>

        <input type="text" name="Description" class="txt" value="@desc"/>

      @Html.ActionLink("Edit", "Edit", "Organization", new { obj = item as Organization }, null)

}
It is raising an exception: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'PartyWeb.Controllers.Internal.OrganizationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Can somebody advise how to pass object as parameter?
Answer:
Can somebody advise how to pass object as parameter?

Why are you using an ActionLink? An ActionLink sends a GET request, not POST. So don't expect your [HttpPost] action to ever be invoked by using an ActionLink. You will have to use an HTML form and include all the properties you want to be sent as input fields.
So:

        @using (Html.BeginForm("Edit", "Organization", FormMethod.Post))
        {

                @foreach (var item in Model)
                {

                        @Html.TextBox("Caption", item.GetValForProp<string>("Caption"), new { @class = "txt" })

                        @Html.TextBox("NameInUse", item.GetValForProp<string>("NameInUse"), new { @class = "txt" })

                        @Html.TextBox("Description", item.GetValForProp<string>("Description"), new { @class = "txt" })

                        <button type="submit">Edit</button>

                }

        }

Also notice that I used a nested
 because you cannot have a <form> inside a
 and some browser such as IE won't like it.
Comment: One more thing, when I click on edit button, the focus is not going to edit action mentioned above, it is directly going into the model class, can you please advise how can I invoke the edit action I have mentioned above?
Comment: +1. I was not aware about the action link functionality. Your post always helps others not only for a specific issues but also for the basic stuff.


How to use Subtitles/Captions with MediaElement.js module

Question: Would anyone have some direction to upload subtitles/captions using the MediaElement.JS module?
Answer: The MediaElement module doesn't support it. In order for ME.js to display subtitles, you need to add a <track> element (e.g. <track kind="subtitles" src="subtitles.srt" srclang="en" />). The module's theme function, theme_mediaelement_video(), doesn't render that element.
In lieu of this, you can override the theme function to add the required <track> element. For example placing this in your theme's template.php:
//Here we're assuming an .srt with the same name of the video exists alongside
//(e.g. "sites/default/files/video.mp4 & sites/default/files/video.mp4.srt)
//Given you might want to upload srt files along with content
// you'll want a better solution

function MYTHEME_mediaelement_video($variables) {
  $output = '
';
  $output .= '<video ' . drupal_attributes($variables['attributes']) . ' >';
  $output .= '<track kind="subtitles" src="' . $variables['attributes']['src'] . '.srt" />';
  $output .= '</video>';
  if ($variables['settings']['download_link']) {
    $output .= '
' . filter_xss_admin($variables['settings']['download_text']) . '
';
  }
  $output .= '
';
  return $output;
}

Comment: How can I add this functionality to the fullscreen version?
Comment: The full screen version works the same as the smaller player.


Show that if $HK$ is an abelian group ($H$,$K$ have coprime orders), then $H$ is in $N_G(K)$

Question: My question stems form this excerpt from Dummet. I follow all of it, except the claim that $PQ$ is a subgroup of the normalizer. I feel like the solution is some simple algebraic one but i cannot seem to find it.
Answer: Let $h\in H$. To show $h\in N_G(K)$ we have to show that $hK=Kh$. So let $x\in hK$. Then we have $x=hk$ for some $k\in K$. Since $HK$ is abelian, also $x=hk=kh\in Kh$. So this shows $hK\subseteq Kh$. Similarly we can show the reverse inclusion.
Comment: That is what i thought too, but elements in $HK$ are of the form $hk$ where that is one element. I dont see how we get $hk=kh$
Comment: Ohhh $h,k$ are both elements of $HK$ wow. Thank you....
Comment: Yeah, sorry, I should have explained it. We have $H,K\leq HK$. For example, every $h\in H$ can be written as $h=he\in HK$.


ActiveMQ HA option with Shared File System

Question: We want HA of ActiveMQ. I explored the option of database and with Zookeeper. I wanted to check the option with Shared storage. In the documentation its mentioned about Storage Area Network. However I do not have access to SAN.
Can I use the message store to be on Shared folder on NAS ? or some shared directory on the file system ?
Regards,
JE
Answer: You could set up an NFSv4 file share and mount that directory in the kahadb persistence adapter.
Consider following in activemq.xml:
<persistenceAdapter>
            <kahaDB directory="{YOUR_SHARED_STORAGE_DIRECTORY}" lockKeepAlivePeriod="5000">
                <locker>
                        <shared-file-locker lockAcquireSleepInterval="10000" />
                </locker>
            </kahaDB>
</persistenceAdapter>

Answer: You need a file system that supports file locking (ie NFS4) as described in the documentation and your filesystem needs to be very reliable.  I'm not a filesystem expert, so I'm not sure what all is out there to meet that requirement, but I know that more than "SAN" does.  I believe that SAN is mentioned due to the reliability, but there other options for reliable network storage out there.
Answer: KahaDB works as well!
The documentation doesn't say that KahaDB also can be used,but have tried it myself KahaDB also supports locking and works well.
As KahaDB is already provided with activeMQ it will be easy to use as nothing extra will be needed.
Hope it helps,
Thanks!
Comment: KahaDB is a "type" of message storage "technique". It could be backed by file system. SAN or Local FS on which MQ is running. I want to know if instead of SAN, can I use NAS or shared directory ?
Comment: shared directory can be used,make sure you give write access as well.


How can I pass collection of number pairs as parameter to IN clause with Dapper and Oracle?

Question: How can I parameterize this query with Dapper and Oracle database?
SELECT COLUMN_C FROM SOME_TABLE
WHERE (COLUMN_A, COLUMN_B) IN ((1, 2), (3, 4), (5, 6))

In other words, I need to send collection of number pairs as :parameters to this query
SELECT COLUMN_C FROM SOME_TABLE
WHERE (COLUMN_A, COLUMN_B) IN :parameters

Comment: you can't do that.  Need to be individual parameters.
Answer: There is no way to pass multiple SQL parameter values as a single bind variable. You would have to do something like this:
WHERE (COLUMN_A = 1 AND COLUMN_B = 2)
   OR (COLUMN_A = 3 AND COLUMN_B = 4)
   OR (COLUMN_A = 5 AND COLUMN_B = 6) ...

or, with bind variables:
WHERE (COLUMN_A = :VALUE1 AND COLUMN_B = :VALUE2)
   OR (COLUMN_A = :VALUE3 AND COLUMN_B = :VALUE4)
   OR (COLUMN_A = :VALUE5 AND COLUMN_B = :VALUE6) ...

and you would have to build the SQL statement dynamically if you didn't know exactly how many number pairs you were dealing with.
Comment: This is a limitation of SQL, not Dapper or Oracle. And since Dapper doesn't do any SQL for you the answer is always "build your own SQL".
Comment: I was afraid of that. Isn't there any tool that could help me with this? I feel like I am the first one who is using Dapper with Oracle. Passing collection of number pairs, passing empty collection, passing collection with more than 1000 items, it seems that the answer is always "build your own SQL".
Comment: @PalleDue Acording to https://developer.mimer.com/sql-2016-validator/ the query I used in my question is valid SQL, so I don't think this is limitation of SQL.
Comment: Oracle mostly adheres to SQL2003: https://docs.oracle.com/cd/B19306_01/server.102/b14200/intro002.htm


How to split one column into two in Hive

Question: In my Hive Table, I have a column called YearMonth which has values like 'Jul1998'. I need to split the string in each row into Month ('Jul') and Year ('1998) and add those separately in new columns in Hive. Unfortunately, my code doesn't do it correctly and adds a NULL instance in every other row like shown below:

I took the below steps to get the above output:
Created a split.py file to split the string 'Jul1998' into 'Jul' and '1998
#!/usr/bin/python
import sys

for line in sys.stdin:
    Month= line[:3]
    Year = line[3:]
    print '\t'.join([Month, Year])

Then I go into Hive and add python file into hive directory
Finally, I used the transform function to split the column and created two new columns.
ADD FILE /home/ec2-user/split.py;
INSERT OVERWRITE TABLE data
SELECT TRANSFORM (yearmonth) USING 'split.py' AS (month,year) FROM data;

Comment: Why don't you use [`SUBSTR`](http://www.folkstalk.com/2011/11/string-functions-in-hive.html)? For example: `SELECT SUBSTR(yearmonth,1,3) AS month, SUBSTR(yearmonth,4,3) AS year FROM data`
Answer: Assuming your data format is consistent, you can simply use regexp_extract in Hive without the need for a UDF.
SELECT regexp_extract(yearmonth,([^0-9]+)) as mth,regexp_extract(yearmonth,([0-9]+)) as yr
FROM data;

Or a simple SUBSTRING.
select substring(yearmonth,1,3) as mth,substring(yearmonth,4) as yr
from data


Will different gauges resolve my sound/distortion problem?

Question: So, i have a cheap electric stratocaster with cheap pickups and a cheap ampli, now, at start i had 09-11-16-24-32-42 strings on, it was too buzzy when distorted on G/B/E but preatty nice sound on e/A/D... So i changed them with 11-14-18-28-38-49 and yes, now on G/B/E it sounds amazing but e/A/D have really low volume and my ampli distortion doesn't do too much distortion on them...
So, what do you think about something like 11-14-18-24-32-42? Is it a good idea?
Comment: It's odd that you'd get poor volume out of larger strings, as that should give your pickups a *stronger* electrical field. Did you change string materials, like from steel to nickel? You might want to list the exact specs of the strings, including brand.
Comment: Ernie Ball 'Skinny top heavy bottom' (gauges - 10 13 17 30 42 52). Been using them for 30 years. I don't have the chops for an 11 top, but your gauges look like they get relatively lighter as they go down. Of course, you could always manually tweak the pickup heights if there's a general volume drift, of if the strings are overall too near or far. Near would pull at the magnets too much, far would be best, at loss of gain.
Comment: It occurred to me that the higher gauge probably raised the relief in your neck and the action in your strings, which would explain why it's much quieter now. The guitar probably needs setting up, so I've posted an answer pointing to the Fender setup guide.
Comment: You would get that result on your E A D strings if you used bronze would strings which are not magnetic.
Comment: I meant bronze wound.
Answer: If the signal balance between your strings is uneven, the problem is more likely in the guitar's setup than the string gauges. The Fender Guitar Setup Guide will show you the tools you need and what steps to take. For the adjustments I describe below, you'll need a precise ruler, a Phillips screwdriver, and a set of hex wrenches.
You've just changed the strings, which is the perfect time to adjust your guitar's setup. Because you've switched to a heavier string gauge, there's a good chance your guitar now has too much relief in the neck. That can raise your string action, which can make your strings quieter than they were before. It can also make it harder to play. You fix this by tightening the truss rod a little. This is the most difficult and risky part of the setup. It's not that difficult, but it's the one place where making a mistake can wreck your guitar, so if you don't feel comfortable doing it yourself, then take the guitar to a shop and ask for a professional setup. Many techs will walk you through the setup so that you can do it yourself in the future.
The next thing to check is that your action height is consistent from string to string. If your treble strings are making weird noises, they might be too low. If your bass strings are too quiet, they might be (relatively) too high. Get them all a consistent height, somewhere around 4/64 in (1.6 mm) for a Stratocaster.
Finally, check that your pickups are a reasonable height, at an angle that produces about the same signal from the bass and treble sides. If any of the strings make weird electronic noises, the pickups are too high on that side. If one side is much quieter than the other, the pickups are too low on that side. Make sure that your equalizer is flat and your bass/mid/treble knobs are equal when checking this, and check each pickup separately.
Even if you aren't comfortable doing a full setup yourself, you can at least measure everything. If you find anything way out of balance, like the action height, you can fix just the parts that are causing the most trouble and see some improvement.


Javascript aggregation issue with new server

Question: I have a new VPS Host and have cloned my existing live site from my current VPS Host. On the new host, there is an issue with JS aggregation and I am hoping someone might recognize what this is and how to solve it.
Generally with JS aggregation set at /admin/config/development/performance, Javascript breaks sitewide, both front end and backend, logged in and non-logged in. I checked permissions and the JS directiory at /sites/default/files/js/ and it seems fine, files are writing to this directory (both the JS files and the GZipped ones).
When I view the raw code of any of these files, the code is fine (not corrupt). I have also tried switching this off, clearing cache, switching back on, clearing browser cache and even deleting the directory which Drupal did and then recreated without any issue. I checked my PHP info file (5.2.17) and it shows this under PHP Variables _SERVER["HTTP_ACCEPT_ENCODING"] - gzip,deflate,sdch so that seems ok. However my old server's PHP info file also had gzip,deflate,sdch under an additional heading called "HTTP Headers Information".
But here is the real tell-tale, I think, when I view the code of my webpage with Chrome web inspector and look in Console, I see as many JS errors as there are aggregated files. (5 or 6 I think). The error is: Uncaught SyntaxError: Unexpected token ILLEGAL If I then view the corresponding JS file, I see this:

So somehow, the aggregated JS files are turning into gibberish characters and the errors are thrown. I have spoken with my webhost and we tried some things but nothing worked. They had me put this code into .htaccess but it did not work:
[root@host ~]# httpd -L | grep deflate
DeflateFilterNote (mod_deflate.c)
DeflateWindowSize (mod_deflate.c)
DeflateBufferSize (mod_deflate.c)
DeflateMemLevel (mod_deflate.c)
DeflateCompressionLevel (mod_deflate.c)

Also I was not exactly sure where in .htaccess to put it. (under <IfModule mod_headers.c> perhaps?) At any rate this did nothing to help matters no matter where I tried that code. I feel like this is a bit of a needle in a haystack and might be tricky to fix but I am curious if anyone recognizes what might be going on so i can fix it.
** I should also note that litespeed Server is running on top of this so not sure if there are nay issues with that. I have not looked into this yet.
Comment: Do you have an uncommented line like `AddType application/x-gzip .gz .tgz` or `AddEncoding x-gzip .gz .tgz` in your httpd.conf file?
Comment: Clive, Brilliant. That works. I also found a core issue here: http://drupal.org/node/1440534 but that did not actually fix my issue, however your code did. If you want to add this as an answer, I will accept and vote up. Thanks!
Comment: Will do, glad it helped I remember that happening to me some time back
Answer: It's likely that your web server isn't sending the correct Content-Type or Content-Encoding header for compressed files.
Adding one of these to your httpd.conf file should solve the problem:
AddType application/x-gzip .gz .tgz

or
AddEncoding x-gzip .gz .tgz

There should be comments in your httpd.conf file that will help you determine which one's most appropriate for your situation (search for <IfModule mime_module> in that file if you're interested).
Comment: After thorough testing, this works great in all browsers except Chrome Canary. Chrome Production works fine. In Canary, I get this error on CSS files now: `Error 330 (net::ERR_CONTENT_DECODING_FAILED): Unknown error.` A google search yielded a few forum posts with lots of different suggestions and explanations. http://productforums.google.com/forum/#!topic/chrome/vxIgSHj3CGg
Comment: Update, it seems like I needed to add more resources to litespeed and I now have JS and CSS aggregation working in all browsers, however, I still cannot get JS gzip working. See http://drupal.org/node/1440534


Proof of Weyl's criterion not using essential spectrum

Question: Consider the following theorem.
Theorem: Let $A$ be a bounded self-adjoint operator on a Hilbert space $\mathcal{H}$. Then $\lambda \in \sigma(A)$ if, and only if there exists a sequence $\{\psi_{n}\}_{n\in \mathbb{N}}$ such that $||\psi_{n}|| = 1$ for all $n$ and $\lim_{n\to \infty}||(A-\lambda)\psi_{n}|| \to 0$.
This is a 'part' of the so-called Weyl's criterion. Usually, this result arises when studying spectral theory of Fredholm operators, where the essential spectrum plays a central role. In general, the above theorem comes together with some statement(s) concerning the essential spectrum of $A$ too, so that the above result is proved by using properties of the essential spectrum.
However, I'm not interested in Fredholm operators, but rather in bounded self-adjoint operators alone.
Question: How can I prove (or where can I find the proof) of the above Theorem using just the usual spectral theory of bounded self-adjoint operators and not using essential spectrum arguments?
Answer: I find it easiest to prove the contrapositive, $\lambda \in \rho(A)$ if and only if no such sequence $(\psi_n)$ exists.
First we observe that no such sequence $(\psi_n)$ exists if and only if there is a $\delta > 0$ such that
$$\lVert (A - \lambda)x\rVert \geqslant \delta \lVert x\rVert$$
for all $x \in \mathcal{H}$.
Next, this form of the condition immediately implies that $A - \lambda$ is injective, and it quickly implies that the range of $A - \lambda$ is closed. Conversely, the open mapping theorem implies that if $A - \lambda$ is injective with closed range, then such a $\delta$ exists.
It remains to be seen that for a self-adjoint $A$, if $A - \lambda$ is injective with closed range, then it is surjective. That follows since $A - \lambda$ is normal (and thus this criterion holds more generally for normal operators, since $A - \lambda$ is normal iff $A$ is normal). Thus suppose $x \in \bigl(\operatorname{im} (A - \lambda)\bigr)^{\perp}$. We then have
$$\lVert (A - \lambda)x\rVert^2 = \langle (A - \lambda)x, (A - \lambda)x\rangle = \langle (A - \lambda)^{\ast}(A - \lambda) x, x\rangle = \langle (A - \lambda)(A - \lambda)^{\ast} x, x\rangle = 0$$
by definition of the adjoint and normality. Since by assumption $A - \lambda$ is injective it follows that $x = 0$, hence $\operatorname{im} (A - \lambda)$ is dense, and since it is by assumption closed, that $A - \lambda$ is surjective.
Comment: Amazing! Thank you so much!


Stackoverflow inside thread - stopwatch java

Question: I would like to create a stopwatch as an android app. My problem is that I got a stackoverflow. Basically I have a class Timer and an onCreate method that instatiate it. Thats my implementation:
public abstract class Timer implements Runnable {

    private boolean running;

    public void start(){
        running = true;
        this.start();
    }

    @Override
    public void run() {
        long milliSeconds = 0;
        long seconds = 0;
        long minutes = 0;

        long baseTime = SystemClock.elapsedRealtime();

        while(running){
            long time = SystemClock.elapsedRealtime() - baseTime;
            long rest = time % 60000;
            milliSeconds = rest % 1000;
            seconds = rest - milliSeconds;
            minutes = time - seconds - milliSeconds;
            display(milliSeconds, seconds, minutes);
        }
    }

    public void stop(){
        running = false;
    }

    public abstract void display(long milliSeconds, long seconds, long minutes);

}

And my onCreate method:
public TextView time;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.opslimit);

        time = (TextView)findViewById(R.id.textView3);

        Timer timer = new Timer(){
            @Override
            public void display(long milliSeconds, long seconds, long minutes) {
                time.setText(minutes + ":" + seconds + ":" + milliSeconds);
            }
        };

        timer.start();
}

Has anyone an idea why I got a Stackoverflow. May be it deals with the display part?
Answer: You call start method recursively within itself. Fix it, and you won't get SO exception.
Note, however, that even if you change to :
    public void start(){
        running = true;
        this.run();
    }

which will fix stackoverflow, your code will run in a main thread and therefore your app won't work. You have to spawn a new thread.
I really suggest you use CountDownTimer  - it will be clean code and less boilerplate threading, check example at the link.
You can, however, make your code work by doing this changes :

make Timer extends Thread instead of implementing Runnable.
change start to :

public void start(){
    running = true;
    super.start(); // <- note super here
}

Optionally add Override notation to start/stop methods, or rename your stop -> stopTimer


can't download .apk file from server

Question: I have an apk file on my server (which is hosted on Hostinger) CentOS OS
now I want users to download that file from my server.
but when I point the url to the apk location it says 404 page not found while I know there are entire web sites dedicated to doing it.
I tried modifying htaccess file
AddType application/octet-stream .apk

then
AddType application/vnd.android.package-archive .apk

then
<Files *.*>
ForceType application/octet-stream
</Files>

but that doesn't seem to work.
even tried doing this https://stackoverflow.com/a/28784154/4481968
PS. all other file formats get downloaded, even .APK file gets downloaded but not .apk (why is that?)
Comment: What's the name of the file? Under Linux, `example.APK` is something different then `example.apk`.
Comment: @Sven metal.apk, but I don't see how it's relevant here.
Answer: It isn't a media type problem, so fiddling with AddType and ForceType isn't going to get you anywhere.  A 404 error means, quite simply, that you don't have the file in the right place.  The webserver error log will tell you where Apache is looking, and it should be straightforward to work out what needs to change (the config or the file location) to get things working.
Comment: Ah, files are case sensitive in Linux; foo.apk isn't the same as foo.APK.  Where the server logs live depends on where it's configured to log to; look for `ErrorLog` in the config.
Comment: the file is in the right place as far as I know, as when I change the extension from .apk to .APK the file gets downloaded, and also tell me where and how can I get my hands on the webserver error log?
Comment: I tried searching for logs Hostinger says it doesn't provide detailed website logs for performance reasons. but I found some in .logs in ftp and they are the error messages. nothing related to this.
Comment: Wow, sounds like your hosting provider sucks pretty bad.
Comment: free hosting... :P but is there an workaround? I need to get those downloads working.
Comment: You get what you pay for.  There is no workaround, because there's no problem, you're just requesting the wrong filename.
Answer: .apk files are blocked for security reasons by Hostinger, time to change my hosting provider.

can't download .apk file from server


How to control AWS Elastic Beanstalk auto scaling based on average response times if one endpoint is expected to take circa 60 seconds

Question: We auto-scale our Elastic Beanstalk Java Application based on the average response times exceeding 3 seconds.  When this happens we add 2 instances to our environment.  Once we are back within 1.5 seconds average response time then we reduce by 1 instance, with a 300 second cooldown policy.
Our new endpoint is expected to take circa 60 seconds to respond, which kinda breaks our auto-scaling model because the averages will now be heavily skewed.
Our original objective was to detect when endpoints encountered latency (we call through to third-party APIs and proxy their results - so any delays are because third parties are timing out or taking longer than planned).  To date the auto-scaling worked a treat.
What options are available to us when we introduce long-running requests?
Are we to look at programmatically increasing and decreasing the number of instances based on the latency of a subset of requests, e.g. average of 3 seconds for endpoint-a and endpoint-b, but an average of 70 seconds for endpoint-C ?
We could make an assumption that if 10% of the users are using the 60-second endpoint and the other 90% are using the 1-2 second endpoint, then we could attempt to set the average higher as a compromise, however, I fear this means we won't scale up early enough for some endpoints.
Thanks,
Rob.
Answer: Have you considered setting up a new Autoscaling group ?
Your statistical approach/thinking is fine, but will affect a certain percentage of requests in the original group. Better to keep the new group separate.
Comment: Hi @AYA Welcome to StackExchange I'm not sure a new auto-scaling group would help? Can you create a group for a specific URL pattern, if not then I don't see how I can set a different average response trigger ?
Comment: Thanks, certainly a newbie here :-) You could use the same launch config to create a new Autoscaling group, but you need more fancy Cloudwatch alarms, right? One possible route could be to setup an alarm, that will filter for the endpoint and then average the R/T. The following link has some nice examples, https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudwatchlogs.html#quickref-cloudwatchlogs-example1.   Or you could get creative with what the new ASG tracks, like if there's an ELB, tracking the inbound req queued or a similar metric for Elastic Beanstalk env.
Comment: Thanks again @AYA RE:"You could use the same launch config to create a new Autoscaling group" is the launch config the Elastic Beanstalk environment config? If I was to add another launch config wouldn't that mean launching a whole new environment (new Load balancer, EC2 instances etc)? Can you setup a CloudWatch alarm to trigger when a specific request URL pattern has a high average response?  Maybe I can use cloud watch to trigger a Lambda function so that I can determine which endpoints have latency then scale up / down using their API? I definitely need it automated like it is now.
Comment: You're right about the ASG config, and there seems to be no easy way out of this. The AWS doc explicitly states one ASG and one trigger is possible for Elastic Beanstalk env-- https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-autoscaling-triggers.html -- So, a custom cloudwatch metric, seems to be the route to go. If you've got sample log data to parse, maybe could help with the custom alarm... [https://stackoverflow.com/questions/14955583/aws-cloud-watch-alarm-triggering-autoscaling-using-multiple-metrics]. Good luck !
Comment: Thanks @AYA - I'll have a read up about cloud watch a bit more, but I suspect I would shy away from it and rely on my own stats that I collect each time I perform a HTTP request, I can use that as a hook and go from there.  If I'm stuck or I decide to be brave with Cloudwatch I'll ping you :-) Enjoy Stack Overflow.


Characters encoding wrong in terminal using git

Question: Any time I try to make a "git diff" command to see a file change, it shows me problem in special characters, like accented ones, but if I see the file with "cat" it shows me everything ok. I am using Ubuntu 12.04 LTS.
ex:
WHERE  `T<C3><A9>cnico` IS NOT NULL

I tried to put these lines in .gitconfig, close terminal e open again, but still didn't work.
[i18n]
    logoutputencoding = utf8
    commitencoding = utf8

Anyone have other suggestion?
Answer: Make sure of your git version.
For Ubuntu12.0.4 (precise), the package search for git indicates a:
git-core (1:18.104.22.168-1)

And i18n issues have been addressed in git1.7.10+ (see "git, msysgit, accents, utf-8, the definitive answers").


Connecting to mysql with SUPER user when reached Too many connections

Question: The documentation says that:

mysqld actually permits max_connections+1 clients to connect. The
  extra connection is reserved for use by accounts that have the SUPER
  privilege

http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html
but it doesn't tell how to connect
Answer: You just connect as usual, you just need the SUPER privilege for the connecting account.
Comment: we have root, but still doesn't let us in. we used `mysql -u root`
Comment: Do you use root for normal connections, e.g. from a web server? This would use up the +1 connection.
Comment: No, we have users setup there, but I will verify on a different node.
Comment: Well, I am positive that this normally works like this, had a buggy web app requiring this just last Friday.
Comment: @SvW Mysql allow to connect everybody until `max_connections` has been reached. Then plain users will be refused and super will be granted to make one spare connection, despite of how many super connections are already established.


Difference between LTO half-height and full-height drives?

Question: I've noticed that most tape drive vendors provide two options: full-height or half-height. The half-height drives are physically smaller and less expensive, yet seem to have identical specifications compared to their full-height peers.
What is the real difference between these drives? If they were really identical in operation, I'm sure that nobody would purchase the more expensive full-height drives, and they would stop being produced.
Answer: Half height used to have limited connection options, however now support almost everything full heights do. Except maybe ESCON, but if you're using that, you have bigger problems (and budgets).
The main difference between the two now is maximum speed. The tapes are the same and interchangeable, but a half height goes maybe 70% the speed as a full height. Check the vendor's published specs to be completely sure.
Answer: Oracle explained this in his document:
<code>What are the differences between full-height (FH) and halfheight
(HH) drives?
Full-height drives are twice the height (2U) of the half-height
drives (1U). In addition to the differences in the height of the
drives, half-height drives historically have had lower
specifications than full-height drives. For example, LTO 4
half-height drives have a native throughput of 80 MB/s while
the full-height drive's native throughput is 120 MB/s. With the
LTO 5 and LTO 6 releases, this trend has changed; LTO 5
half-height and full-height drives both have a native
throughput of 140 MB/s, and LTO 6 half-height and fullheight
drives both have a native throughput of 160 MB/s.
</code>
http://www.oracle.com/us/products/servers-storage/storage/tape-storage/lto-tape-drives-overview-faq-1906830.pdf
Comment: +1. Runs down to "Historical reasons when the electronics were bigger".
Answer: I run a tape duping company and in my experience, the full height drives are more robust, and more likely to 'go the distance' if you're operating them all day. I haven't had a chance to compare HH and FH LTO5 and 6 drives, but certainly if you disassembled earlier generations of LTO (and before that, DLT) and compared the drive mechanisms, the FH parts were stamped from thicker metal and had been finished to a higher standard.
If you're just backing up a tape or two every day, either drive will probably be swapped out and upsized before it fails; if you're using it all day every day, go for a full height.
Comment: In my experience on 90% of drives, the first component to fail is a tape head. I don't know if the tape heads are any different between the models.
Answer: The only thing you are missing is the automation of the tape being ejected from the drive. The full-height drives I have in my organization have a motor which ejects the tape nicely.
The half-height drives have a door on them, you just flip it up to open it and take the tape out.
IMHO, there is no difference. Our half-height perform just as well as full-height.
I'm pretty sure half height was invented to save rack space. Full-height drives are obsolete in my organization now, we only buy half-height. Less moving parts to break.
Of all the tape drive failures I have dealt with, most were a full-height and
Comment: I think you accidentally the rest of you sentance...
Comment: Our Quantum LTO-3 HH drive does automatic tape ejection.
Comment: Ditto, HP LTO-3 HH does automatic
Comment: I would guess difference between these drives is non-existent. Basil states below a possible performance difference, I would say this is only on the theoretical maximums. The true limiting factor on tape drive performance is size and number of files on the server. That is the only piece of information that matters when determining backup speed. Full or Half Height, my drives perform between 750 and 3000 MB/min.
Answer: Modern HP lto-6 half-height (6250) and full-height (6650) drives have the same performance spec. The only difference is size.
Answer: As a someone who has changed FH HP ultrium 960 to HH ultrium 3000 (L3 to L5) recently, I can add that FH seem to have significantly quieter fans.
Answer: I am surprised at the answer so many people have given. Full height is superior to Half height in many ways

Full Height will have a higher transfer rate
If the specification sheet shows you the same transfer rate, it must mean that the data was written in such controlled manner that the buffer was nearly full and there was continuous data writing. In real world situations since a FH will have higher buffer, and a capability to wind tape faster, it will perform faster specially when data is not written continously.

Full height will have better build quality
Full Height has a higher MTBF , higher load/unload and better build material.

Read here for a full explanation by someone who knows much better than me
https://community.ibm.com/community/user/storage/blogs/shawn-brume1/2020/09/29/choosing-the-right-technology-why-would-i-want-to
Answer: Oracle SUN tape full-height supports automation environment and 8 gb/sec FC connection while half-height doesn't support these features. I guess both these features are not so important as the tape speed max is only about 120 MB/sec there is not need of FC connection.
Comment: Oracle Sun LTO5 Half-height drives DO support both FC and SAS connections, so that's no longer the case.


How to move a struct into a class?

Question: I've got something like:
typedef struct Data_s {
  int field1;
  int field2;
} Data;

class Foo {
  void getData(Data& data);
  void useData(Data& data);
}

In another class's function, I might do:
class Bar {
  Data data_;
  void Bar::taskA() {
    Foo.getData(data_);
    Foo.useData(data_);
  }
}

Is there a way to move the Data out of the global scope and into Foo without creating a new class? Data mirrors a struct existing in a library I'm using elsewhere. (i.e. same fields, just different name. I cast Data into the other struct later. I do this because Foo is an abstract class, and the derived class using the library is just one of many.)
Currently, just pasting it inside the class and replacing Data with Foo::Data everywhere doesn't work.
class Foo {
  typedef struct Data_s {
    int field1;
    int field2;
  } Data;
  ...
}

I get 'Data' in class 'Foo' does not name a type at Bar data_;
Comment: There are only a few differences between struct and class, what are you trying to achieve by 'moving struct to class' ? Probably some clarification about what exactly are you trying to do would help.
Comment: So you want to create a class which is similar to Data_s? Or you want to copy its members' values at runtime into a class?
Comment: Added/clarified. Is that better?
Answer: You can define the struct inside the class, but you need to do it ahead of the place where you first use it. Structs, like classes themselves, must be forward-declared in order to use them:
class Foo
{
public:
    struct Data
    {
        int field1;
        int field2;
    };

    void getData(Foo::Data& data) {}
    void useData(Foo::Data& data) {}
};

void UseFooData()
{
    Foo::Data bar;
    Foo f;
    f.getData(bar);
    f.useData(bar);
}

Edit: Updated example to use the same fields/class names as listed in the original question. Please note that in order to be visible outside of the Foo class, Data needs to be declared public and other code needs to reference it as Foo::Data.
Comment: Since the question has struct Data_s and class Foo, can you revise your answer in terms of those?
Answer: More precisely, Foo::Data isn't accessible in the code snippet you gave.  Class members default to private visibility.
Secondly, when you're using C++, typedef for structure declarations is NOT recommended (there are other valid uses, but your usage is not).
Try this corrected version instead:
class Foo {
public:
  struct Data {
    int field1;
    int field2;
  };
  ...
}

Comment: just curious, when is typedef for structure declarations recommended then?
Comment: Never in C++.  In C, if you didn't use a typedef, you'd have to say "struct that" everywhere, the typedef lets you say just "that".  With C++ you don't need the struct, so the typedef is useless.  Typedef has other uses, especially in the presence of templates, but typedef on a class or struct definition is a quick way to spot a C programmer with zero C++ experience.
Comment: Actually, I was doing that only b/c I was following the example of the minizip and unrar libraries, which are written in C. @.@

How to move a struct into a class?


Why does realmd list multiples of the same realm?

Question: I'm setting up an Ubuntu server so that users can authenticate against a Windows AD server. Not knowing about realmd, I used Samba Winbind's net join command to join the machine to the domain. Afterwards, I installed realmd and tried realm list:
username@ubuntuhost:~$ realm list
thedomain.com
  type: kerberos
  realm-name: THEDOMAIN.COM
  domain-name: thedomain.com
  configured: kerberos-member
  server-software: active-directory
  client-software: winbind
  required-package: winbind
  required-package: libpam-winbind
  required-package: samba-common-bin
  login-formats: THEWORKGROUP\%U
  login-policy: allow-any-login
thedomain.com
  type: kerberos
  realm-name: THEDOMAIN.COM
  domain-name: thedomain.com
  configured: kerberos-member
  server-software: active-directory
  client-software: sssd
  required-package: sssd-tools
  required-package: sssd
  required-package: libnss-sss
  required-package: libpam-sss
  required-package: adcli
  required-package: samba-common-bin
  login-formats: %U
  login-policy: allow-permitted-logins
  permitted-logins:
  permitted-groups:

It appears that I have two realms--the first managed by winbind and the second managed by sssd. Am I right? I don't really need both. How do I whittle this down to just one? I guess I'd prefer to use the sssd version. How do I remove the windbind entry?
Answer: This is actually a dangerous situation, as you're probably using ONE of the two entries, not both, and you can't be sure you're using the one you want.
Depending on your nsswitch.conf, you may be using winbind or sss. You probably don't need both, and I assume sss the best choice.
So, assuming that we want to use sss and NOT winbind, alas the only way I found to keep the right realm is to remove both and re-add the one you want:
realm leave
realm leave
realm join thedomain.com

Comment: Hmmm... Darn. I actually don't have permission to add machines to the domain myself. The original, `net join` command was performed by one of our IT admins when I him to log into this Linux box and issue the command for me--he very kindly did so. He could've just said, "no." I know our IT guys are very busy--I hate to bother them with requests to do the same thing over again. Thanks for clarifying this, though.


Consolidar dados de várias abas numa só (mesma pasta de trabalho)

Question: Tenho 18 planilhas(abas) com dados de usuários e preciso copiar e colar os dados em outra planilha(aba) de no nome consolidado. Preciso copiar o cabeçalho apenas da primeira planilha e ao final remover as linhas vazias.
Está tudo numa pasta de trabalho só. O cenário mais próximo que cheguei foi este mas está muito lento:
Sub juntarfim()
    '
    Range("A1").Select
    Sheets("PLANILHA1").Select
    Range("A5:E500").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("CONSOLIDADOJUNTOS").Select
    ActiveSheet.Paste
    '
    Range("A501").Select
    Sheets("PLANILHA2").Select
    Range("A6:E500").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("CONSOLIDADOJUNTOS").Select
    ActiveSheet.Paste
    '
End sub

Comment: Evite a utilização do [Select](https://stackoverflow.com/q/10714251/7690982), pois o mesmo é lento e pode causar erros em códigos muito grandes. Com relação ao código, se puder criar um [mcve] com alguns dados de exemplo...
Answer: Sub juntarfim()

Application.ScreenUpdating = False 'desativa atualização de tela.
Range("A1").Select
Sheets("PLANILHA1").Select
Range("A5:E500").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("CONSOLIDADOJUNTOS").Select
ActiveSheet.Paste
'
Range("A501").Select
Sheets("PLANILHA2").Select
Range("A6:E500").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("CONSOLIDADOJUNTOS").Select
ActiveSheet.Paste
'
End sub

Comment: muito obrigado!!!


React Axios Network Error

Question: Estou fazendo meu primeiro curso de react native com axios e encontrei problemas ao fazer chamadas get.
O codigo relevante é:
api.js:
import axios from "axios";

const api = axios.create({
  baseURL: "https://192.168.15.8:3333",
});

export default api;

index.js:
 async function loadIncidents() {
    if (loading) {
      return;
    }

    if (total > 0 && incidents.length === total) {
      return;
    }

    setLoading(true);

    const response = await api.get("incidents", {
      params: { page },
    });

    setIncidents([...incidents, ...response.data]);
    setTotal(response.headers["x-total-count"]);
    setPage(page + 1);
    setLoading(false);
  }

O erro é:
Comment: nessa parte `const response = await api.get("incidents", {` faltou a barra, exemplo `const response = await api.get("/incidents", {` porque se não coloca aponta para o endereço errado
Comment: Fiz isso que você falou, continua com o mesmo erro
Comment: e não dá para saber! infelizmente problema que não podemos reproduzir
Answer: Verifique se o IP do seu servidor não foi alterado sem querer.
Quando estiver trabalhando com requisições, ou funções assíncronas (await) num geral, utilize sempre try{ ... } catch { ... } para tratar o erro:
async function loadIncidents() {
    if (loading) {
        return;
    }

    if (total > 0 && incidents.length === total) {
        return;
    }

    setLoading(true);
    try {
        const response = await api.get("incidents", {
            params: { page },
        });

        setIncidents([...incidents, ...response.data]);
        setTotal(response.headers["x-total-count"]);
        setPage(page + 1);
    } catch (err) {
        console.log('Ocorreu um erro: ', err)
    }
    setLoading(false);
}

Dessa forma você pode exibir o erro de uma forma mais clara, e sem travar sua aplicação

React Axios Network Error


Loop skips first number of the count

Question: I am unsure why this is skipping what should be the next number. For example, if I input 5 the list then runs 7,8, etc, but the number 6 is dropped. Similar if I input 4 the list then runs 6,7, etc.
Sub CountFromInput()
Dim i As Integer
Dim start As Integer

start = InputBox(Prompt:="Input the first number", Title:="Number Input")
Range("b1") = start

For i = 2 To 14
    Cells(i, 2).Value = start + i
Next i

End Sub

Comment: Yes, that because `i=2` and `2+4` is `6`. You need to start with `i= 1` or is this a kind of trick question?
Comment: No trick intended. I have i = 2 to 14 because the input box puts the initial number in row 1 and I want rows 2 to 14 filled with the concurrent numbers.
Answer: Sub CountFromInput()
Dim i As Integer
Dim start As Integer

start = InputBox(Prompt:="Input the first number", Title:="Number Input")
Range("b1") = start

For i = 1 To 13
    Cells(i+1, 2).Value = start + i
Next i

End Sub

Comment: That's working as expected. If I understand your changes, this started the loop count 1 row down through the use of  'i + 1'  in the loop, and for this reason the count had to be changed to '1 To 13' because the '+1' needed to be account for to achieve the end goal of 14 increments.

Loop skips first number of the count


Existence of a non-square integer $L$ such that $L$ is a quadratic residue modulo $p^n$ for all $n$

Question: The background of this question is on the sequences in $p$-adic integers, in which I originally looked into the following problem:

Can a sequence of perfect squares converge to a non-square value under the $p$-adic metric?

Where the $p$-adic metric is, as usual, defined as
$$d_p(m,n)=p^{-\max\{n\in\mathbb N\colon p^n|(m-n))\}}$$
For $m\neq n$, and $d_p(m,m):=0$
Obviously, it is ask for the existence of a function $f:\mathbb N\to\mathbb Z$ and a non-square number $L$ such that for all $n\in\mathbb N$,
$$f(n)^2-L=p^{g(n)}q(n)$$
Where $g:\mathbb N\to\mathbb N$ is an unbounded function and $q(n)$ is coprime to $n$ for all $n$. Clearly, this is also equivalent to say that the equation
$$x^2\equiv L\pmod{p^n}$$
Is soluble for infinitely many $n$. But we know that if $L$ is a quadratic residue modulo $p^n$, it is also a quadratic residue modulo $p^{n-1}$. Therefore, the statement resolves to the following proposition:

There is (not) a non-square integer $L$ such that it is a square modulo $p^n$ for every $n\in \mathbb N$.

Which I know neither is true or not, nor how to start off decently. Though I have not found any of them, and I believe that such $L$ does not exist, i still cannot find out a complete proof.
The proposition can indeed be generalized into the following

There is (not) a non-$k$th power $L$ such that it is congruent to a $k$th power modulo $p^n$ for all $n\in\mathbb N$

Could you give me a hint to start off? Thanks in advance.
Answer: Not only are there plenty of non-squares which become squares in the $p$-adic numbers $\mathbf{Z}_p$, the phenomena underlying this was
one of the motivating reasons for constucting the $p$-adic numbers in the first place. Here are some hints (only hints!) to get you started.
Notice that
$$2^2 = -1 \mod 5,$$
$$(2 + 5)^2 = 7^2 = -1 \mod 5^2,$$
$$(2 + 5 + 2 \cdot 5^2)^2 = 57^2 = -1 \mod 5^3.$$
So now try the following:
A. Modify $57$ by adding a multiple of $5^3 = 125$ so that $(57 + k \cdot 5^3)^2 \equiv -1 \mod 5^4$
B. Inductively construct $x_n$ with the following properties.

$x_1 = 2$,
$x_n \equiv x_{n-1} \mod 5^{n-1}$,
$x^2_n \equiv -1 \mod 5^{n}$.

C. Think about how general the construction above is. What would happen if one replaces $-1$ and $5$ by $a$ and $p$, where $a$ is a square modulo $p$, and $p$ is an odd prime. What happens when $p = 2$?


PHP - How to use the following JS email validator for PHP

Question: I have seen the following script from jQuery Validation Plugin.
http://docs.jquery.com/Plugins/Validation/Methods/email
email: function(value, element) {
    // contributed by Scott Gonzalez:
    // http://projects.scottsplayground.com/email_address_validation/
    return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

what should I do to make use of it for PHP email validation?
Comment: That's looks needlessly complex.
Answer: To use it in PHP you should discard it entirely.
Instead, use a proper PHP email validator like the built-in filter library, or something like Zend_Validator to check the email.
Quick Example:
$validator = new Zend_Validate_EmailAddress();

if ($validator->isValid($email)) {
    // email appears to be valid
} else {
    // email is invalid; print the reasons
    foreach ($validator->getMessages() as $messageId => $message) {
        echo "Validation failure '$messageId': $message\n";
    }
}

Manual: http://framework.zend.com/manual/en/zend.validate.introduction.html
Comment: Hello webdestroya,

I don't use Zend_Validator. May you give me some hints how to validate the email use the filter library. Or point me to some URL that indicates a tutorial.

Thank you
Comment: @q0987 - Ok, I added an example as well as link to the Zend Reference for the Email Validator.
Comment: Hello webdestroya,

I don't have experience to use Zend framework, is it difficult to let the webpage support Zend?

Thank you
Comment: @q0987 - No it should be very easy. You just include the Zend library with your project, and you should be able to start using it.
Answer: $isValid = preg_match('/^((([a-z]|\d|[!#\$%&\'\*\+\-\/=\?\^_`{\|}~]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])+(\.([a-z]|\d|[!#\$%&\'\*\+\-\/=\?\^_`{\|}~]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(\\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(([a-z]|\d|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])*([a-z]|\d|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])))\.)+(([a-z]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])|(([a-z]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])([a-z]|\d|-|\.|_|~|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])*([a-z]|[\x{00A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}])))$/iu', $email);

Comment: Adding some explanation on how this stuff works would be great to improve your answer


How to compute the confidence interval for the Difference of Two Means with unknown variance?

Question: I have to determine the 90% confidence interval for the difference of Two Means of expenses in products for the cleaning of Palace A and Palace B.
I have the following data: on a sample of 21 cleaners were detected variables:
X = monthly expenditure on cleaning products for building A
Y = monthly expenditure on cleaning products for building B,
which can be taken jointly as normal. The following summaries are obtained:

I'm not able to compute the pooled variance. Could someone please help me? Thanks in advance.
Comment: Seems like you only have 20 observations. As far as I can tell [these steps](https://en.wikipedia.org/wiki/Confidence_interval#Basic_steps) are exactly what you need. Assuming of course that the observations are iid. If not clear, maybe ask more specifically which part is not clear.
Comment: @PaulG I think the point is to be able to calculate the variance of $X$ and the variance of $Y$ with only the four equations given.
Comment: Yes, you're right! My problem is how compute the variance of Y. Can you give me some hints?
Comment: You can calculate the variance of $(X-Y)$, which may be enough for testing the difference of the two means in a paired test.  If you assume independence then you can also calculate the variance of $Y$, but that may not be necessary.
Answer: From the comments I understand the problem is to calculate the sample variances of $X,Y$ given only this information. Let's see if it's possible (I will leave out unbiasedness denominators, i.e. $1/(n-1)$, for simplicity):
For $X$, every component is known:
$$Var[X]=\frac{1}{n}\sum_{i=1}^{20}x_i^2+(\frac{1}{n}\sum_{i=1}^{20}x_i)^2 \tag{1}$$
For $Y$, we only know the last term explicitly.
$$Var[Y]=\frac{1}{n}\sum_{i=1}^{20}y_i^2+(\frac{1}{n}\sum_{i=1}^{20}y_i)^2 \tag{2}$$
Let's expand the last information to see if we can deduct something from it:
$$\sum_{i=1}^{20}(x_i-y_i)^2=\sum_{i=1}^{20}(x_i^2-2x_iy_i+y_i^2)=\sum_{i=1}^{20}x_i^2-2\sum_{i=1}^{20}x_iy_i+\sum_{i=1}^{20}y_i^2 \tag{3}$$
Here we don't know the last 2 terms. So we are stuck (at least I don't see a way to solve for the latter). However, if we assume independence of $X$ and $Y$, which is sensible in this case since there's no reason to assume by default that the expenditures are individually co-dependent, then the covariance is zero, i.e.:
$$Cov[X,Y]=\frac{1}{n}\sum_{i=1}^{20}x_iy_i-\frac{1}{n}\sum_{i=1}^{20}(x_i)\frac{1}{n}\sum_{i=1}^{20}(y_i) \overset{!}{=}0$$
Solving for the first term leads to:
$$
\frac{1}{n}\sum_{i=1}^{20}x_iy_i = \frac{1}{n^2}\sum_{i=1}^{20}x_i\sum_{i=1}^{20}y_i \\
\Leftrightarrow \sum_{i=1}^{20}x_iy_i = \frac{1}{n}\sum_{i=1}^{20}x_i\sum_{i=1}^{20}y_i \\
$$
Now plugging this into $(3)$ leads to
$$\sum_{i=1}^{20}y_i^2+\sum_{i=1}^{20}y_i^2$$
which can now be solved for the last term:
$$
\sum_{i=1}^{20}y_i^2 = \sum_{i=1}^{20}(x_i-y_i)^2 - \sum_{i=1}^{20}x_i^2 + 2\frac{1}{n}\sum_{i=1}^{20}x_i\sum_{i=1}^{20}y_i
$$
which in turn can be used for the variance of $Y$, i.e. $(2)$.
EDIT: @Henry mentions in a comment on the OP that you can calculate the variance of $X-Y$ directly, which is true and makes my answer somewhat of over-engineering. :) Just fyi: You would treat the difference as a random variable $Z=X-Y$ and then apply the variance formula $(1)$ and replace $x_i$ with $x_i-y_i$. Obviously all info is given since $\sum (x_i-y_i)=\sum x_i - \sum y_i$.
Comment: PaulG & Henry: Thank you both very much for your help! Now it's clear!
Comment: Though now that I think about it I'm not sure what effect would dependency between $X,Y$ have when calculating the difference. If they're independent it should lead to the same answer since $Var[X-Y]=Var[X]+Var[Y]$ (under independence)


One sample run test, but with P(+) $\neq \frac{_1}{^2}$

Question: I am trying to find out how to conduct run tests on one sample but with a non 0.5-0.5 underlying occurrence pattern of the two dichotomous values.
For instance +++---++++, but assume that +'s had an underlying probability of 0.8 of happening whereas -'s had 0.2.
Is there a runs test which can address this?
(If so, is there an R function for it?)
Comment: Yes of course. You can alternatively suggest a test that can conduct this analysis.
Comment: There's many different "runs test" test-statistics. What test statistic are you interested in using? The total number of runs of +'s and -'s? The number of runs of one sign? the length of the longest run? ... Note that the widely used [Wald-Wolfowitz](https://en.wikipedia.org/wiki/Wald%E2%80%93Wolfowitz_runs_test)\* runs test conditions on the total +/- counts, so doesn't assume p(+)=0.5. $\:\:$ \*(incorrectly attributed to them, but that's Stigler's law for you)
Comment: Asking for code / packages is off-topic here. Did you try [Googling it](https://www.google.com/search?q=r+runs+test&oq=r+runs+test&gs_l=serp.3..0j0i30l2j0i8i30l7.141717.141717.0.1419184.108.40.206.0.0.0.76.126.96.36.199.msedr...0...1c.1.64.serp..0.1.76.ijRxIo-8Iww)?
Comment: in R, `randtests::runs.test` (on CRAN) can do it
(code `-` as `-1` and `+` as `1`, and set the threshold to `0`)
Answer: If you're interested in a runs test of randomness (which I suppose from your tags, but your text doesn't indicate), the Wald-Wolfowitz runs test conditions on the totals of the +/- counts, so it doesn't assume $p(+)=\frac{1}{2}$.
The Wald-Wolfowitz test (e.g. see Stephens, 1939) is a permutation test based on the total number of runs of both kinds, conditional on the total number of symbols of each kind.
I presume you're interested in too few runs (the usual case), which indicates "clumping of signs".
Your example data has 3 runs, with $n_+=7$ and $n_-=3$. There are 120 arrangements of the symbols, of which 2 have 2 runs (all + followed by all - and vice versa) and of the 3-run cases there are 2 with 7 "+"s in the center and 6 with 3 "-"s in the center, for a total of 10 cases with 3 or fewer runs:
2 runs:
--- +++++++
+++++++ ---

3 runs:
- +++++++ --
-- +++++++ -

+ --- ++++++
++ --- +++++
+++ --- ++++
++++ --- +++
+++++ --- ++
++++++ --- +

so the exact p-value of that case is 10/120.
It's a widely used test, most stats packages offer it in some way, though some only offer the asymptotic approximation (which works better with larger $n_+$ and $n_-$).
If you're interested in testing something else or using some different statistic, you'll need to say more.
(In R, randtests::runs.test (on CRAN) can do the Wald-Wolfowitz test
(code - as -1 and + as 1, and set the threshold to 0); if your sample size is large enough to use the asymptotic approximation, it's easy to code by hand, in any case)
[1] Stevens W.L. (1939),
  "Distribution of groups in a sequence of alternatives"
Annals of Eugenics 9:10-17
Comment: Thank you very much. Great to confirm this. Do you by any chance have any suggestions on a runs test where the underlying distribution can be given and a comparison is made to it?
Comment: What do you intend by 'the distribution can be given'? The pmf for the Wald-Wolfowitz statistic is given in many places, not least the reference in my answer. That same reference has a 'runs of one kind' test which has a pmf with a 'standard' distribution (hypergeometric), but I wouldn't normally recommend it over the Wald-Wolfowitz.


Completely disconnecting a separable metric space by removing a sequence of countable dense subsets

Question: I am wondering if given a separable metric space $X$, it is possible to totally disconnect $X$ by repeatedly removing countable dense subsets.
For example, let $I_1$ be a countable dense subset of $X$, and let $Y_1=X\setminus I_1$. Inductively, define $I_n$ as a countable dense subset of $Y_{n-1}$ and $Y_n=Y_{n-1}\setminus I_n$.
My question is, what happens eventually? Is there some $n\in\mathbb{N}$ for which $Y_n$ is totally disconnected, and if so how would one go about proving it? If not, are there any other relevant results associated with this? What about $Y_\infty:=\bigcap_{i=1}^\infty Y_i=X\setminus (\bigcup_{i=1}^\infty I_i)$ ?
Answer: $(X\setminus I_1)\setminus I_2=X\setminus(I_1\cup I_2)$. The countable union of countable dense sets is still countable dense. So all the sets $I_n$ can be joined into one countable dense set. So the question asks whether a separable metric space is the union of a totally disconnected space and a countable dense set.
For $\mathbb{R}$, this is true: $\mathbb{Q}$ is the countable dense set, $\mathbb{Q}^c$ is totally disconnected.
For $\mathbb{R}^2$, it is false. $\mathbb{R}^2\setminus C$ for $C$ countable is still connected, in fact path-connected. At any of its points $p$, the set of lines through $p$ is uncountable, whereas the lines joining $p$ to points in $C$ is countable; so $\mathbb{R}^2\setminus C$ is full of intersecting lines.


php 5.3 and libxml2 nightmare

Question: My CentOS 5.7 ships with libxml2 2.6.26 that is very outdated and also causes many problems with my current PHP 5.3.3. I need to update libxml2 to 2.7.8 version or at least 2.7.3+ i've readed many posts, used google to find a solution but i'm really unable to solve this issue that is driving me nuts. So please, if there is anyone who knows how to upgrade this library without breaking the OS, please, help me. I need a secure and confirmed answer.
Many thanks in advance :)
Answer: Perhaps you'd be best served by upgrading to CentOS 6.2?  It would at this time get PHP 5.3.3 and libxml2 2.7.6 from the usual repositories.
Comment: One of the strengths of CentOS is that it _doesn't_ change quickly.  But the corollary to this is that cutting-edge versions of software will not be automatically available.  Of course, you're always free to compile from source into some new, separate directory.
Comment: I can't upgrade to 6.2. CentOS is not upgradable, so i would need to install it from scratch. I need a solution to install that library only, i can't believe that it could be so dificult...
Answer: @FidoBoy If you mean you're unable to upgrade CentOS, you can post eh error/message here and someone will assist.
Else, you can upgrade CentOS through yum,
<code>yum upgrade
</code>
Additionally, compiling and installing Libxml 2.7.x version is very much possible. However, you need to make sure that you install the latest version in a separate directory by providing the --prefix option. You will also need to then recompile PHP and provide the path of the libxml 2.7.x library so that it will use the latest and not the one present in the lib directories.
Comment: I'm afraid that i'm not an expert when mantaining a linux server, cause i'm mainly a programmer. However i'm into a library dependencies nightmare and i can find an easy way to escape from it. My system is running CentOS 5.7 with Plesk panel 10.4.4. Using the Plesk repos i've upgraded PHP into PHP53 (php 5.3.3) but this causes a serious problems and bugs with libxml2 (if you use DOMDocument it has many bugs).
Comment: So i think that the easiest way to solve my situation is to install an updated libxml2 into the CentOS system. I didn't knew that i'll need to recompile PHP to do this... this is very annoying cause PHP is installed by plesk and i'm afraid that recompile it could be very difficult.
Comment: So, sincerely i need some advice tips about the best way to go and to solve this situation. I can't believe that CentOS doesn't provide an easy way to run PHP 5.3.x. As i've readed on the CentOS website, installing packages compiling from sources is not recommended and it could be better to install it using yum

php 5.3 and libxml2 nightmare


Let $X_1$ and $X_2$ be two random numbers independently drawn from a set of numbers with replacement

Question: Let $X_1$ and $X_2$ be two random numbers independently drawn from a set of numbers with replacement. Write a formula for $E[(X_1 - X_2)^2]$
I'm not entirely sure how to approach this. Any hints/explanations?
Answer: First notice that
$$
\mathbb{E}\left[\left(X_{1}-X_{2}\right)^{2}\right] = \mathbb{E}\left[X_{1}^{2} - 2 X_{1}X_{2} + X_{2}^{2}\right] =
\mathbb{E}\left[X_{1}^{2}\right] + \mathbb{E}\left[X_{2}^{2}\right] -\mathbb{E}\left[X_{1}X_{2}\right]$$
If they are independent and drawn from the same set then
$$
\mathbb{E}\left[\left(X_{1}-X_{2}\right)^{2}\right] = 2\mathbb{E}\left[X_{1}^{2}\right] - 2\mathbb{E}\left[X_{1}\right]^{2} = 2 \left(\mathbb{E}\left[X_{1}^{2}\right]-\mathbb{E}\left[X_{1}\right]^{2}\right) = 2 Var(X_{1})
$$
Answer: We have that $(X_1-X_2)^2=X_1^2-2X_1X_2+X_2^2$. Hence our expression is equivalent to
$$\mathbb{E}(X_1^2-2X_1X_2+X_2^2)$$
By linearity of expectation, this is equivalent to
$$\mathbb{E}(X_1^2)+\mathbb{E}(X_2^2)-2\mathbb{E}(X_1X_2)$$
Since $X_1$ and $X_2$ are independent, this is equivalent to
$$\mathbb{E}(X_1^2)+\mathbb{E}(X_2^2)-2\mathbb{E}(X_1)\mathbb{E}(X_2)$$


Sprite Kit - Detecting Y due to an impulse and Gravity, if the ball is moving away or Closer to the ground

Question: I'm creating a false shadow for an SKSpriteNode (a Ball) with physicsBody and impulse in Y direction applied to it. I like to decrease the opacity of the shadow which stays on the ground as the ball raise and decrease it back to 100% as it heads back toward the ground. any Idea?
Answer: Yes, use the update method. Then simply test the balls Y position on every update.

Add the ball to your scene.
Add a shadow to your scene.
In the update method of your scene (called at every frame by SpriteKit) move the shadow to the correct coordinate. (Y level of that which the shadow is hitting, X of the ball).
Set the opacity to (300.0-ball.position.y/300.0). 300.0 being the height where the shadow disappears completely.
Comment: Hi Theis, thanks for the reply. the formula didn't quite work for me , maybe I'm doing something wrong. lets assume the bal.postion.y at alpha 100% on the ground is equal to 200 Y and the height where the shadow completely should disappear(0% opacity) be 300 Y. Here would be the calculation of the ball on the ground (according to your formula) 300-200 = 100    100/300 = 0.3 which suppose to be 1 and the calculation when the ball disappears according to the formula you have provided becomes 300-300= 0  0/300 = 1 which should be 0!
Comment: Remember to use floats not ints. (300.0-ball.position.y)/300.0
Comment: Thanks Theis, I have another question regarding this post if you could have a look at would be nice:) Cheers http://stackoverflow.com/questions/23353615/sprite-kit-shadow-on-multiple-moving-object-affected-impulse-and-gravity
Answer: Below is a code sample. You can also use a SKAction to move the object up and down instead of doing it manually like I have in the update method. It all depends on your code and what works best for you.
<code>#import "MyScene.h"

@implementation MyScene
{
    SKSpriteNode *object1;
    SKSpriteNode *shadow;
    BOOL goUp;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        object1 = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
        object1.position = CGPointMake(100, 25);
        [self addChild:object1];

        shadow = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
        shadow.position = CGPointMake(200, 25);
        [self addChild:shadow];

        goUp = true;

    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)update:(CFTimeInterval)currentTime
{
    if((goUp == true) && (object1.position.y == 200))
        goUp = false;

    if((goUp == false) && (object1.position.y == 25))
        goUp = true;

    if(goUp == true)
    {
        object1.position = CGPointMake(object1.position.x, object1.position.y+1);
        shadow.alpha -= 0.005;
    }

    if(goUp == false)
    {
        object1.position = CGPointMake(object1.position.x, object1.position.y-1);
        shadow.alpha += 0.005;
    }
}

@end
</code>
Comment: Hi there, Thanks for the code, I am actually using physics for the ball and on touchesBegan I am applying and impulse like so ball.physicsBody applyImpulse:CGVectorMake(0, 350) , so on touchBegan the ball shoots up up 350 dy and at some point depending on the mass and gravity it will fall back down. my question is how can we monitor that change in +y to -y?


Subspace of $\mathbb{R}^3$

Question:
$\{(x,y,z)\mid 2x^2-8y^2-9z^2\le 1\}$

Why is this not a subspace of $\mathbb{R}^3$?
I know the zero vector is in this set because $ 2(0) - 8(0) - 9(0) \le 1$
But I can't seem to verify if the set is closed under linear combination.
Note: This is NOT for a test/marked assignment, simply practice.
Comment: You can see $v=(\frac12,0,0)$ is in that set, but $2v$ is not.
Comment: When is $t\cdot(x,y,z)$ in the set for all $t\in\mathbb{R}$?
Comment: What happens if you choose two elements that are both equal to 1?
Answer: Note that $\displaystyle v=\left(\frac{1}{\sqrt{2}},0,0\right)$ is a vector in this collection. Is $2\cdot v$ in this collection?
Answer: It is not closed by scalar multiplication. See that $\left(\frac{1}{\sqrt2},0,0\right)$ is in the set, but, for instance, $100 \cdot \left (\frac{1}{\sqrt2}, 0, 0\right)$ is not.
Answer: I think it's because it's not under R^n by scalar multiplication. If u choose
2(1)-8(1)-9(1) = -15
And if u then multiply by a scalar -1, you get 15 which is not defined in the collection.
Comment: This argument is invalid, because $(-1)^2=1$. You have to multiply the arguments, not the equation.

Subspace of $\mathbb{R}^3$