How to compare any value in one matrix with any value in another matrix without using loops?

Question: In the code below I have x any y coordinates of 4 nodes. First two nodes i.e. 1 and 2 fall in category c (matrix c) while the last two i.e 3 and 4 fall in category d (matrix d). "dist" represents distance between all the nodes. Is there any command in matlab using which i can tell if any of the nodes in c is at a distance less than R from any of the nodes in d e.g something like
if distance of any of the nodes in C from any of the nodes in D > R
%do this
end

I can do it using for loops but looking for a shorter way. Thanks
x=[1 2 4 4];
y=[3 5 6 1];
range=R
dist=[0.7 1.6 3.5 3.5; 2.9 0.7 1.6 4.7; 4.9 2.9 0.7 5.5; 3.8 4.3 4.5 0.7];
c=[1 2];
d=[3 4];

Comment: Do you already have `dist`? Or is computing it part of the question? Also, what would the output be in your example, exactly?
Comment: you want to look at [`pdist2`](https://uk.mathworks.com/help/stats/pdist2.html), possible duplicate https://stackoverflow.com/questions/43407122/matrix-of-distances-between-data-in-2d-matlab
Answer: I do not completely understand your question, but from what I get the functions you are looking for are:

A>B - the binary operators in Matlab compares elements
any - returns true if any of the elements are true
pdist2(a,b) - compares distance from all observations in a vector a with all observations in another vector b.

I will gladly update with a more precise answer, but then please provide a complete example of what you want.


Show that certain sequence used in the proof of Wallis product formula is decreasing

Question: Define $I_0 := \pi/2, I_1 := 1$ and
$$
 I_{n+2} := \frac{n+1}{n+2} I_n.
$$
This sequence is monotone decreasing, which could be seen by recognizing that
$$
 I_n = \int_0^{\pi/2} \cos^n(x) \mathrm d x
$$
and $\cos^n(x) \ge \cos^{n+1}(x)$ for $x \in [0,\pi/2]$ (proof by induction and partial integration).
This sequence is used in the proof of Wallis product formula
$$
 \lim_{n \to \infty} \frac{2 \cdot 2}{1 \cdot 3} \cdot  \frac{4 \cdot 4}{3 \cdot 5} \cdots  \frac{2n\cdot 2n}{(2n-1)(2n+1)} = \frac{\pi}{2}
$$
by
$$
 \frac{2 \cdot 2}{1 \cdot 3} \cdot  \frac{4 \cdot 4}{3 \cdot 5} \cdots  \frac{2n\cdot 2n}{(2n-1)(2n+1)} = I_{2n+1} \cdot \frac{1}{I_{2n}} \cdot \frac{2}{\pi}
$$
and with $I_n \ge I_{n+1} \ge I_{n+2}$ we have
$$
 1 \ge \frac{I_{n+1}}{I_n} \ge \frac{I_{n+2}}{I_n} = \frac{n+1}{n+2} \to 1 \quad (n \to \infty)
$$
so that $\frac{I_{n+1}}{I_n} \to 1$ for $n \to \infty$, which yields be manipulating limits Wallis product formula.
Now my question, in the above proof, that $I_n$ is decreasing was proved by using integral calculus, are there any more elementary ones, maybe just using the plain definition of the sequence?
Answer: By applying the exponential generating function transformation for:
$$I_{n+2}-\frac{n+1}{n+2}I_n=0$$
where $\displaystyle P_0(n)=-\frac{n+1}{n+2}$ and $P_2(n)=1$, we get:
$$tY'+Y=tY'''+2Y''$$
which is hell of a equation to be solved:
$$Y(t) = \frac14 i \pi c_1 {\bf L_0}(t)+c_2 {\bf I_0}(t)+c_3 {\bf K_0}(t)$$
where $\bf i$, ${\bf L_n}(x)$, ${\bf I_n}(x)$ and ${\bf K_n}(x)$ are imaginary unit, modified Struve, modified Bessel function of first kind and modified Bessel function of the second kind respectively.
and expansion of the right side yields:
$$Y(t)=\frac14i\pi c_1\sum_{k=1}^{\infty}\frac{2t^{2k-1}}{((2k-1)!!\pi)^2}+c_2\sum_{k=0}^{\infty}\frac{t^{2k}}{4^k(k!)^2}+c_3\sum_{k=0}^{\infty}?$$
Unfortunately I couldn't write the expanded form of modified bessel function of second type.
Anyways using this we can show that:
$$I_n=\frac{(a_2(-1)^n+a_1)\Gamma\left(\frac{n+1}2\right)}{\sqrt{\pi}\;\Gamma\left(\frac n2+1\right)}$$
Using $I_0=\pi/2$ and $I_1=1$:
$$I_n=\frac{\sqrt{\pi}\;\Gamma\left(\frac{n+1}2\right)}{2\Gamma\left(\frac n2+1\right)}$$
Or in friendly notation:
$$I_n=\frac{\sqrt{\pi}(n+2)\left(\frac{n+1}2\right)!}{2(n+1)\left(\frac{n+2}2\right)!}$$
which surely is a decreasing function, see its graph:
Comment: While this is certainly a valid solution, it doesn't strike me as being a *more elementary* approach! :0
Answer: I suppose the answer to your question is simply no. There is no way to prove something involving integrals without integrals(no pun intended:)).


Ngram filter works differently than I thought

Question: I created an index with the following mapping,
curl -XPUT http://ubuntu:9200/ngram-test -d '{
    "settings": {
        "analysis": {
            "filter": {
                "mynGram": {
                    "type": "nGram",
                    "min_gram": 1,
                    "max_gram": 10,
                    "token_chars": [ "letter", "digit" ]
                }
            },
            "analyzer": {
                "domain_analyzer": {
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": ["lowercase", "mynGram"]
                }
            }
        }
    },
    "mappings": {
        "assets": {
            "properties": {
                "domain": {
                    "type": "string",
                    "analyzer": "domain_analyzer"
                },
                "tag": {
                    "include_in_parent": true,
                    "type": "nested",
                    "properties": {
                        "name": {
                            "type": "string",
                            "analyzer": "domain_analyzer"
                        }
                    }
                }
            }
        }
    }
}'; echo

Then I added some documents,
curl http://ubuntu:9200/ngram-test/assets/ -d '{
  "domain": "www.example.com",
  "tag": [
    {
      "name": "IIS"
    },
    {
      "name": "Microsoft ASP.NET"
    }
  ]
}'; echo

But from the query validate,
http://ubuntu:9200/ngram-test/_validate/query?q=tag.name:asp.net&explain

The query has become this,
filtered(tag.name:a tag.name:as tag.name:asp tag.name:asp. tag.name:asp.n tag.name:asp.ne tag.name:asp.net tag.name:s tag.name:sp tag.name:sp. tag.name:sp.n tag.name:sp.ne tag.name:sp.net tag.name:p tag.name:p. tag.name:p.n tag.name:p.ne tag.name:p.net tag.name:. tag.name:.n tag.name:.ne tag.name:.net tag.name:n tag.name:ne tag.name:net tag.name:e tag.name:et tag.name:t)->cache(org.elasticsearch.index.search.nested.NonNestedDocsFilter@ad04e78f)

Totally unexpected. I was expecting asp.net* or *asp.net or *asp.net* like queries, not things like tag.name:a,
That means when I query for asp.net, things like alex will appear in search result as well, that's totally wrong.
Did I miss something?
EDIT
I increased min_gram to 5, and added search_analyzer
        "tag": {
            "include_in_parent": true,
            "type": "nested",
            "properties": {
                "name": {
                    "type": "string",
                    "analyzer": "domain_analyzer",
                    "search_analyzer": "standard"
                }
            }
        }

But from validate, it is still unexpected:
# http://ubuntu:9200/tag-test/assets/_validate/query?explain&q=tag.name:microso
filtered(tag.name:micro tag.name:micros tag.name:microso tag.name:icros tag.name:icroso tag.name:croso)->cache(_type:assets)

Hmm ... it still contains search for icros icroso croso
Answer: An nGram token filter will split your tokens at the character level. If all you need is to split on words, your whitespace tokenizer already does the job.
Using the elyzer tool, you get insights into each step of the analysis process. Using your analyzer, it yields this:
> elyzer --es localhost:9200 --index ngram --analyzer domain_analyzer --text "Microsoft ASP.NET"

TOKENIZER: whitespace
{1:Microsoft}   {2:ASP.NET}
TOKEN_FILTER: lowercase
{1:microsoft}   {2:asp.net}
TOKEN_FILTER: mynGram
{1:m,mi,mic,micr,micro,micros,microso,microsof,microsoft,i,ic,icr,icro,icros,icroso,icrosof,icrosoft,c,cr,cro,cros,croso,crosof,crosoft,r,ro,ros,roso,rosof,rosoft,o,os,oso,osof,osoft,s,so,sof,soft,o,of,oft,f,ft,t}   {2:a,as,asp,asp.,asp.n,asp.ne,asp.net,s,sp,sp.,sp.n,sp.ne,sp.net,p,p.,p.n,p.ne,p.net,.,.n,.ne,.net,n,ne,net,e,et,t}

Although what you seem to be willing is more something like this:
TOKENIZER: whitespace
{1:Microsoft}   {2:ASP.NET}
TOKEN_FILTER: lowercase
{1:microsoft}   {2:asp.net}

And that can be achieved by removing the mynGram token filter from your analyzer.
Comment: Thanks Val, +1 for elyzer tool. I wanted queries for `micro,micros,microso,microsof,microsoft`, not `m,mi,mic,micr,micro,micros,microso,microsof,microsoft` and any other keyword contains `micro` .. Is there anything like that? So far I had to use `*micro*` to accomplish that, which is not recommended
Comment: Oh in that case, you can still use the nGram token filter, but with `min_gram = 5`. Also you probably need to not use the same analyzer at search time, i.e. try to set `"search_analyzer": "standard"` so that your nGram token filter is only used at indexing time.
Comment: You need to use an edge-ngram token filter if you only want the prefixes. After changing that, make sure to reindex your data.


Beta regression

Question: Consider some positive random variables $X^1, X^2$ and $Y\sim Beta(p; 1)$ where $p=\beta_1X^1 + \beta_2X^2$. We have a random sample $\{X^1_i, X^2_i, Y_i\}$. Now, estimating $\beta_1, \beta_2$ is not hard, e.g. using GLM.
Now let's say that we do not observe $X^2$. Is it still possible to consistently estimate $\beta_1$ (i.e. using only a statistic consisting of $\{X^1_i, Y_i\}$)? If not, is there some assumption (normality etc.) for $X^i$ under which we can consistently estimate $\beta_1$?
Answer: Update I realized a problem with my previous post, here's an update with a general philosophy of "marginalizing" out unwanted covariates.
Introduction
Suppose we have a mean model
\begin{align*}
\mathbb{E}[Y|X^1, X^2] &= \beta_0 + \beta_1 X^1 + \beta_2 X^2 \tag{$\heartsuit$}\\
\mathbb{E}[Y|X^1, X^2] &= e^{\beta_0 + \beta_1 X^1 + \beta_2 X^2} \tag{$\diamondsuit$}
\end{align*}
Assuming $X^1 \perp \!\!\! \perp X^2$, we have from $(\heartsuit)$ the marginal model
\begin{align*}
\mathbb{E}[Y|X^1] = \mathbb{E}[\mathbb{E}[Y|X^1, X^2]] = \beta_0 + \beta_1 X^1 + \beta_2\mathbb{E}[X^2|X^1] = \beta_0^* + \beta_1^* X^1
\end{align*}
with $(\beta_0^*, \beta_1^*) = (\beta_0 + \beta_2\mathbb{E}[X^2|X^1], \beta_1)$ or from $(\diamondsuit)$ the marginal model
\begin{align*}
\mathbb{E}[Y|X^1] = \mathbb{E}[\mathbb{E}[Y|X^1, X^2]] = e^{\beta_0^* + \beta_1^* X^1}
\end{align*}
where $(\beta_0^*, \beta_1^*) = (\beta_0 + \log \mathbb{E}[e^{\beta_2 X^2}|X_1], \beta_1)$. In both these cases, where $Y$ is assumed to follow a linear or log-linear model with respect to covariates $X^1, X^2$, we have that the marginal coefficient $\beta_1^*$ is numerically equal to the full conditional model coefficient $\beta_1$.
Consistently estimating a parameter
Generalized estimating equations set up equations of the form
\begin{align*}
\sum_{k=1}^{K} \mathbf{D}_k^\intercal \mathbf{V}_k^{-1}(\mathbf{Y}_k - \boldsymbol{\mu}_k) = \mathbf{0}
\end{align*}
where $\mathbf{Y}_k$ is a vector of observations which are believed with be correlated within itself, but $\mathbf{Y}_k \perp \!\!\! \perp \mathbf{Y}_{k'}$ (vectors are independent of each other). Without diving too deep into the theory of GEEs, the relevance here is that, as long as a mean model is correctly specified, fitting a GEE will always return consistent estimates of the desired coefficients. And a GLM is a special case of a GEE! What this implies, for example, if we have a model with
\begin{align*}
Y_i = \beta_0 + \beta_1 X^1_i + \beta_2 X^2_i + \epsilon_i, \qquad \epsilon \sim F
\end{align*}
for any distribution $F$ with mean 0 and finite second moments (say, $\epsilon_i \sim \text{Exponential}(\frac{1}{2021}) - 2021$), fitting as if these errors were normal would still yield consistent estimates of $(\beta_0, \beta_1, \beta_2)$! Of course, the standard errors for these estimators would be incorrect and would need to be adjusted with sandwich estimators, but the consistency is not affected.
Application to current problem
The mean of $\text{Beta}(p, 1)$ is $\frac{p}{p+1}$, which is not a tractable form to perform the marginalization trick because of the "non-separability" of $X^2$ from $X^1$. My idea was to search for a transformation to make it more tractability, and once close transformation is setting $\widetilde{Y}_i = -\log(Y_i)$, which provides the mean model
\begin{align*}
\mathbb{E}[\widetilde{Y}_i|X^1, X^2] = \frac{1}{p} = \frac{1}{\beta_0 + \beta_1 X^1 + \beta_2 X^2}
\end{align*}
This still isn't quite there, but now if you're willing to accept the functional form
\begin{align*}
p = e^{\beta_0 + \beta_1 X^1 + \beta_2 X^2}
\end{align*}
(which somewhat makes more sence, since this guarantees $p > 0$ as needed in the beta distribution), we have that
\begin{align*}
\mathbb{E}[\widetilde{Y}_i|X^1, X^2] = e^{-\beta_0 - \beta_1 X^1 - \beta_2 X^2}
\end{align*}
and therefore the marginalization trick reveals
\begin{align*}
\mathbb{E}[\widetilde{Y}_i|X^1] = e^{\beta_0^* + \beta_1^* X^1 }
\end{align*}
where $(\beta_0^*, \beta_1^*) = (-\beta_0 +\log \mathbb{E}[e^{-\beta_2 X^2}|X^1], -\beta_1)$. Essentially, we're treating the $X^2$ like errors in a normal regression model, but noting that they may not be mean 0 and therefore would bias the intercept. That's not a problem, since we are interested in $\beta_1$!
Final procedure

Transform $\widetilde{Y} = -\log(Y)$
Regress $\widetilde{Y}$ on $X^1$ with log link with any distribution you want (exponential, normal). The resulting coefficient is consistent for $-\beta_1$.
Comment: Hi @Thomas, let me answer each of your questions accordingly:
*Modeling with wrong distributions in a GLM: As long as the mean model is correct, than yes, we get consistent estimates (but with wrong standard errors). For example, suppose $Y \sim \text{Poisson}(e^{\beta_0 + \beta_1 X})$ and $Y \sim \text{Exp}(e^{-\beta_0 - \beta_1 X})$, which both has $E[Y|X] = e^{\beta_0 + \beta_1 X}$. If the Poisson model were the true model, but I model with the exponential, I'd still get consistent estimates for $\beta_0, \beta_1$.
Comment: This is a very good answer, thanks.
Comment: What do you mean by "normal distribution would work as well"? I am very interested what you mean by this. Is there some similar transformation where we would get something like $\widetilde{Y}\sim N(p,1)$?
Comment: wait, isnt $$\mathbb{E}[\widetilde{Y}|X^1, X^2] = \frac{1}{ \beta_0 + \beta_1 X^1 + \beta_2 X^2}$$?
Comment: I also had a small doubt. Once you derive that $E[\tilde{Y}|X_1]$ is linear in $X_1$, how would you proceed ? Still to make a formal regression you need some hypothesis on the residuals right ? So in theory you would need to know the distribution of $\tilde{Y}|X_1$ . The latter would also depend probably on the parameters $\beta_0, \beta_1$ that you want to find or not ?
Comment: ( I also have the same doubt of @Albert Paradek, now that I read his comment, but I am curious to know also how you would proceed if the expectation were linear )
Comment: Hey AlbertParadek and @Thomas, sorry for my sloppy answer before. I've updated with much more info, hope this helps
Comment: Interesting. But so I understand well that even if in a GLM we are modelling the errors with a wrong distribution, we are always consistent? ( i.e  in the limit of N large the result will always be correct? )
Comment: I would also clarify in your answer in the summary of the procedure that you changed the relation between X and p to a more reasonable one as far as I understood...
Comment: By the way, do you have any suggestion for the numerical approach in my answer?
Comment: I really like this, thanks @TomChen for your answer and time. Last thing that bothers me:

You assumed that we parametrize $p=e^{\beta_0+\beta_1X_1+\beta_2X_2}$. That's
reasonable from the info you had. But actually what I am dealing with is that $p\in [0,1]$ (this holds from its interpretation). First thing I did was super simple- what if we put a linear link and don't care about the interpretation. But, maybe I am looking for some link like logit. Do you have some idea how to proceed in that case? I can put it as a new question and give you like 200 points if you solve that :D
Comment: @AlbertParadek By luck, a logit link extends naturally. With $\text{logit}(p) = \log(\frac{p}{1-p})$, the inverse link is $\text{expit}(x) = \frac{e^x}{1+e^x}$ and we have $p = \text{expit}(\beta_0 + \beta_1 X^1 + \beta_2 X^2)$. This means that $\mathbb{E}[\widetilde{Y}|X^1, X^2] = \frac{1}{p} = 1 + e^{-\beta_0 - \beta_1 X^1 - \beta_2 X^2}$ and once again $X^1, X^2$ are separable. We just need to define outcomes $Y^\dagger = \widetilde{Y} - 1$ and the previous procedure would return consistent estimates for $-\beta_1$.
Comment: Hi @TomChen, thanks again. But unfortunately, it is still only a solution for "special cases". I am working with a few models, not sure which one to use and it would be really helpful to have also the classical linear case AND a case with some link between [-1,1] (i.e. modified expit such as $p=\frac{-1+e^{q}}{1+e^{q}}, q=\beta_0+\beta_1X_1+\beta_2X_2  $ or something similar (we deal with covariance btw).) But this solution does not work for these cases. I opened a new question with this specifically, if you are interested to help a bit more :)
Comment: hups, i meant [1,2] not [-1,1] of course not negative. the question is here https://math.stackexchange.com/q/4351729/615430
Answer: Maybe one can go numerical. In the presence of latent variables we have to maximize the marginal likelyhood, that here reads:
$log L=\sum_i log (\int dx^2_i p(x^1_1)p(x^2_i)y^{(\beta_1x_i^1+\beta_2x^2_i)}(\beta_1x_i^1+\beta_2x^2_i)$ [1]
One could try the EM algorithm and see if it simplifies things (but the nasty additive term mixing the parameters is not simplifying things...).
An other approach is upgrading $x^2_i$,$\beta_1$ and $\beta_2$ all to r.v. with a prior distribution and sample from the posterior or take a $MAP$ for all of them.
This can be done using PyMC3:
https://docs.pymc.io/en/v3/
https://discourse.pymc.io/t/maximum-likelihood-estimation-of-a-bayesian-model/967
I would try to modify the code from here ( the first linear regression example ) in two ways:
https://docs.pymc.io/en/v3/pymc-examples/examples/getting_started.html

The distribution of $Y$ should follow your beta distribution ;
Upgrade $X_2$ to be a random variable with a prior distribution, rather than a fixed one ;

Having done this, you should be able to obtain MAP estimates for all variables and samples from the posterior. Each $x^i_2$ will be than treated as a parameter of the model so you would be sampling a space of dimensions of the number of samples that you have, therefore I am not sure how much this approach would be stable.
Comment: This approach is cool in theory, but ultimately because the "parameter dimension" equals your "sample size dimension", you are left with an identifiability problem. Adding a prior helps stabilize it, but the resulting estimates won't be consistent because we constantly have our sample size dominated by the number of parameters :(.
Comment: Perfect thanks a lot for the feedback!
Comment: But now that I am thinking each time we have a latent variable per sample (e.g. gaussian mixtures) we have one parameter per sample, but this does not prevent us from applying these methods. What is different here?
Comment: Sorry Thomas that I didn't commented your solution, i must say its a bit too advanced for me to understand, a few expressions that have never encountered yet. I tried to look into them a bit but it's quite hard. I am sure that its an interesting solution though, thanks.
Comment: The other solution is much better :)

Beta regression


Installing Boost on CentOS 6.5 (Rocks 6.1.1)

Question: I have a Rocks 6.1.1 (with CentOS 6.5) installed on a VM, and I'm trying to get Boost installed on it.
I tried doing yum install boost-devel. However, it complains about missing dependencies:
   Error: Package: boost-devel-1.41.0-18.el6.i686 (Rocks-6.1.1)
           Requires: libboost_serialization.so.5
   Error: Package: boost-graph-1.41.0-18.el6.i686 (Rocks-6.1.1)
           Requires: libicuuc.so.42
   Error: Package: boost-devel-1.41.0-18.el6.i686 (Rocks-6.1.1)
           Requires: libboost_math_tr1l.so.5
   Error: Package: boost-devel-1.41.0-18.el6.i686 (Rocks-6.1.1)
           Requires: libboost_prg_exec_monitor.so.5
   ...

How do I get libboost installed? Maybe I'm missing a repository, or something like that (a silly mistake).
Thank you very much.
Comment: A little bit further information please? I have the last Rocks release (6.1.1). It's fresh, there isn't anything else to upgrade that I can see.
Answer: My guess (not able to test a Rocks VM build at the moment) is that the Rocks 6.1.1 install doesn't include the latest EPEL release package (for EL6), which includes libboost and its dependencies. You can get the latest package here. Hopefully installing that package and then running a yum install boost-devel will work for you.
Comment: I tried this, and I still get the same error.


how to effectively hide a field (with title) on a form

Question:
Possible Duplicate:
specify $form elements to be excluded from display?

I would like to hide a field on a form using hook_form_ID_alter. The form is owned by another module. This field cannot be unset because it contains a value.
Using CSS {display: none} for the standard field class is not good because the field should be hidden only in specific conditions (which must be determined using php).
In hook_form_ID_alter, I could add an #attribute to the field with a class value e.g. hideme and then use CSS to hide this class. But it will leave the field title (tried).
The field has #prefix set to
 (in this particular case). This prefix precedes the field as well as the title when displayed in a browser. So I could analyze the prefix with regular expression and add a hideme class there. But I am not 100% sure what the #prefix will contain, so the regexp could be complex.
Perhaps there is a better way to hide a field with title on a form?
Answer: You can set the #access property for the form field to FALSE. The form field will not be shown to the users, but its value will be still be available in $form_state['values'] for the submission, and validation handlers.
Using #access is always the suggested way to avoid users can change the value of a form field, and avoid any third-party module depending on that form field starts to raise warnings, or fails to work as expected.
Answer: You can use the hide() function instead of unset(), if you want to retain the value in the field. From the docs:

Hides an element from later rendering.

In simple words, hide() marks the render-able array as already rendered, so that the theme's function will not render it.
Comment: `hide()` shouldn't be used for form elements, it can cause a lot of problems. See the comments on the accepted answer to the duplicate question :)


Secure password less ssh configuration between HP-UX and Linux Suse

Question: I already verify the permission (700 for .ssh and 600 for ./ssh/* ) review the config for the file sshd_config, but the server continu asking for a password, this is the log:
nomgmpr@psoftn $ ssh -vvv email@example.com
OpenSSH_5.9p1+sftpfilecontrol-v1.3-hpn13v12, OpenSSL 0.9.8q 2 Dec 2010
HP-UX Secure Shell-A.05.90.003, HP-UX Secure Shell version
debug1: Reading configuration data /opt/ssh/etc/ssh_config
debug3: RNG is ready, skipping seeding
debug2: ssh_connect: needpriv 0
debug1: Connecting to 126.96.36.199 [220.127.116.11] port 22.
debug1: Connection established.
debug1: identity file /psdb/.ssh/identity type -1
debug1: identity file /psdb/.ssh/identity-cert type -1
debug3: Incorrect RSA1 identifier
debug3: Could not load "/psdb/.ssh/id_rsa" as a RSA1 public key
debug1: identity file /psdb/.ssh/id_rsa type 1
debug1: identity file /psdb/.ssh/id_rsa-cert type -1
debug1: identity file /psdb/.ssh/id_dsa type -1
debug1: identity file /psdb/.ssh/id_dsa-cert type -1
debug1: identity file /psdb/.ssh/id_ecdsa type -1
debug1: identity file /psdb/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1
debug1: match: OpenSSH_5.1 pat OpenSSH*
debug1: Remote is NON-HPN aware
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.9p1+sftpfilecontrol-v1.3-hpn13v12
debug2: fd 4 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "18.104.22.168" from         file "/psdb/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /psdb/.ssh/known_hosts:5
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: email@example.com,ssh-rsa-cert-    firstname.lastname@example.com,ssh-rsa
debug3: RNG is ready, skipping seeding
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: AUTH STATE IS 0
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: firstname.lastname@example.com,email@example.com,ssh-rsa,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-    cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,email@example.com
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,email@example.com
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,email@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,email@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,firstname.lastname@example.com,zlib
debug2: kex_parse_kexinit: none,email@example.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,email@example.com,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,email@example.com,aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,email@example.com,hmac-ripemd160,email@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,email@example.com,hmac-ripemd160,email@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,firstname.lastname@example.com
debug2: kex_parse_kexinit: none,firstname.lastname@example.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: REQUESTED ENC.NAME is 'aes128-ctr'
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: REQUESTED ENC.NAME is 'aes128-ctr'
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 122/256
debug2: bits set: 504/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 2f:6b:0b:9c:27:e3:64:26:d7:7c:dd:87:de:db:de:27
debug3: load_hostkeys: loading entries for host "188.8.131.52" from file "/psdb/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /psdb/.ssh/known_hosts:5
debug3: load_hostkeys: loaded 1 keys
debug1: Host '184.108.40.206' is known and matches the RSA host key.
debug1: Found key in /psdb/.ssh/known_hosts:5
debug2: bits set: 525/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /psdb/.ssh/identity (0)
debug2: key: /psdb/.ssh/id_rsa (6000000000059270)
debug2: key: /psdb/.ssh/id_dsa (0)
debug2: key: /psdb/.ssh/id_ecdsa (0)
debug1: Authentications that can continue: publickey,keyboard-interactive
debug3: start over, passed a different list publickey,keyboard-interactive
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /psdb/.ssh/identity
debug3: no such identity: /psdb/.ssh/identity
debug1: Offering RSA public key: /psdb/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Trying private key: /psdb/.ssh/id_dsa
debug3: no such identity: /psdb/.ssh/id_dsa
debug1: Trying private key: /psdb/.ssh/id_ecdsa
debug3: no such identity: /psdb/.ssh/id_ecdsa
debug2: we did not send a packet, disable method
debug3: authmethod_lookup keyboard-interactive
debug3: remaining preferred: password
debug3: authmethod_is_enabled keyboard-interactive
debug1: Next authentication method: keyboard-interactive
debug2: userauth_kbdint
debug2: we sent a keyboard-interactive packet, wait for reply
debug2: input_userauth_info_req
debug2: input_userauth_info_req: num_prompts 1
Password:

Can you help me with some tips?
Comment: Anything obvious being logged on the server side?
Comment: How many key file pairs do you have in your .ssh directory?
Answer: The more important help can come from the server side if you have access to the server. On the server side, stop sshd. If the server side is HP-UX, /sbin/init.d/secsh stop will do this for you. Then you need to start sshd in debug mode using command /usr/sbin/sshd -ddd. At this point make sure nobody else is coming to this machine via ssh, because, sshd in debug mode will only allow one single incoming connection.
Then you go to your linux machine and issue the command ssh -vvv hpux_server. At that point, compare the debug outputs side by side. I am sure, in no time you will see where the problem is coming from. My bet is on the private and public ssh keys mismatch, due to file formatting but I might be wrong of course.
If you don't get it, please post the debug output from both client and the server, for everyone to see.


PhoneGap/Cordova + JQueryMobile: should HEAD be repeated in all pages?

Question: I'm doing my first steps in this environment and am trying to figure out the best practices. My app includes several HTML pages:
Should I duplicate the whole HEAD part into all the HTML pages,
Or maybe some of it is only required in the initial HTML page?
EXTRA
To my wonder I couldn't find an up-to-date example of a standard HTML header for such app, so with my question I'm also doing a share of knowledge.
Here is the header which, in my understanding, is required to allow the combination of JQM into PhoneGap:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' gap://ready file://* *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; media-src *">
    <title>JQM Test</title>
    <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css" />

    <link rel="stylesheet" type="text/css" href="css/index.css" />

Just for the completeness, in case you are wondering, the cordova part appears at the end of the page:

Answer: Note: Please do not downvote if this answer is wrong, but instead add a note explaining why it is wrong, so that we can all learn.
Nobody responded so I will put my tentative answer which I still need to verify.
In a normal web app, headers must be repeated because the user can bookmark a non-initial page, and get back to it later, so every page must be able to take the role of the initial page.
However with PhoneGap/Cordova we can ensure a specific page is loaded on startup, and this way, because pages are loaded using ajax, we might be able to skip the include parts of the other pages.


Android smoothly rotate on surfaceView with respect to user

Question: In Android, how to give draw a rotating/flipping coin wrt user on SurfaceView. It's very easy to use an animation and show the flipping coin in an ImageView, but I require this on SurfaceView with the same smoothness. Is there any way that I can give flipping animation in an ImageView then take out its content at every instant and then draw it on the SurfaceView continuously?
Answer: you can use Matrix class to perfom these operation on drawing bitmap.
something like
Paint paint = new Paint();
    paint.setAntiAlias(true);
    Matrix needleTransMatrix = new Matrix();
    needleTransMatrix.postRotate(rotationAngle,needleImage.getWidth()/2,needleImage.getHeight());
    needleTransMatrix.postTranslate( centerX+METER_OFFSET-needleImage.getWidth()/2, centerY-needleImage.getHeight());

    Matrix dialTransMatrix = new Matrix();
    dialTransMatrix.postRotate(rotationAngle,dialImage.getWidth()/2,dialImage.getHeight()/2);
    dialTransMatrix.postTranslate( METER_OFFSET,0);

    canvas.drawBitmap(bgImage, METER_OFFSET, 0, paint);
    canvas.drawBitmap(dialImage, dialTransMatrix, paint);
    canvas.drawBitmap(needleImage, needleTransMatrix, paint);

The below is the drawing thread about which i am talking about
private class AnimationThread extends Thread{

    private boolean isRunning = true;
    private int destinationNeedlePosition = NEEDLE_POSITION_ENQURIES;

    public AnimationThread(int destinationNeedlePosition) {
        this.destinationNeedlePosition = destinationNeedlePosition;
    }

    public void cancelAnimation(){
        isRunning = false;
    }

    @Override
    public void run() {

        int destinationAngle = destinationNeedlePosition *45;

        while(isRunning && destinationAngle != rotationAngle){
            if(destinationAngle > rotationAngle)
                rotationAngle++;
            else
                rotationAngle--;
            postInvalidate();
            try {
                sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

Comment: yup i tried using matrix it can be used to get only one instant at a time by scalling .. that won't give a smooth flipping feel!!
Comment: you need to create a thread which would do transition from one position to another and interpolate the positions. The same thing I have done this way to rotate the needle of a meter.
Comment: why are you using the 2 matrices ?
Comment: Those are to animate two separate object in scene. I have not give you complete class that is the snippet from the class
Comment: oh what i what to achieve is a coin flipping wrt user ... smoothly ie each instant of the rotation should be visible . It seems that the code u have give would rotate the image ... The coin rotation i want should be like that somewhat similar to that of flipping page ... the coin should start flipping(reducing size from one edge) then at mid way edge pts 2 user den grows back reverse action happens 2 d othr edge!
Comment: I couldn't find anything the Matrix class to rotate it in z-direction. I would like to suggest you to do this using opengl. Refer the link below for basics. http://insanitydesign.com/wp/projects/nehe-android-ports/
Comment: is it somehow possible to get the coin to flip in an imageView. Then use a thread to extract the image in animation from the imageView at every instant and continuously display the extracted image on canvas
Comment: thanks for the instant help ... although this is not related to the above question it wud b gr8 deal 4 me if u help me out ... I am an indian so is there any way I can try out the in app billing feature in android ... i just wanna do it for learning purpose . The problem is google wallet's merchant account is not yet available for indians. Is there any testing account available for testing purpose!!
Comment: This would not be a good approach. I would recommend you opengl for doing this. As When we do animation on any view including ImageView with Animation class or its decedents That animation is done on overlay and the state does not persist.
Comment: No google has updated the list of countries. Now you can add merchant account from india as well.


Estou com o seguinte erro no VBA "erro em tempo de execução 13 tipos incompatíveis"

Question: Estou criando um código para enviar e-mail automaticamente, porém meu código trava com este erro no Email.Body:

erro em tempo de execução 13 tipos incompatíveis

Estou fazendo algo errado?
Set objeto = CreateObject("Outlook.Application")
Set Email = objeto.createitem(0)

    Email.Display
    Email.to = Cells(2, 6).Value
    Email.cc = Cells(2, 7).Value
    Email.Subject = Cells(2, 3).Value & Cells(9, 6).Value
    **Email.Body** = "Olá, boa tarde!" & Chr(10) & Chr(10) & Cells(2, 2).Value _
    & Cells(2, 8).Value & Cells(9, 6).Value & "." & Chr(10) & Chr(10) & "Temos o total de" & "" & Cells(2, 5).Value _
    & "" & "remessas pendentes." & Chr(10) & Chr(10)

    Email.Send

Comment: Ao pedir ajuda sobre um erro, é útil sempre informar a linha do erro. Além disso, no seu caso, você não colocou no código a declaração das variáveis (que é essencial para saber o tipo esperado pelo VBA, cuja desconformidade é a razão do erro "tipos incompatíveis").
Answer: Eu testei seu código declarando as variáveis objeto e Email como Variant e funcionou normal no meu computador.
Declaração das variáveis como Variant:

Dim objeto As Variant
Dim Email As Variant

Talvez você tenha definido suas variáveis como de outro tipo e isso tenha causado o problema.
Mas, se o problema persistir, nos informe o seu código completo e em qual linha especificamente ocorre o erro.
O código completo ficou assim:
Sub GerarEmail()

    Dim objeto As Variant
    Dim Email As Variant

    Set objeto = CreateObject("Outlook.Application")
    Set Email = objeto.createitem(0)

    Email.Display
    Email.to = Cells(2, 6).Value
    Email.cc = Cells(2, 7).Value
    Email.Subject = Cells(2, 3).Value & Cells(9, 6).Value
    Email.Body = "Olá, boa tarde!" & Chr(10) & Chr(10) & Cells(2, 2).Value _
        & Cells(2, 8).Value & Cells(9, 6).Value & "." & Chr(10) & Chr(10) & "Temos o total de " & "" & Cells(2, 5).Value _
        & "" & "remessas pendentes." & Chr(10) & Chr(10)

End Sub


How to figure out key from key signature?

Question: I know the major scale formula so can easily work out the signature by building the scale from tonic, but I've never learnt it the other way... How to know the key/scale from the signature of sharps/flats.
I know there's links to circle of fifths but for practical purposes do most people just learn by rote, is this generally regarded as the easiest way or are there handy tricks?
Comment: Some may remember my question about using number of fingers to tell the rest of the band what key. Number of fingers up = number of sharps, fingers down = flats. Knowing how many should give the key. Which ones they are? Again, should really be known!
Answer: Last sharp in the key signature is the leading note (7th) of the major key.   Last flat is the 4th. Or last but one is the tonic.
So three sharps - F, C and G - is A major.  G♯ is the 7th note of A major.
Four flats - B, E, A and D -  is A♭ major.   D♭ is the 4th note of A♭ major.   Or, just go back one from D in the list!
When taking 'grade' theory exams, we would jot 'FCGDAEB' and 'BEADGCF' (notice that the order of sharps is the order of flats backwards?) at the top of the page.   After a bit, of course, you just know the keys and signatures.
Also, of course, Father Christmas Goes Down All Escalators Backwards and BEAD Gives Catholic Faith (questionable theology, but memorable).
And for the relationship between relative minor and major:
A Major did some looting and left the army with a bit of money, which he invested in a mine.  He employed a Miner to work it.  It was quite a shallow mine, so for the Major to visit the Miner he had to go down just three steps... (including three letter names, should there be any confusion between A♭ and G♯)
Comment: Father Charles Goes Down And Ends Battle.  Battle Ends And Down Goes Charles' Father.
Comment: I would just note that into the baroque period it wasn't quite as standardized as this since the shift from the modal to the tonal system was still in progress.  You'll see pieces that appear to be notated in Dorian mode but aren't really distinguishable from the minor key -- for example, a piece in G minor with only a B-flat in the key signature, but most if not all of the Es in the piece are lowered to E-flat with accidentals.
Comment: You and User Richard both had nice answers. This answer seem quite helpful, and one thing that I think might improve it would be an image depicting the process (of course, if you've got spare time).
Comment: This is how I do it, still, after all these years.
Comment: A few people have said "last" sharp/flat but nobody I think explicitly explained that. "Last" meaning highest on the stave?
Comment: Probably because the last one ISN'T necessarily the highest?   F, C, G, D.  Up, down, up, down.
Comment: I admit I'm always skeptical of the "go down three steps" approach; it tends to lead to too many errors of thinking the relative key of A major is G-flat minor.
Comment: @Richard - Three steps and three letter names.
Answer: In my experience, most fluent musicians know their key signatures by rote, because it's such a fundamental concept that lays the foundation for almost everything that comes after it. Not knowing key signatures—or having to actively think through them every time—strikes me as akin to doing algebra while still using your fingers for basic addition. ("Oh, I've seen it!" you say. Yes, and we see students trying to write applied chords without knowing key signatures, too. Alas!)
For major key signatures, there are rules for both flat-based and sharp-based key signatures:

If the key signature has flats, then the second-to-last flat is the tonic pitch of the major key. Traditional flat key signatures always follow the order of the flats—BEADGCF—and so a key signature of four flats (B♭, E♭, A♭, D♭) is the key of A♭ major since that is the next-to-last flat.
If the key signature has sharps, then the final sharp is the leading tone; we go up one diatonic half step from that sharp to find tonic. Conveniently, the order of sharps in traditional key signatures is just the reverse of the order of the flats; in this case, FCGDAEB. If a key signature has two sharps—F♯ and C♯—we move up a diatonic half step to D to find the tonic.

There's just one caveat: it isn't immediately obvious how these relate to two key signatures, so we just need to know that C major has nothing in its key signature and F has one flat (B♭).
We can easily reverse engineer this to notate a key signature. If the tonic is B♭, then we want this to be the next-to-last flat, so the key signature will have (again, follow the order of flats) B♭ and E♭.
If you're looking for minor keys, that one is a bit trickier; I always recommend my students think of the minor tonic as being scale-degree 6 of the major scale. This forces them to think through their major scales, and it also prevents the inevitable errors they encounter when they just try to "go down three half steps" (they always seem to do four, or to misspell the minor tonic enharmonically).
Answer: The most painless way to "learn key signatures by rote" is just to play a lot of music in different keys.
If you mostly play genres of music that is only written in a few keys, then not "instantly" recognizing the others isn't going to limit you much anyway.
As a keyboard player, the only ones that make me stop and think a bit (after a few decades of playing!) are the minor keys with 5 or 6 sharps or flats. Seven sharps/flats are easy to remember, because they the same letter-name as none, i.e. C or A.
But hey, when was the last time you saw a piece in D sharp minor anyway - so does it really matter if you have to work that out by counting on your fingers? :)
"Learning key signatures" doesn't always help in any case, if somebody puts a score like these in front of you. Yes, triple flats and triple sharps are a thing. And for extra credit, notice the spectacular typo on the last chord on the line of the first example...
Comment: Thank you for your first example. Gosh, what horrible notation. Alkan wrote your second example and would sometimes stick with an abstruse key rather than doing an enharmonic change, but even Alkan would never have perpetrated the horror of your first example. What piece is it from?
Comment: Yes, triple flats and triple sharps are a thing, but not a very big thing. :)
Comment: I struggle to conceive of a good reason to use notation like these examples! Fortunately they don't come up very often for most people, if at all. One of the joys of being an early musician is that the weirdest things we have to deal with are period notation, not triple-flats...
Comment: I'm not sure I agree. I often use sheet music but I don't know what key it is, I just play/sing it. I suppose I know the key, I just don't know the _name_. If you're playing piano it might be more obvious because you see the relationship to the keys?
Answer: Trying to put Albrecht Hügli's answer in different words (because not everyone is fluent in solmization):
If you have sharps, the root note of the major scale of that key is a semitone over the last sharp:

F# -> semitone over F# -> G major
F#, C#, G#, D# -> semitone over D# -> E major

If you have flats, the root note of the major scale of that key is the flat before the last flat (i.e. the root note is a fourth below/a fifth over the last flat):

Bb -> fourth below -> F major
Bb, Eb -> flat before the last flat: Bb -> Bb major
Bb, Eb, Ab, Db, Gb, Cb -> flat before the last flat: Gb -> Gb major

and so on :)
Answer: Most players will learn them by rote, which becomes the quickest way to recognise them when facing the music.
My suggestion is to use mnemonics - just like we do when learning the line notes on treble clef - 'Every Good Boy Deserves Favour/Football/Flogging...'
I use the same idea to enable students when memorising the string names on guitars. A memorable one is Elephants And Donkeys Grow Big Ears.
So, taking the key names from the circle, we have C G D A E B. With the possibility of omitting C, as it has neither sharps nor flats. Obviously there's F♯ and C♯ to follow if needed - maybe not in early stages of learning?
A six word sentence will do the job - one personal to you, or a silly one will suffice!
Just like the note names for spaces on the treble clef - FACE - we have (F) BEAD (G) to maybe help, or, just make up another mnemonic.
It's a bit of fun, maybe aimed more appropriately at younger people, but it works: still remember Richard Of York Gained Battles In Vain?
Otherwise, by rote generally works - we learned the alphabet that way, didn't we? And there's more in that!
Comment: At school I learned "father Charles goes down and ends battle" for the order of the sharps / keys, and reversed "battle ends and down goes Charles' father" for flats. Still use it - key signature with 5 sharps, which are they? Mumbles mnemonic - FCGDA!
Answer: You want a picture, you got a picture. :)
Comment: Why no Ab minor?
Comment: @HeatherS. Or A-sharp minor, for that matter.
Comment: @Richard, that too.
Comment: It is inconsistent, isn't it? If I were drawing this, I would have left out C# and Cb too. Don't really know why anyone ever uses those keys anyway, when they can use the enharmonic one.
Comment: I'm sure there've been questions asking about what use those keys are.
Answer: This is quite easy if you know the movable do:
The last sharp is Ti, the last flat is Fa. If there are more than one flat the second last flat is do.
Ti and Fa are the leading tones, so the Do and La can easily be defined. Whether major or minor ... this can be decided by identifying the last note: If this is La and there are additional accidentals altering So and Fa to Se and Fe we are in minor.
Comment: I do not know what a "movable do" is. You might expand some of the stuff you're assuming people know because it looks like it's a great answer
Comment: Sure - I am meaning mainly for future readers it is good to explain terms (or at least link to a good description).
Comment: https://en.wikipedia.org/wiki/Solf%C3%A8ge  I will edit my answer and explain it later. At the moment I beg you to look up the do re mi and movable do in wikipedia and in this SE: https://music.stackexchange.com/questions/58015/what-exactly-is-the-tonic-sol-fa-system-and-how-is-it-different-from-solf%c3%a8ge it is very simple and much less complicated than it looks there.
Comment: Thus I'll posts my own explanation as I used to draw it on the blackboard for my classes. We can later delete this comments, o.k,
Comment: @Mr.Boy it might help if you know that "do" here sounds like "doe" rather than "doo."  So whatever it is, a movable do is not a hairstyle.  Homographs can be confusing!
Answer: The easiest way is to just learn the Circle of Fifths and the Circle of Fourths.
Starting in C, the Circle of Fifths will give you the sharp keys, while the Circle of Fourths will give you the flat keys.
So the sharp keys are G, D, A, E, B, F#(Gb)
And the flat keys are F, Bb, Eb, Ab, Db, Gb(F#)
Answer: There's another way based on rote memory: learn how many sharps and flats are in each key.  For example, when you think of the key of A major, you should instantly know that there are three sharps.  And when you think of four flats, you should instantly know it's Ab major or F minor.
Now, you can just see how many sharps or flats are the key signature and know what key it is.
I don't think that memorizing the number of sharps and flats is necessarily any better a way of decoding key signatures than Laurence's excellent answer.  However, in addition to giving you a way to decode key signatures, it gives you another way to communicate with musicians in an ensemble setting.  One way that musicians communicate keys is to use their fingers, where the number of fingers held up shows how many sharps are in the key, or the number of fingers held down shows how many flats are in the key.  If someone holds up one finger and you've memorized the number of sharps and flats in the keys, then you know the tune is in G major (or E minor).
Answer:
Sharp keys: from last sharp

Major = Half-step up
Minor = Whole-step down

Flat keys: last flat = root of a major chord

Minor = Chordal third
Major = Chordal fifth

For sharp keys
Note the three-note (minor) scale formed by each row.

Num. #s
Minor
Last #
Major

1
E
F#
G

2
B
C#
D

3
F#
G#
A

4
C#
D#
E

5
G#
A#
B

6
D#
E#
F#

7
A#
B#
C#

For flat keys
Note the major triad formed by each row.

Num. bs
Last b
Minor
Major

1
Bb
D
F

2
Eb
G
Bb

3
Ab
C
Eb

4
Db
F
Ab

5
Gb
Bb
Db

6
Cb
Eb
Gb

7
Fb
Ab
Cb


PyQt4 Gui that prints loop

Question: I'm trying to learn PyQt4 and has made the following Gui for this purpose - it has no other use.
The code works almost as expected - the only thing that doesn't is the 'else' clause.
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Form(QDialog):
    def __init__ (self, parent=None):
        super(Form, self).__init__(parent)
        self.startButton = QPushButton('Start')
        self.stopButton = QPushButton('Stop')
        self.browser = QTextBrowser()
        self.myLabel = QLabel()
        layout = QVBoxLayout()
        layout.addWidget(self.startButton)
        layout.addWidget(self.stopButton)
        layout.addWidget(self.browser)
        layout.addWidget(self.myLabel)
        self.setLayout(layout)
        self.startButton.setFocus()
        self.startButton.clicked.connect(self.guiLoop)
        self.stopButton.clicked.connect(self.guiLoop)
        self.setWindowTitle('Loop Gui')

    def guiLoop(self):
        state = False
        text = self.sender()
        self.myLabel.setText(text.text())
        time.sleep(1)
        if text.text() == 'Start':
            state = True
        else:
            state = False
        i = 0
        while state:
            time.sleep(.1)
            self.browser.append(str(i))
            QApplication.processEvents()
            i += 1
        else:
            self.browser.append('Stop loop')
            time.sleep(3)
            sys.exit()

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

...I'd expect that the program would print 'Stop loop' in the browser widget before exiting, but it doesn't
       else:
            self.browser.append('Stop loop')
            time.sleep(3)
            sys.exit()

I now have 3 questions:

Why doesn't it print 'Stop loop'
If you imagine that the loop was instead a data stream from a serial connection, how could I print only every 10th value. In the loop that would be 1, 11, 21 ... and so on
General comments on my code

Thx in advance
Answer: Add the following line in your else part
QApplication.processEvents()

like
while state:
    time.sleep(.1)
    if i % 10 == 1:
        self.browser.append(str(i))
        QApplication.processEvents()
    i += 1
else:
    self.browser.append('Stop loop')
    QApplication.processEvents()
    time.sleep(3)
    sys.exit()

Output is like: 1 11 21 31 etc.. and Stop Loop

PyQt4 Gui that prints loop


Debian : SSH port attack continues, cannot change port coz of provider, suggestions?

Question: We have a debian server, which is running our Tomcat hosted applications and we have installed Fail2Ban on it. Everyday morning I see that a lot of people on the internet try to attack the server.
One time, I took action on it, I disabled root login for ssh, changed default SSH port-number, and only specific user-names were allowed to login. Now, because of that, the softwares provided by our Hosting providers for taking backup and monitoring failed. Also the admins couldn't login. For that I had to revert the changes I had done.
Is there any way for this problem. I would hate for some user to get lucky and compromise the server. These are the ideas I have, how do they sound :

Root access only allowed in intranet.
Default port only allowed in Intranet.
Admin has installed SSH certificates in authorized_keys, anyhow that can be useful?

Any other ideas, thank you. :-)
Comment: Do you a firewall in your hosting provider? If so, you can config access to ssh port only to your IP. And if the hosting provider doesn't use internal IPs open it also to the hosting IP range.
Comment: http://unix.stackexchange.com/questions/139285/limit-max-connections-per-ip-address-and-new-connections-per-second-with-iptable Block new connections if they exceeds rate limit.
Answer:
Disable root access completely.
Disable password access completely, only allow key-based login.
Continue to use fail2ban

That's about it and will protect you from anyone "getting lucky" with a password guess.
Comment: The password is complicated enough which cannot be guessed. I cannot disable root access as the backup softwares/ Admins access via root. If that was possible, it would have been very easy for me.. :-)
Comment: Your 2nd point seems interesting. I will contact the admin and will be back. THank you. :-)
Comment: Admins **should** use `sudo` anyway. If you claim the password is secure, what do you worry about?
Comment: Because right now users are trying brute-force which they are failing at, I just want to discourage proficient attackers who can perform some advanced attacks, god knows what.
Comment: Just dissable `password auth` then, most of attacks are to `root` user with dummy passwords.
Comment: I would add that you should setup SSH to listen on a 2nd port (just add a second ```Port``` line), then restrict access to 22/tcp to the hosting providers IP ranges with the firewall.  Use the second SSH port for normal access to the box from outside.  The primary purpose of putting SSH on a non-standard port is to cut down on log traffic, but it serves a secondary purpose as speed-bump security to slow down automated attacks.
Comment: @tgharold : Intriguing, currently I disabled passwords as the providers have there keys in authorized_keys, and it is working good as of now. I would like to know how I can limit the providers, backup software at 22?
Comment: @tgharold : I have 2 keys which start with ssh-rsa in authorized_keys, but one key starts with from and an IP address. That also I would need to isolate to 22.
Comment: I would allow the provider's backup software to login at both 22 and the alternate port (you gain nothing by blocking it).  The bigger gain would be to change the IP firewall (iptables or ufw) so that port 22 is only reachable from the provider's IP address ranges instead of being reachable from the entire world.


Find all integer solutions of $35x^{31} + 33x^{25} + 19x^{21} \equiv 1 \pmod{ 55}$

Question: Find set of all integers x for which the following holds: $35x^{31} + 33x^{25} + 19x^{21} \equiv 1 \pmod {55}$
Since $55 = 5\cdot 11$, simultaneous congruences:
$35x^{31} + 33x^{25} + 19x^{21} \equiv 1 \pmod 5$
$35x^{31} + 33x^{25} + 19x^{21} \equiv 1 \pmod {11}$
And then these can be simplified:
$3x^{25} - x^{21} \equiv 1 \pmod 5$
$2x^{31} - 3x^{21} \equiv 1 \pmod {11}$
How can I proceed from here?
Comment: Do you know Fermat's little theorem (http://en.wikipedia.org/wiki/Fermat_little_theorem)?
Comment: Hint:  for modular arithmetic, you can use \pmod {stuff} and if stuff is only one character you don't need the braces.
Comment: fyi: the accepted answer is incorrect - see my comment there.
Answer: We will find Fermat's Theorem useful. Recall that it says that if $p$ is prime and $a$ is not divisible by $p$, then $a^{p-1}\equiv 1 \pmod{p}$.
We start as you did. Modulo $5$, we arrive at the congruence $3x^{25}-x^{21}\equiv 1\pmod{5}$. If $x$ is a solution, it cannot be divisible by $5$. Thus $x^4\equiv 1\pmod{5}$ by Fermat's Theorem. Thus $x^{24}=(x^4)^6\equiv 1 \pmod{5}$. Similarly,  $x^{20}\equiv 1\pmod{5}$. So our congruence is equivalent to $3x-x\equiv 1\pmod{5}$. Solving $2x\equiv 1\pmod{5}$ is quick: we get $x\equiv 3\pmod{5}$.
For the second congruence, start from your $2x^{31}-3x^{21}\equiv 1\pmod{11}$. Note that $x$ cannot be divisible by $11$. Since $x^{10}\equiv 1\pmod{11}$ (Fermat's Theorem again), we get $x^{31}\equiv x\pmod{11}$ and $x^{20}\equiv 1\pmod{11}$. So our congruence is equivalent to $2x-3x\equiv 1\pmod{11}$, and the solution is $x\equiv -1\pmod{11}$.
So we want to solve $x\equiv 3\pmod{5}$, $x\equiv -1\pmod{11}$. For bigger numbers, we might use the machinery of the Chinese Remainder Theorem. But with these small numbers, it s easiest to look at the numbers that are congruent to $-1$ modulo $11$, and stop when we get a number congruent to $3$ modulo $5$. Start at the smallest positive candidate, $10$. Is it congruent to $3$ modulo $5$? No. Next try $21$ (no), $32$ (no), $43$.  Bingo, got it!
There is a unique solution modulo $55$, so the general solution is $x\equiv 43\pmod{55}$, that is, all numbers of the form $55k+43$, where $k$ ranges over the integers, positive, negative, and $0$.
Comment: The correct solution is $\rm\: x\equiv 43\:\ (mod\ 55).\:$ The above result is incorrect due to an error: $\rm\ mod\ 11\!:\ 19 \equiv -3,\ $ not $\rm\: -2.\ \ $
Comment: @MathGems: Thank you very much for finding the error mod $11$. Luckily, easy o fix.


Observed information matrix is a consistent estimator of the expected information matrix?

Question: I am trying to prove that the observed information matrix evaluated at the weakly consistent maximum likelihood estimator (MLE), is a weakly consistent estimator of the expected information matrix. This is a widely quoted result but nobody gives a reference or a proof (I have exhausted I think the first 20 pages of google results and my stats textbooks)!
Using a weakly consistent sequence of MLEs I can use the weak law of large numbers (WLLN) and the continuous mapping theorem to get the result I want. However I believe the continuous mapping theorem cannot be used. Instead I think the uniform law of large numbers (ULLN) needs to be used. Does anybody know of a reference that has a proof of this? I have an attempt at the ULLN but omit it for now for brevity.
I apologise for the length of this question but notation has to be introduced. The notation is as folows (my proof is at the end).
Assume we have an iid sample of random variables $\{Y_1,\ldots,Y_N\}$ with densities $f(\tilde{Y}|\theta)$, where $\theta\in\Theta\subseteq\mathbb{R}^{k}$ (here $\tilde{Y}$ is a just a general random variable with the same density as any one of the members of the sample). The vector $Y=(Y_1,\ldots,Y_N)^{T}$ is the vector of all the sample vectors where $Y_{i}\in\mathbb{R}^{n}$ for all $i=1,\ldots,N$. The true parameter value of the densities is $\theta_{0}$, and $\hat{\theta}_{N}(Y)$ is the weakly consistent maximum likelihood estimator (MLE) of $\theta_{0}$. Subject to regularity conditions the Fisher Information matrix can be written as
$$I(\theta)=-E_\theta \left[H_{\theta}(\log f(\tilde{Y}|\theta)\right]$$
where ${H}_{\theta}$ is the Hessian matrix. The sample equivalent is
$$I_N(\theta)=\sum_{i=1}^N I_{y_i}(\theta),$$
where $I_{y_i}=-E_\theta \left[H_{\theta}(\log f(Y_{i}|\theta)\right]$. The observed information matrix is;
$J(\theta) = -H_\theta(\log f(y|\theta)$,
(some people demand the matrix is evaluated at $\hat{\theta}$ but some don't). The sample observed information matrix is;
$J_N(\theta)=\sum_{i=1}^N J_{y_i}(\theta)$
where $J_{y_i}(\theta)=-H_\theta(\log f(y_{i}|\theta)$.
I can prove convergence in probability of the estimator $N^{-1}J_N(\theta)$ to $I(\theta)$, but not of $N^{-1}J_{N}(\hat{\theta}_N(Y))$ to $I(\theta_{0})$. Here is my proof so far;
Now $(J_{N}(\theta))_{rs}=-\sum_{i=1}^N (H_\theta(\log f(Y_i|\theta))_{rs}$ is element $(r,s)$ of $J_N(\theta)$, for any $r,s=1,\ldots,k$. If the sample is iid, then by the weak law of large numbers (WLLN), the average of these summands converges in probability to $-E_{\theta}[(H_\theta(\log f(Y_{1}|\theta))_{rs}]=(I_{Y_1}(\theta))_{rs}=(I(\theta))_{rs}$. Thus $N^{-1}(J_N(\theta))_{rs}\overset{P}{\rightarrow}(I(\theta))_{rs}$ for all $r,s=1,\ldots,k$, and so $N^{-1}J_N(\theta)\overset{P}{\rightarrow}I(\theta)$. Unfortunately we cannot simply conclude $N^{-1}J_{N}(\hat{\theta}_N(Y))\overset{P}{\rightarrow}I(\theta_0)$ by using the continuous mapping theorem since $N^{-1}J_{N}(\cdot)$ is not the same function as $I(\cdot)$.
Any help on this would be greatly appreciated.
Comment: Related: [Convergence rate of empirical Fisher information matrix](http://math.stackexchange.com/q/170117/29951).
Comment: @Dapz Please accept my sincerest apologies for not replying to you until now - I made the mistake of assuming nobody would answer. Thank-you for your answer below - I have upvoted it since I can see it is most useful, however I need to spend a little time considering it. Thank-you for your time, and I will reply to your post below soon.
Comment: does my answer below address answer your question?
Answer: $\newcommand{\convp}{\stackrel{P}{\longrightarrow}}$
I guess directly establishing some sort of uniform law of large numbers
is one possible approach.
Here is another.
We want to show that $\frac{J^N(\theta_{MLE})}{N} \convp I(\theta^*)$.
(As you said, we have by the WLLN that $\frac{J^N(\theta)}{N} \convp I(\theta)$. But this doesn't directly help us.)
One possible strategy is to show that
$$|I(\theta^*) - \frac{J^N(\theta^*)}{N}| \convp 0.$$
and
$$
|\frac{J^N(\theta_{MLE})}{N} - \frac{J^N(\theta^*)}{N}| \convp 0
$$
If both of the results are true, then we can combine them to get
$$
|I(\theta^*) - \frac{J^N(\theta_{MLE})}{N}| \convp 0,
$$
which is exactly what we want to show.
The first equation follows from the weak law of large numbers.
The second almost follows from the continuous mapping theorem, but unfortunately our function $g()$ that we want to apply the CMT to changes with $N$:
our $g$ is really $g_N(\theta) := \frac{J^N(\theta)}{N}$. So we
cannot use the CMT.
(Comment: If you
examine the proof of the CMT on Wikipedia,
notice that the set $B_\delta$ they define in their proof for us now
also depends on $n$. We essentially need some sort of equicontinuity at $\theta^*$
over our functions $g_N(\theta)$.)
Fortunately, if you assume that the family $\mathcal{G} = \{g_N | N=1,2,\ldots\}$
is stochastically equicontinuous at $\theta^*$, then it immediately
follows that for $\theta_{MLE} \convp \theta^*$,
\begin{align*}
|g_n(\theta_{MLE}) - g_n(\theta^*)| \convp 0.
\end{align*}
(See here: http://www.cs.berkeley.edu/~jordan/courses/210B-spring07/lectures/stat210b_lecture_12.pdf for a definition of stochastic equicontinuity at $\theta^*$, and a proof of the above fact.)
Therefore, assuming that $\mathcal{G}$ is SE at $\theta^*$, your desired result holds
true and the empirical Fisher information converges to the population Fisher information.
Now, the key question of course is, what sort of conditions do you need
to impose on $\mathcal{G}$ to get SE?
It looks like one way to do this is to establish a Lipshitz condition
on the entire class of functions $\mathcal{G}$ (see here: http://econ.duke.edu/uploads/media_items/uniform-convergence-and-stochastic-equicontinuity.original.pdf ).
Answer: The answer above using stochastic equicontinuity works very well, but here I am answering my own question by using a uniform law of large numbers to show that the observed information matrix is a strongly consistent estimator of the information matrix
, i.e. $N^{-1}J_{N}(\hat{\theta}_{N}(Y))\overset{a.s.}{\longrightarrow}I(\theta_{0})$ if we plug-in a strongly consistent sequence of estimators. I hope it is correct in all details.
We will use $I_{N}=\{1,2,...,N\}$ to be an index set, and let us temporarily adopt the notation $J(\tilde{Y},\theta):=J(\theta)$ in order to be explicit about the dependence of $J(\theta)$ on the random vector $\tilde{Y}$. We shall also work elementwise with $(J(\tilde{Y},\theta))_{rs}$ and $(J_{N}(\theta))_{rs}=\sum\nolimits_{i=1}^{N}(J(Y_{i},\theta))_{rs}$, $r,s=1,...,k$, for this discussion. The function $(J(\cdot,\theta))_{rs}$ is real-valued on the set $\mathbb{R}^{n}\times\Theta^{\circ}$, and we will suppose that it is Lebesgue measurable for every $\theta\in\Theta^{\circ}$. A uniform (strong) law of large numbers defines a set of conditions under which
$\underset{\theta\in\Theta}{\text{sup}}\left|N^{-1}(J_{N}(\theta))_{rs}-E_{\theta}\left[(J(Y_{1},\theta))_{rs}\right]\right|=\nonumber\\
\hspace{60pt}\underset{\theta\in\Theta}{\text{sup}}\left|N^{-1}\sum\nolimits_{i=1}^{N}(J(Y_{i},\theta))_{rs}-(I(\theta))_{rs}\right|\overset{a.s}{\longrightarrow}0\hspace{100pt}(1)$
The conditions that must be satisfied in order that (1) holds are (a) $\Theta^{\circ}$ is a compact set; (b) $(J(\tilde{Y},\theta))_{rs}$ is a continuous function on $\Theta^{\circ}$ with probability 1; (c) for each $\theta\in \Theta^{\circ}$ $(J(\tilde{Y},\theta))_{rs}$ is dominated by a function $h(\tilde{Y})$, i.e. $|(J(\tilde{Y},\theta))_{rs}|<h(\tilde{Y})$; and
(d) for each $\theta\in \Theta^{\circ}$ $E_{\theta}[h(\tilde{Y})]<\infty$;. These conditions come from Jennrich (1969, Theorem 2).
Now for any $y_{i}\in\mathbb{R}^{n}$, $i\in I_{N}$ and $\theta'\in S\subseteq\Theta^{\circ}$, the following inequality obviously holds
$\left|N^{-1}\sum\nolimits_{i=1}^{N}(J(y_{i},\theta'))_{rs}-(I(\theta'))_{rs}\right|\leq\underset{\theta\in S}{\text{sup}}\left|N^{-1}\sum\nolimits_{i=1}^{N}(J(y_{i},\theta))_{rs}-(I(\theta))_{rs}\right|.\hspace{50pt}(2)$
Suppose that $\{\hat{\theta}_{N}(Y)\}$ is a strongly consistent sequence of estimators for $\theta_{0}$, and let $\Theta_{N_{1}}=B_{\delta_{N_{1}}}(\theta_{0})\subseteq K\subseteq \Theta^{\circ}$ be an open ball in $\mathbb{R}^{k}$ with radius $\delta_{N_{1}}\rightarrow 0$ as $N_{1}\rightarrow\infty$, and suppose $K$ is compact. Then since $\hat{\theta}_{N}(Y)\in \Theta_{N_{1}}$ for $N$ sufficiently large enough we have $P[\underset{N}{\text{lim}}\{\hat{\theta}_{N}(Y)\in\Theta_{N_{1}}\}]=1$ for sufficiently large $N$. Together with (2) this implies
$P\left[\underset{N\rightarrow\infty}{\text{lim}}\left\{\left|N^{-1}\sum\nolimits_{i=1}^{N}(J(Y_{i},\hat{\theta}_{N}(Y)))_{rs}-(I(\hat{\theta}_{N}(Y)))_{rs}\right|\leq\right.\right.\nonumber\\
\hspace{40pt}\left.\left.\underset{\theta\in\Theta_{N_{1}}}{\text{sup}}\left|N^{-1}\sum\nolimits_{i=1}^{N}(J(Y_{i},\theta))_{rs}-(I(\theta))_{rs}\right|\right\}\right]=1.\hspace{100pt}(3)$
Now $\Theta_{N_{1}}\subseteq\Theta^{\circ}$ implies conditions (a)-(d) of Jennrich (1969, Theorem 2) apply to $\Theta_{N_{1}}$. Thus (1) and (3) imply
$P\left[\underset{N\rightarrow\infty}{\text{lim}}\left\{\left|N^{-1}\sum\nolimits_{i=1}^{N}(J(Y_{i},\hat{\theta}_{N}(Y)))_{rs}-(I(\hat{\theta}_{N}(Y)))_{rs}\right|=0\right\}\right]=1.\hspace{100pt}(4)$
Since $(I(\hat{\theta}_{N}(Y)))_{rs}\overset{a.s.}{\longrightarrow}I(\theta_{0})$ then (4) implies that $N^{-1}(J_{N}(\hat{\theta}_{N}(Y)))_{rs}\overset{a.s.}{\longrightarrow}(I(\theta_{0}))_{rs}$. Note that (3) holds however small $\Theta_{N_{1}}$ is, and so the result in (4) is independent of the choice of $N_{1}$ other than $N_{1}$ must be chosen such that
$\Theta_{N_{1}}\subseteq \Theta^{\circ}$. This result holds for all $r,s=1,...,k$, and so in terms of matrices we have $N^{-1}J_{N}(\hat{\theta}_{N}(Y))\overset{a.s.}{\longrightarrow}I(\theta_{0})$.


In online convex optimization, what is a leader in FTL algorithm?

Question: I am currently reading into online convex optimization. Can someone please explain  me what exactly is a leader in the Follow-The-Leader algorithm and its variants?
Why is it called Follow-The-Leader?
Answer: The Follow-The-Leader (FTL) algorithm is a simple algorithm for solving online prediction problems. Imagine that you have a committee of experts, each of which suggests a strategy. At each time point, you pick an expert and follow his or her advice, which yields some associated cost (or reward) at the next time step. Your goal is to minimize the total cost/maximize your total reward.
Follow-The-Leader uses a very simple approach: track the performance of all experts over all previous time steps, then select the expert/strategy/etc that has performed the best so far, and follow its advice on the next round. Update everything and choose again.
This approach is called follow the leader, in part because you're following (the advice) of the leading strategy (e.g., the player with the best score in a game). Follow the leader is also the name of a traditional children's game, where everyone imitates the movements of a "leader", which is close enough to the algorithm to be (mildly) funny.
Answer: In the particular case of on-line convex optimization a leader corresponds to a point in the convex domain of optimization. So in principle you have an infinite number of experts.


Sequential Job Schedule using Quartz in Spring

Question: Sequential Job Schedule using Quartz in Spring
I have three or more jobs which depends on their respective previous jobs and they will run in the sequential order. If Job 1 finished Job 2 run and when Job 2 finished Job 3 run. If any error occurred in previous Job then next triggered Jobs will not be fired. I tried to know about Job-chaining using quartz but can't able to get it through.
The Jobs sequence are as per below
Job 1 -> Job 2 -> Job 3

we defined their respective beans in quartz.xml as per below
<beans ...>
    <bean name="scheduler1"
            class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
                <property name="jobClass"
                    value="com.abc.xyz.schedular.Scheduler1" />
                <property name="durability" value="true" />
            </bean>
            <bean id="trigger1"
            class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
                <property name="jobDetail" ref="scheduler1" />
                <property name="cronExpression" value="${scheduler1.cronExpression}" />
            </bean>
          <bean name="scheduler2"
            class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
                <property name="jobClass"
                    value="com.abc.xyz.schedular.Scheduler2" />
                <property name="durability" value="true" />
            </bean>
            <bean id="trigger2"
            class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
                <property name="jobDetail" ref="scheduler2" />
                <property name="cronExpression" value="${scheduler2.cronExpression}" />
            </bean>
            <bean name="scheduler3"
            class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
                <property name="jobClass"
                    value="com.abc.xyz.schedular.Scheduler3" />
                <property name="durability" value="true" />
            </bean>
            <bean id="trigger3"
            class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
                <property name="jobDetail" ref="scheduler3" />
                <property name="cronExpression" value="${scheduler3.cronExpression}" />
            </bean>
        <bean name="jobScheduler"
            class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <property name="triggers">
                <list>
                    <ref bean="trigger1" />
                    <ref bean="trigger2" />
                    <ref bean="trigger3" />
                </list>
            </property>
            <property name="autoStartup" value="${jobScheduler.autoStartup}" />
        </bean>
</beans>

In the above xml files the cron expressions are as follows   scheduler1.cronExpression=0 1 0 * * ?  , scheduler2.cronExpression=0 2 0 * * ?  , scheduler3.cronExpression=0 3 0 * * ? and the jobScheduler.autoStartup=true .
The Schedular class for Scheduler1.java , Scheduler2.java , Scheduler3.java is defined below.
public class Scheduler1 implements Job {

    private static final Logger log = (Logger) LogManager
            .getLogger(Scheduler.class.getName());

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            /*
             *  doing my heavy Process
             */
        } catch (Exception e) {
            log.error("Error in setExpiredAllPlans Schedular1 ");
        }
    }
}

public class Scheduler2 implements Job {

    private static final Logger log = (Logger) LogManager
            .getLogger(Scheduler.class.getName());

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            /*
             *  doing my heavy Process
             */
        } catch (Exception e) {
            log.error("Error in Schedular2 ");
        }
    }
}

public class Scheduler3 implements Job {

    private static final Logger log = (Logger) LogManager
            .getLogger(Scheduler.class.getName());

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            /*
             *  doing my heavy Process
             */
        } catch (Exception e) {
            log.error("Error in setExpiredAllPlans Schedular3 ");
        }
    }
}

Now how would i able to chain the jobs using above configuration because sometimes these heavy process take more than 1 minute so i don't want to start the next fire job until previous job is completed.
If you have any concern/clarification ,please revert me.
Thanks in advance.
Comment: If you want to run them sequentially, why don't you just put them all in the same `Job`?
Comment: as @heenenee said, or if your jobs count is configurable and/or changes over the time, you probably need to use some publish-subscribe layer over your jobs, which may allow you to even change your chain configuration in runtime.
Comment: Hi @heenenee and Maks , Thanks for reply , i can put them into single job that is i m doing currently but i want to configure job chaining in the project thats why i asked the question.
Answer: To chain the execution of your jobs, you will need to implement a JobListener. In its jobWasExecuted event handler you will need to define your job chaining logic so that your jobs are executed in a sequential order regardless of how long the executions of individual jobs take. In that case you will only need a trigger for the very first job (Job 1) as the chained jobs (Job 2 and Job 3) will be triggered "manually" from the event handler.
You can also use the JobChainingJobListener implementation that enables you to programmatically define simple job chains in your application. To define your job chain, you will use the addJobChainLink method.
If you would like a robust solution that will allow you to avoid hard-coding the job chaining logic in your application code while letting you modify your job chaining rules at runtime through a GUI without the need to touch, redeploy and restart your application, you can consider using our product QuartzDesk. QuartzDesk comes with a powerful job chaining engine that allows you to implement all sorts of common job chaining scenarios including scheduled (i.e. not immediate) executions of your chained (target) jobs, multiple target jobs, local/remote target jobs etc.


SQL Query to ASP.NET LINQ Query

Question: What is the equivalent .NET LINQ Query for the below SQL Query?
select *
from customers
where CUSTOMERID not in ('123','321')

Answer:     var exceptList = new List<string> {"123","321"};
    var target = (from item in Db.customers select item.CUSTOMERID ).Except(exceptList);

Answer: For only those two values 123 and 321 you can simple do this:
var results = Customers.Where(c => c.CUSTOMERID != 123 && c.CUSTOMERID != 321);

For a list of values, something like nums where nums is an array of CUSTOMERID you can do this:
var nums = new int[]{123, 321};
var results = Customers.Where(c => !nums.Contains(c.CUSTOMERID));

Answer: from d in Members
where d.CUSTOMERID !=123 || d.CUSTOMERID !=321
select d

Answer:   var ids=new[]{'123','321'};
var results=    from x in Customers
    where !ids.Contains(x)

SQL Query to ASP.NET LINQ Query


Contents of Plist file getting deleted

Question: I am trying to save name and num in a plist stored in bundle, it is getting saved properly but the problem is that once I execute again my application, I am unable to retrive previous data stored in plist.
Here is my code for plist named sample.plist, two texfields name, number:
<code>-(void)viewdidload
{
    [super viewdidload];
    self.path=[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"plist"];
    self.dictionary=[[NSMutabledictionary alloc] initWithContentsOfFile:self.path];
}

-(IBAction)save
{
    if(self.dictionary==nil) {
        self.dictionary=[[NSMutabledictionary alloc]
        initWithObjectsAndKeys:self.name.text,self.number.text,nil];
    } else {
        self.dictionary=[NSMutabledictionary  dictionaryWithContentsofFile:self.path];
        [self.dictionary setobject:self.name.text forKey:self.number.text];
    }

    [self.dictionary writetofile:self.path];
}
</code>
Answer: You can find many question related to this issue in SO. It is a very simple issue your plist is in application bundle which is a read-only information.
If you want to edit the contents move the plist to documents directory when you access the plist for the first time. Consequently always use that path for all read/write operations.
Whenever you need the path of plist use the following method
<code>- (NSString *)savedPlistPath{

NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                          NSUserDomainMask,
                                                          YES)[0];

NSString *filePath = [documents stringByAppendingPathComponent:@"sample.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {

    NSString *bundleFilePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"plist"];
    [fileManager copyItemAtPath:bundleFilePath toPath:filePath error:nil];

}
return filePath;
</code>
}
Comment: @user2440960 Glad to help you. Do accept the answer if it's helpful. Happy Coding :)
Answer: I had a similar issue and perhaps this solution could help. Rather than creating the plist file in xcode and pushing it to the device, write a new file in the document directory.
<code>NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
self.filePath = [documentDirectory stringByAppendingPathComponent:@"sample.plist"];
[self.dictionary writeToFile:self.filePath atomically:YES];
</code>
As @Anupdas points out, the plist in the bundle is read-only.

Contents of Plist file getting deleted


@SchemaValidation issue with weblogic's TransformerFactoryImpl

Question: I have been troubled to the core with an issue with @SchemaValidation in combination with weblogic's TransformerFactoryImpl. I have written a few JAX-WS web services and I need to validate the messages by adding @SchemaValidation. But the problem is in my application I have done some transformation specific stuff where I have to use weblogic.apache.xalan.processor.TransformerFactoryImpl factory otherwise my transformation fails. As soon as I add the system property to specify my transformer factory my deployment starts failing because of @SchemaValidation annotation.It starts giving errors like:
org.xml.sax.SAXParseException:s4s-att-not-allowed: Attribute 'xmlns:tns' cannot appear in element 'schema'
Everything works fine if I remove the @SchemaValidation annotation. Can anyone please help me, it has become a major issue and i couldnt find much help on net.
Thanks a lot,
A
Comment: Hello, any help on this one please???
Answer: As per the following error you gave the issue may not be related to TransformerFactoryImpl but rather in your WSDL. Can you try removing the namespace declaration for xmlns:tns from the schema element? so that it uses name space declared at global level i.e. declared in the definitions tag.


YouTube - MP4 to MP3 messes up

Question: It's supposed to download all the videos in the playlist and convert them to mp3. But all this does is make the mp4's and 1 empty mp3 with a number higher than the max mp4. My newbie brain doesn't know how to fix this...
var ytpl = require('ytpl');
var fs = require('fs-extra');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var binaries = require('ffmpeg-static');
var ytdl = require('ytdl-core');

var output_dir = path.join(__dirname+"/dl");

ytpl("PL8n8S4mVUWvprlN2dCAMoIo6h47ZwR_gn", (err, pl) => {
    if(err) throw err;

    let c = 0;

    pl.items.forEach((i) => {
        ytdl(i.url_simple+"", { filter: 'audioonly' }).pipe(fs.createWriteStream(output_dir+"/"+c+".mp4")).on('finish', () => {
            console.log("Finished MP4 DL, starting conversion...");
            ffmpeg(output_dir+"/"+c+".mp4")
                .setFfmpegPath(binaries.path)
                .format('mp3')
                .audioBitrate(320)
                .output(fs.createWriteStream(output_dir+"/"+c+".mp3"))
                .on('end', () => {
                    console.log("Finished MP3 Convert...");
                })
                .run();
        });
        c++;
    });

});

Answer: Fixed using an example by ytdl-core Link
Fixed code:
var ytpl = require('ytpl');
var fs = require('fs-extra');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var binaries = require('ffmpeg-static');
var sanitize = require('sanitize-filename');
var ytdl = require('ytdl-core');

var output_dir = path.join(__dirname+"/dl");

ytpl("PL8n8S4mVUWvprlN2dCAMoIo6h47ZwR_gn", (err, pl) => {
    if(err) throw err;

    for (const i of pl.items) {
        let stream = ytdl(i.id, {
            filter: 'audioonly'
        });

        ffmpeg(stream)
            .audioBitrate(320)
            .save(`${output_dir}/${sanitize(i.title + " (by " + i.author.name + ")")}.mp3`)
            .on('end', () => {
                console.log("Done! Downloaded \""+i.title + " (by " + i.author.name + ")"+"\"");
            });
    }
});

YouTube - MP4 to MP3 messes up


Julia JuMP - `max` in the goal function Error: No method matching isless

Question: There is a error in my code, can anyone help me please?
My code:
function funP(u, τ::Float64)
w = (τ*max(u, 0)) + ((1-τ)*max(-u, 0))
return w
end

τ = 0.2
modelquant = Model(with_optimizer(OSQP.Optimizer))
@variable(modelquant, β[i=0:1])
@variable(modelquant, erro[1:T])

@constraint(modelquant,[i=1:T], erro[i] >=  contratos[i] - β[0] - β[1]*spot[i])
@constraint(modelquant,[i=1:T], erro[i] >= -contratos[i] + β[0] + β[1]*spot[i])

@objective(modelquant, Min, sum(funP(erro[i], τ) for i=1:T))

optimize!(modelquant)
objective_value(modelquant)
 = JuMP.value.(β)

The error is:

julia> @objective(modelquant, Min, sum(funP(erro[i], τ) for i=1:T))
ERROR: MethodError: no method matching isless(::Int64, ::VariableRef)
Closest candidates are:
isless(::Missing, ::Any) at missing.jl:87
isless(::Real, ::AbstractFloat) at operators.jl:166
isless(::Integer, ::ForwardDiff.Dual{Ty,V,N} where N where V) where Ty at C:\Users\Fernanda.julia\packages\ForwardDiff\kU1ce\src\dual.jl:140
...
Stacktrace:
[1] max(::VariableRef, ::Int64) at .\operators.jl:417
[2] funP(::VariableRef, ::Float64) at .\REPL[8]:2
[3] macro expansion at C:\Users\Fernanda.julia\packages\MutableArithmetics\bPWR4\src\rewrite.jl:276 [inlined]
[4] macro expansion at C:\Users\Fernanda.julia\packages\JuMP\qhoVb\src\macros.jl:830 [inlined]
[5] top-level scope at .\REPL[20]:1

Thank you so much!
Answer: You need to re-engineer your model to replace the max function with a binary variable.
In your case the code will look like this (check for typos):
@variable(modelquant, erro_neg[1:T], Bin)
@variable(modelquant, erro_pos[1:T], Bin)
@constraint(modelquant,for i=1:T,erro_neg[i]+erro_pos[i]==1)
@constraint(modelquant,for i=1:T,erro[i]*erro_pos[i] >= 0)
@constraint(modelquant,for i=1:T,erro[i]*erro_neg[i] <= 0)
@objective(modelquant, Min, sum( τ*erro_neg[i]*erro[i]+ (1-τ)*erro[i]*erro_npos[i] for i=1:T))

Please note that in my version you could actually safely remove the Bin condition from erro_neg and erro_pos and the model will still work (you need to test empirically what your solver prefers)


Decomposition of polynomial into irreducible polynomials

Question: I'm preparing to my algebra exam. And I have problem and I have no idea how to solve it.

Given polynomial
  $$x^4+4x^3+4x^2+1.$$
  The task is find expansion of the polynomial as a product of irreducible polynomials in $\mathbb{R}$.

I will be happy if you show me the way how to solve such problems
Comment: @Fly: $\mathbb C$ is a quadratic extension, so every polynomial over $\mathbb R$ of degree greater than two is reducible. The only ireducible polynomials are linear ones and quadratics with negative determinant.
Comment: @FlybyNight - you get a real factorisation into quadratics by organising the roots into conjugate pairs.
Answer: Hint:$$x^4+4x^3+4x^2+1=(x+1)^4-2(x+1)^2+2$$
$$(x+1)^4-2(x+1)^2+2=((x+1)^2-1)^2+1=((x+1)^2-1+i)((x+1)^2-1-i)$$
This will allow you to get the roots of the equation $x^4+4x^3+4x^2+1=0$. By multiplying the monomials with conjugate roots you will get the real quadratic factors.
To see why this always works:
It is a fact that if $P$ is a polynomial such that $P(z)=0$, then $P(\bar z)=0$.
Finally:
$$(x-(a+bi))(x-(a-bi))=x^2-2ax+a^2+b^2$$
Which is a real quadratic polynomial.
Comment: How do you get the first equality just like that?
Comment: I used an online software that gets all of the roots of a polynomial. After seeing that all of them were in the form -1+... I tried substituting $x=u-1$ and it worked.
Answer: It suffices to show that $f(x)=x^4+4x^3+4x^2+1$ has no linear factors over $\mathbb{Z}_3$: $f(0)=f(1)=1$ and $f(2)=2$, so $f(x)$ has no linear factors.  Then $f(x)$ must factor to two quadratic polynomials: $$f(x)=(ax^2+bx+c)(ux^2+vx+w)$$ We then have that $au=1$.  Multiplying the first polynomial by $u$ and the second by $a$, we may assume that $a=u=1$.  Equating the coefficients of the powers of $x$, we have
$$
\begin{eqnarray*}
4&=&v+b\\
4&=&w+c+bv\\
0&=&bw+cv\\
1&=&cw
\end{eqnarray*}
$$
Some algebra shows that $$\begin{eqnarray*}
 b&=& 2+\sqrt{2 \left(1+\sqrt{2}\right)}\\c&=& 1+\sqrt{2}+\sqrt{2 \left(1+\sqrt{2}\right)} \\ v&=& 2-\sqrt{2 \left(1+\sqrt{2}\right)}\\ w&=& 1+\sqrt{2}-\sqrt{2 \left(1+\sqrt{2}\right)}
\end{eqnarray*}
$$
So, letting $\alpha=1+\sqrt{2}$, we see that $x^4+4x^3+4x^2+1$ factors to $$\left(x^2+\left(2+\sqrt{2\alpha}\right)x+\alpha+\sqrt{2\alpha}\right)\left(x^2+\left(2-\sqrt{2\alpha}\right)x+\alpha-\sqrt{2\alpha}\right).$$
Comment: Of course, a system! I would say that the ideal answer would be a combination of Mark Bennet's and Marek's comment to estabilish that  the asked factorization exists, combined with the system of equations.


How to make package of .exe file with required .dll and lib (opencv) files in visual studio 2010 C++

Question: I have created an opencv project which include path having headers,*.lib and *.dll files of opencv in project properties and I have hard coded path of header files of opencv in .cpp that I have created.Let us say I need to give this project to customer,hence I only need to give .exe file of execution directly in customer system.
so please anyone help how I can do packaging of path of .dll and .lib along with my project .exe file. or are there any other way where i can send .exe file to customer which comprises of all i.e can execute opencv and also my logic in customers system.
thanks in advance and sharing answer is always appreciable.
Comment: do you want to distribute a binary(exe) or a project(code/sln/vcproj) ?
Comment: "I have hard coded path of header files" - ouch. that sounds like a total sockshot.
Comment: hey @berak, I need to send .exe file only and hard code means making headers of opencv to include in to my .c++ file.
Comment: If you only need to give an executable to your customer, then why do you want to include static library files (.lib)? Any compiled code used by your executable should be linked in automatically from your static libraries during the build process.
Comment: Hey @JBentley, thats not happening, the build .exe file doesn't comprises(linked) all those lib and dll auotmatically.
Comment: @santosh If you are able to build and run your executable (which from your comments, it appears you are), then the .lib files are linked and it is just the .dll files you need to worry about.
Answer: Either use relative paths for everything you're using and ship them along (if you're allowed to, check the licenses first!!), or if you need to give your users the source code (as a VS solution) and you can't/don't want to hardcode the paths of your tools use CMake to generate the solution files.
If you need to package binaries together along with your executable (and still, you're allowed to), you can use an installer packaging app like Inno Setup
You need to make sure every dependency needed by your application is shipped otherwise your customers won't be able to run your software. To find out dependencies in a Win environment, try to use the dependency tool shipped with each copy of visual studio.
As a sidenote: you shouldn't be putting complete absolute paths in the include directives, e.g.
#include "C:\mysystem\helloworld\app\opencv\header.h"

because that is the sure recipe for compilation problems or unnecessary preprocessing when deploying or redistributing your sources. This doesn't apply to binaries: they just need to find the compiled dependencies/tools they need.
Comment: hey, thanks for reply,yea @Marco of course, i don't want to show my source code to my customer. and about the path hard coding,in my c++ file. I need to give the path for header files of the opencv(open source library).I have tried to built by putting the header file,.lib and .dll in debug folder of project still it's not working for me.i.e my .exe file is not packed of all above files.
Comment: can you run your app after you've compiled it? What error do you get?
Comment: i can able to run in my system,as i have installed opencv in my PC and *.dll that are present can pick up and run. but when I tried to install in my friends PC(which doesn't contain opencv installed) it's not working.
Comment: That is what you're trying to do.. then you need to deploy along with your executable all the openCV dlls needed. Use the depencency lookup tool to find those out and ship them along with your app.
Answer: Visual Studio 2010 Does not provide the package creation for C++.
In My Opinion you have to use third party software like
[Advanced Installer]1 who search for the required dll and
provide us to create the package as an installer.
And for the paths you have included in the Header.
If You Have a .exe then it does not matter for running your application.
Hope this will help you.


point $P$ is Centroid If Area of$\triangle APB = $Area of $\triangle BPC = $Area of $\triangle CPA$.

Question: In a $\triangle ABC$ If $P$ be a point which is Inside the $\triangle ABC$ such that
Area of$\triangle APB = $Area of $\triangle BPC = $Area of $\triangle CPA$.
Then how can I prove that the point $P$ is the centroid of $\triangle ABC$?
Answer: Hints:

In $\triangle ABC$, let $M$ be the middle of $BC$, prove that $|\triangle ABM| = |\triangle ACM|$ (consider the heights perpendicular to $AM$).
Let $E$ be an interior point of $\angle BAC$. Prove that $|\triangle ABE| = |\triangle ACE|$ if and only if the point of intersection of $|AE|$ and $|BC|$ is $M$ (observe, that $|AE|$ is common to both and thus does not change the ratio).

Good luck ;-)
Answer: Coordinates are not really necessary. If
$$ [APB]=[APC], $$
then $P$ lies on the median from the $A$-vertex in the triangle $ABC$, since, if you put $P_A = AP\cap BC$, you have:
$$1=\frac{[APB]}{[APC]}=\frac{[AP_A B]}{[AP_A C]}=\frac{BP_A}{CP_A}.$$
Since the argument works for all the vertices, $P$ lies in the intersection of the medians, i.e. $P$ is the centroid of $ABC$.
Answer: If we are allowed to use Coordinate Geometry, let $A(x_1,y_1),B(x_2,y_2),C(x_3,y_3)$ and $P(h,k)$
Now, calculate the area of the $3$ triangles using this (Article#25) and then equate them to form two equations of $h,k$ and solve for $h,k.$
Comment: Thanks
lab bhattacharjee


proving the symmetric and transitive properties of an equivalence relation

Question: Let $S$ be a non-empty set, $A$ be the set of all functions from $S$ to $S$, and $B$ be the set of all bijective functions from $S$ to $S$. Define the following relation on A:
$$f \sim g \iff \exists h \in B \mid fh=g$$
where $fh$ is the composition of $f$ and $h$. Is this an equivalence relation on $A$?
This is what I have so far:
$ah=a ⇒  a^{-1} ah=a^{-1} a ⇒ eh=e⇒ h=e$ and $e \in B$ therfore $a \sim a$
Because $e$ is the identity element and all sets have an identity element, therefore it is reflexive.
$$ah=b ⇒ a^{-1} ah=a^{-1} b⇒ eh=a^{-1} b⇒ h=a^{-1} b$$
$$bh=a⇒ b^{-1} bh=b^{-1} a⇒ eh=b^{-1} a⇒ h=b^{-1} a$$
But I do not know how to show that since $a \sim b$ then $b \sim a$. I think I have a start but I'm not sure how to show this.
I am also not sure how to show that it is transitive because I keep solving for h but don't know how to show this.
Answer: There is nothing that says that $a$ is bijective or that $a^{-1}$ exists.
But $h$ is bijective and $h^{-1}$ exists
Reflexive $a\sim a$
Let $h$ be the identity function.
Symmetric $a\sim b \implies b\sim a$
There exists an $h$ such that $a\circ h = b$
$b\circ h^{-1} = a$
Transitive $a\sim b$ and $b\sim c \implies a\sim c$
$a\circ h = b\\
b\circ g = c\\
a\circ (h\circ g) = c$
The composition of two bijections is a bijection.
Answer: For symmetry show that $ah=b$ implies $bh^{-1}=a$ .
For transitivity show that $ah_1=b$ and $bh_2=c$ implies $ah=c$ where $h=h_1 h_2$.
Comment: I see! thank you!


Generator for $C_{0}(\Omega)$

Question: Let $\Omega$ be a locally compact Hausdorff space, and suppose that the $C^{*}$-algebra $C_{0}(\Omega)$ is generated by a sequence of projections $(p_{n})_{n=1}^{\infty}$. Show that the hermitian element $h=\sum_{n=1}^{\infty}p_{n}/3^{n}$ generates $C_{0}(\Omega)$.
I think it is quite clear that the $C^{*}$-subalgebra generated by $h$ is in $C_{0}(\Omega)$ but I can't show equality.
Answer: For any positive linear functional $\tau$ on $C_0(\Omega)$,
$$
\tau(h) \geq \frac{1}{3^n}\tau(p_n) \quad\forall n\in \mathbb{N}
$$
Hence, if $\tau(h) = 0$, then $\tau = 0$. Conclude that $C^{\ast}(h) = C_0(\Omega)$
Comment: The following theorem : If $a$ is a normal element of a C* algebra, then there is a positive linear functional $\tau$ such that $\|a\| = |\tau(a)|$
Comment: May I know what is the result you are using here to get the conclusion?
Comment: Could you elaborate? I am not sure how to get the result from the fact that if $\tau(h) = 0$, then $\tau = 0$...

Generator for $C_{0}(\Omega)$