Homeomorphisms between lens spaces and Poincaré conjecture

Question: It is known that $L(p,q)\cong L(p,q')$ if and only if $q\equiv \pm (q')^{\pm 1}\mod p$ where
$$
L(p,q)\cong{\mathbb{S}^3}/\mathord{\sim}
$$
is the quotient space generated by the $\mathbb{Z}_p$-action
$$
\rho(z_1,z_2)=(\zeta z_1,\zeta^q z_2)
$$
where $\zeta$ is a pth root of unity and $p$ and $q$ are coprimes.
Right to left implication can be proven using Reidemeister torsion (https://www3.nd.edu/~lnicolae/Torsion.pdf page 104). However, left to right proof is supposed to be verified easily by the reader. Does someone know how to construct the homeomorphism between $L(p,q)$ and $L(p,q')$ assuming the congruence on $q$ and $q'$?
EXTRA QUESTION:
Does the Poincaré conjecture imply that every closed compact orientable 3-manifold with $\pi_1(X)\cong \mathbb{Z}_p$ is a lens space?
Comment: I  think your last question is true. The universal cover is a closed, connected, simply connected 3-manifold, and hence a sphere, so $X$ is a quotient of $S^3$ by some covering space action by $\mathbb Z/p$.
Comment: An answer to your first question is [here](https://math.stackexchange.com/questions/2788149/diffeomorphism-of-lens-spaces) (although I admit to not reading it carefully.)
Comment: @AndresMejia how could you be sure that there are no more $\mathbb{Z}_p$-actions on $S^3$ other than the ones that define lens spaces?
Comment: great question. I don't think I have a good answer off the top of my head. I hope somebody with a better background in low dimensional topology has something to say.
Comment: For your extra question: PC is not enough but it is a special case of Thurston's Geometrization Conjecture (called Spherical Space Form Conjecture), proven by Perelman.
Comment: @AndresMejia Uniqueness of the $\mathbb{Z}_p$-action on $S^3$ follows from linear algebra. If $M$ is a matrix in $O(4)$ such that $M^p = I$, then the minimal polynomial of $M$ divides $x^p - 1$. You can then use some primary decomposition theorem to show that $M$ is always conjugate to some combination of classical $2 \times 2$ rotation matrices plus reflections. (This should, in fact, be true for higher-dimensional spheres as well.)
Answer: For two roots of unity $\lambda,\mu$ define $\rho_{\lambda,\mu}: (z,w)\mapsto (\lambda z, \mu w)$. Then $\rho_{\lambda,\mu}$ and $\rho_{\lambda,\bar\mu}$ are conjugate via the orthogonal map
$$
(z,w)\mapsto (z, \bar{w}).
$$
This shows that $L(p,q)$ is homeomorphic to $L(p,-q)$.
Next, if $q$ is coprime to the orders of $\lambda,\mu$ then the subgroup generated by $\rho_{\lambda,\mu}$ is the same as the one generated by $(\rho_{\lambda,\mu})^q$.
Lastly, assuming that $p$ is coprime to $q$, $q'$,
$qq'\equiv 1$  mod $p$, and
$$
\lambda=\exp(i 2\pi/p), \mu= \exp(i 2\pi q/p),
\mu'= \exp(i 2\pi q'/p),
$$
then
$$
\lambda^{q'}= \exp(i 2\pi q'/p),
$$
$$
\mu^{q'}= \exp(i 2\pi /p).
$$
In other words, the subgroup generated by $\rho_{\lambda,\mu}$ is the same as generated by
$\rho_{\mu',\lambda}$. However, $\rho_{\mu',\lambda}$ is
conjugate in $U(2)$ to $\rho_{\lambda,\mu'}$ via
$$
(z,w)\mapsto (w,z).
$$
This proves that $L(p,q)$ is homeomorphic to $L(p,q')$.
Lastly, for your extra question, PC is not enough, you need SSFC. The later was proven by Perelman in the same paper(s) where he proves the Poincare Conjecture.


Como restaurar banco de dados para recuperar dados?

Question: O Mysql existe algum sistema de backup automático? Na minha tabela havia um campo CNPJ que continha CNPJs e CPFs, era do tipo varchar alterei para o tipo int e ferrou com tudo.
Comment: Sempre faça um backup antes de alterar qualquer coisa em um banco de dados que esteja em produção.
Comment: Você configurou para fazer back up no servidor? alguma cron?  algo para fazer automaticamente? senão e bem pouco provável.
Comment: @GuilhermeNascimento Não sei se é duplicata. Pela descrição, ele quer saber se o mysql faria, sozinho, por padrão, algum backup que permitiria que ele recuperasse os dados que perdeu.
Comment: Eu também acho que esses são os únicos caminhos pra backup. Por isso a resposta aqui seria "não", @GuilhermeNascimento
Comment: @bfavaretto pois é, me foquei no titulo e na primeira linha, ajustei a pergunta para evitar confusões
Answer: Creio eu que não exista nada pronto, a não ser que o teu servidor/administradores tenham implementado algo, então só entrando em contato com o suporte técnico e/ou administradores do servidor para solicitar uma cópia do backup.
Caso não tenha nada implementado em teu servidor não será possível restaurar.
Quando for fazer modificações é sempre bom testar na sua máquina local primeiro, para evitar estes tipos de problemas.
Sugestões de backup para evitar problemas futuros:

Como fazer backup diários de Banco de Dados Mysql?
Realizar backup automatico MySQL
Backup automático com MySQL
Backup MySQL com Event Scheduler


How can one identify key signatures with flats?

Question: I know that when a key signature has sharps, the major key indicated is always one half step above the last sharp in the key signature.
For example, the key of D Major has two sharps -- F# and C#, in that order -- D is one half step higher than the last sharp.
Can anyone give me a similar easy rule that works with flat key signatures?
Comment: This is a legitimate question that doesn't seem to have an answer on this site. It's just worded very poorly. The question should be, "How do I determine what key a piece is in, given the key signature?". OP has answered half of this in his comment. Remember, SE is supposed to be a repository of answers, like a question-driven Wikipedia. And it's actually entirely valid to ask a question and answer it yourself.
Comment: @GeneralNuisance - does it seem odd that a question is posed, and an answer to an almost identical question is posted in the comments? No-one has been impolite, but the question itself is in dire need of rephrasing, wouldn't you agree?
Comment: To find the name of a key signature with sharps, look at the sharp farthest to the right. The key signature is the note a half step above that last sharp. Key signatures can specify major or minor keys. To determine the name of a minor key, find the name of the key in major and then count backwards three half steps.
Comment: @Care Witthoft -very faint possibility, but not really a dupe. And how obvious to someone who doesn't understand?
Comment: @MattPutnam - of course it's entirely valid, but it's exactly what the OP didn't do. I can't understand why that comment was made. True, a poorly worded question. In need of an edit?
Comment: @Tim I considered editing, but that would involve completely rewriting it, and that seems against the spirit of the site. But either we should do that, or delete this and I'll repost it worded better (and answer it myself). I actually think it's a really great question that deserves a solid answer on here.
Comment: Hey, guys, can we try to be a little more friendly to the poor person who asked this question, who clearly is new here and is trying to contribute? All of the things you note about this question are true, but there are so many more thoughtful ways to make them clear. We all start somewhere, and there is nothing *malicious* or ill-intended about this question. There's no need to get snappy here.
Comment: Pigion -- Thank you for your contribution to this site! This should answer your question: https://music.stackexchange.com/a/54011/27335 I will repost some of it in an answer here.
Answer: You can find the second to last flat, and that's the major key signature. Flats are easy!
For example:

The second to last flat is on G, so Gb Major.
This trick works for all of them except, of course, F Major, which has one flat:

Just remember that one flat is F Major.
For minor key signatures, you can count up six scale degrees on the major key signature, or count down three half steps. I usually count down, because for me that's easier, but it's technically more correct to view the minor key signature as starting on the sixth scale degree.
(Taken from another answer of mine from this question: Finding The Key Of A Song,  which I initially misunderstood and this answer isn't relevant to it, but I am glad I left it up!)
Answer: The last flat shown is the fourth note from the scale of the key. Thus just Bb shown, this is the fourth note from F, the key in question.
A key sig.can also mean minor key, so with last (only) flat as Bb, count up two tones to the key note, of D. Thus, Dm.
Answer: The fastest way I know is to form a major chord having the key signature's last flat as its root. The third of the chord will be the tonic of the corresponding minor scale; the fifth of the chord will be the tonic of the corresponding major scale.
In the table below, the columns show the last given flat for each key signature and the corresponding relative major and minor keys; the rows show major chords.

# flats
Last flat
Minor key
Major key

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

With sharp keys, not only does a half-step up from the last sharp give the major scale, but a whole-step down gives the minor scale.
See also this post.


Calculating Residues around given poles using limit fomula

Question: i am having an issue with a sample question I have been given and I cannot figure out the correct way of dealing with the question.
I have to calculate the following residue of $\displaystyle\frac{\cos(z^3) - 4e^z}{z^8 - z}$ at $z = 0$
So, usually I would use the limit formula like this one: Linky
but I do not know what the order of the function is, i guess that is my main problem.  I know 7 is incorrect but how do I go about finding the order?
Thanks
Answer: Let $f(z)=\frac{\cos(z^3)-4e^z}{z^8-z}$.  Note that the numerator approaches $-3$ as $z\to 0$.  Furthermore, note that $z^8-z=z(z^7-1)$ has a zero of order $1$.  Then, we deduce that $f$ has a pole of order $1$ and
$$\begin{align}
\text{Res}\left(\frac{\cos(z^3)-4e^z}{z^8-z},z=0\right)&=\lim_{z\to 0}\left(\frac{\cos(z^3)-4e^z}{z^7-1}\right)\\\\
&=3
\end{align}$$
Comment: I kept thinking (stupidly) the pole was of order 8, thanks
Comment: @user It would have been a pole of order $8$ if not for the presence of the term $-z$ in the denominator. ;-))
Answer: Just expand the function at $z=0$ and use the definition of residue, i.e. IT IS the coefficient of $1/z$:
$$f(z):=\frac{\cos(z^3) - 4e^z}{z^8 - z}=\frac{1+O(z^6) - 4(1+z+O(z^2))}{-z(1-z^7)}
=\frac{3}{z}+O(1)$$
Therefore the residue at $z=0$ is $3$.
P.S. You can also compute the residue in using the linked formula: the pole $z=0$ has order $1$ therefore the residue is given by the limit
$$\lim_{z\to 0} zf(z)=\lim_{z\to 0}\frac{\cos(z^3) - 4e^z}{z^7 - 1}=\frac{1-4}{-1}=3.$$
Answer: Expanding the numerator around $z=0$ you get
$$ \cos(z^3) - 4 e^z = -3 - 4z + \mathcal O(z^6). $$
For the denominator you have instead
$$z(z^7-1) = -z + \mathcal O(z^8),$$
so that you can write the whole expression as
$$\frac{3}{z} + \mathcal O(1). $$
We conclude that the pole is of order 1, and the residue is 3.


Contrast if regression coefficients of two predictors are equals

Question: I've got this model:
model <- lm(biomass ~ salin+ph+k+na+zn, data = sparData)

with sparData dataset:
   obs loc tip.veg biomass salin   ph       k      na      zn
1    1  OI    DVEG     676    33 5.00 1441.67 35184.5 16.4524
2    2  OI    DVEG     516    35 4.75 1299.19 28170.4 13.9852
3    3  OI    DVEG    1052    32 4.20 1154.27 26455.0 15.3276
4    4  OI    DVEG     868    30 4.40 1045.15 25072.9 17.3128
5    5  OI    DVEG    1008    33 5.55  521.62 31664.2 22.3312
16  16  SI    DVEG     396    30 3.25  646.65 17307.4 31.2865
17  17  SI    DVEG     352    27 3.35  514.03 12822.0 30.1652
18  18  SI    DVEG     328    29 3.20  350.73  8582.6 28.5901
19  19  SI    DVEG     392    34 3.35  496.29 12369.5 19.8795
20  20  SI    DVEG     236    36 3.30  580.92 14731.9 18.5056
31  31  SM    DVEG     824    26 4.85  936.26 20436.0 18.9875
32  32  SM    DVEG    1196    29 4.60  894.79 12519.9 20.9687
33  33  SM    DVEG    1960    25 5.20  941.36 18979.0 23.9841
34  34  SM    DVEG    2080    26 4.75 1038.79 22986.1 19.9727
35  35  SM    DVEG    1764    26 5.20  898.05 11704.5 21.3864

How can I contrast if regression coefficients of k and zn are equals? I'm a little lost in this.
Coeff. are:
Call:
lm(formula = biomass ~ salin + ph + k + na + zn, data = spartData)

Residuals:
    Min      1Q  Median      3Q     Max
-707.55 -177.46   30.92  144.08  643.21

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) 2473.99632 3030.81508   0.816   0.4354
salin        -87.22784   53.34201  -1.635   0.1364
ph           415.44896  220.27220   1.886   0.0919 .
k              0.02802    0.64766   0.043   0.9664
na            -0.01272    0.02475  -0.514   0.6197
zn           -24.00394   40.06079  -0.599   0.5638
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 387.9 on 9 degrees of freedom
Multiple R-squared:  0.738, Adjusted R-squared:  0.5925
F-statistic: 5.071 on 5 and 9 DF,  p-value: 0.01739

Thanks in advance!
Comment: Yes, make an hypothesis testing. Check if they are equals. :/ Thanks!
Comment: What do you mean by "how can I contrast" ? Do you mean "how can I test" ?
Answer: The standard approach for testing linear hypothesis, like the one you are dealing with, is to compare the full or unrestricted model with the restricted model though the log-likelihood ratio test. In your case the full model is the one you fitted, whereas the restricted model, i.e., the one under $H_0$, is
$biomass = \beta_0 + \beta_1*salin+\beta_2*ph+\beta_3*k+\beta_4*na+\beta_3*zn+\epsilon\\
         \qquad\quad= \beta_0 + \beta_1*salin+\beta_2*ph+\beta_3*(k+zn)+\beta_4*na+\epsilon$
Notice that here the estimated $(\beta_0,\beta_1,\beta_2,\beta_4)$ can be different from the corresponding estimates from the full model, but you don't care about them. What you care is how much lower is the log-likelihood of the restricted model when compared to the full model. For this you need to compare their log-likelihoods through a log-likelihood ratio test.
In R you can do it like this
 # let's load the data, I've copy-pasted your dataset in a text file
> sparData <- read.table("sparData.txt",
                         header = TRUE,row.names = "obs")

 # fit the unrestricted model
> mod.spar <- lm(biomass ~ salin+ph+k+na+zn, data = sparData)
> summary(mod.spar)

Call:
lm(formula = biomass ~ salin + ph + k + na + zn, data = sparData)

Residuals:
    Min      1Q  Median      3Q     Max
-707.55 -177.46   30.92  144.08  643.21

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) 2473.99632 3030.81508   0.816   0.4354
salin        -87.22784   53.34201  -1.635   0.1364
ph           415.44896  220.27220   1.886   0.0919 .
k              0.02802    0.64766   0.043   0.9664
na            -0.01272    0.02475  -0.514   0.6197
zn           -24.00394   40.06079  -0.599   0.5638
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 387.9 on 9 degrees of freedom
Multiple R-squared:  0.738, Adjusted R-squared:  0.5925
F-statistic: 5.071 on 5 and 9 DF,  p-value: 0.01739

  # fit the restricted model under H0: k = zn
> mod.spar.res <- lm(biomass ~ salin+ph+I(k+zn)+na, data = sparData)

  # log-likelihood ratio test for the restricted vs unrestricted
> anova(mod.spar.res, mod.spar)
Analysis of Variance Table

Model 1: biomass ~ salin + ph + I(k + zn) + na
Model 2: biomass ~ salin + ph + k + na + zn
  Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     10 1409289
2      9 1353912  1     55377 0.3681  0.559

 # which is equivalent to:
> library(car)
> linearHypothesis(mod.spar, "k = zn")
Linear hypothesis test

Hypothesis:
k - zn = 0

Model 1: restricted model
Model 2: biomass ~ salin + ph + k + na + zn

  Res.Df     RSS Df Sum of Sq      F Pr(>F)
1     10 1409289
2      9 1353912  1     55377 0.3681  0.559

As you can see from the p-value, you cannot reject your $H_0$.
Comment: Thank you!  I will explore this functionality till ur next fully detailed answer. By the way I've edited mi question to include the full dataset ;)
Comment: I've edited the answer, giving few more details. Hope it helps.


Using OR in conditional fields

Question: I have several select fields in content type, which is more like Q/A & most of the answers are YES/NO. It's like tree flow, all question are dependent upon answer of previous question.
I am using condition fields & field conditional state module for this purpose. OR can be implemented by help of FIELD CONDITIONAL STATE as module description says --
Module supports AND/OR functionality for control fields which means:

    AND - all choices must be selected to control the filed
      (example: field A will be visible when in field B option 1 and option 2 is selected)
    OR - any choice will control field
      (example: field A will be visible when in field B option 1 or option 2 is selected).

But I have some fields(e.g. Field C) which should be appear on selection of YES of Field A or NO of Field B.
Is it possible to achieve it by this module or some other way by any contributed module. I am not looking for making my own form by FORM API as I have around 60 question in content type & it will become so messy to manage in code.
Edited --
I have searched & got option such as using OR in conditional field in this manner-
field_atleast_50_capital is visible when field_property_deriving has value "No".
OR
field_atleast_50_capital is visible when field_arrangements_90_subsidiary has value "Yes".

But it doesn't work..
Answer: just an observation from looking at the module documentation:
there is a note under interaction with other dependencies on the Edit dependency page which says this:
When this dependent has more than one dependee, how should this condition be evaluated against the others?
Note that sets will be grouped this way: ANDs AND ORs AND XORs
with a selection for AND, OR and XOR
This would indicate that you

define your dependency of field C on A,
define your dependency of field C on B
and select OR as your interaction with other dependencies
Comment: The OR option which you are talking about has been tested by me, which comes from condition field module at standalone configuration of the module, which I accessed from module page itself. I put one condition & check it to interact with other condition as OR and added one more condition, but it didn't work..
Comment: I have the same problem, I used conditional fields with "OR" and it didn't work as expected. I had to set values manually in one of the field but it doesn't even work in another form I am making.

Using OR in conditional fields


ORA-00980: synonym translation is no longer valid

Question: O que significa este erro?
Quais as ações que podem ser tomadas para remediá-lo?
Comment: Como não há quem responda veja este [artigo](http://www.dba-oracle.com/sf_ora_00980_synonym_translation_is_no_longer_valid.htm)
Comment: @ramaral Não abre aqui pra mim. Fiz a pergunta porque nenhum dos artigos que pesquisei me dá uma resposta objetiva.
Comment: O que quer dizer com "Não abre aqui pra mim."?
Comment: @ramaral O site não abre. Diz que o endereço está indisponível.
Comment: O link está correto. Eu clico em [artigo](http://www.dba-oracle.com/sf_ora_00980_synonym_translation_is_no_longer_valid.htm) no meu comentário e abre.
Comment: http://www.dba-oracle.com/sf_ora_00980_synonym_translation_is_no_longer_valid.htm
Comment: Será que vocês poderiam, se não for pedir muito, **responder à pergunta em português**? Se eu quisesse a resposta do Google em inglês não teria vindo aqui.
Answer: Tradução livre da documentação oficial
ORA-00980: A tradução do sinônimo não é mais válida
Causa: Um sinônimo não foi traduzido para um objeto de destino legal. Isso pode ocorrer por uma das seguintes razões:

O esquema de destino não existe.

O objeto de destino não existe.

O sinônimo especifica um link de banco de dados (database link) incorreto.

O sinônimo não é versionado mas específica um objeto de destino versionado.

Ação: Mude a definição do sinônimo para que o sinônimo aponte para um objeto de destino legal.

Trocando em miúdos, alguém mexeu no objeto de destino (ou até mesmo no SCHEMA, db link, etc) e esqueceu de recriar / excluir o sinônimo.


the improper integral $\int_0^{\infty} (1+x)^{-1}e^{-x}dx$

Question: I wish to calculate the improper integral
$\int_0^{\infty} (1+x)^{-1}e^{-x}dx$. How shoud we start? Give me some hint.
Comment: This integral requires [exponential integral](http://en.wikipedia.org/wiki/Exponential_integral)
Comment: This is known as the [Gompertz constant](http://mathworld.wolfram.com/GompertzConstant.html).
Answer: Make a substitution $u = 1 + x$; this transforms the integral into
$$e \int_{1}^\infty \frac{e^{-u}}{u} du = -e \, \text{Ei}(-1) \approx .596$$
where $\text{Ei}$ is the exponential integral, which cannot be written in terms of elementary functions.
Comment: Does the integral converge in the usual sense?
Comment: @Yamamoto Yes, by comparison to the function $e^{-x}$, which is integrable.
Comment: Thanks a lot. I didin't know the exponential integral.


GridView Delete Confirm ButtonField

Question: I want to delete a row form my gridview with confirm by javascript.
My gridview looks like:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
        <Columns>
            <asp:ButtonField CommandName="delete" Text="Delete" />
        </Columns>
    </asp:GridView>

I already tried do with TempleField and it works, but the problem is getting the value of the select row to delete from database.
I tried like this:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
        <Columns>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="btnSave" runat="server" Text="Delete" OnClientClick="return confirm('Do you want to delete?')" CommandName="delete" />
            </ItemTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>

And tried get the value like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
        if (e.CommandName == "delete")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            string id = GridView1.Rows[index].Cells[1].Text.ToString();
            Response.Write(id);
        }
}

But it throws a FormatException on
int index = Convert.ToInt32(e.CommandArgument);

Can somebody help me? Sorry but my English is bad.
Comment: You need to add `CommandArgument='<%# Eval("Yourrowidfieldvalue") %>'` in the button tag
Comment: What did you add as your command argument ? If your using it as index then use `<%# ((GridViewRow) Container).RowIndex %>`
Comment: _"I tried like this"_ So did it work? If not, what happened instead?
Comment: Ok, i added now give me that error:"ArgumentOutOfRangeException" on line 'string id = GridView1.Rows[index].Cells[1].Text.ToString();'
Comment: I'm using the same way you are in your second example. But in the end of my confirm I use `;` and the delete is `Delete`. Works fine.
Answer: You need to set the CommandArgument from the button tag
 <asp:Button ID="btnSave" runat="server" Text="Delete" OnClientClick="return confirm('Do you want to delete?')" CommandName="delete" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>

Here is more info on how to use CommandArgument
Comment: Thaks for the help, and for the people who try it.

GridView Delete Confirm ButtonField


How to set views pager item size programmatically?

Question: I want to set views pager size programmatically. I have tried below code to set pager size.
$view = \Drupal\views\Views::getView('english_chart');
$view->pager['items_per_page'] = 5;
$view->execute();

It's not working and showing this error:
ResponseText: Error: Cannot use object of type Drupal\views\Plugin\views\pager\Some as array ....
Answer: The object returned from $views->pager is an object implementing ViewsPluginInterface and extending PagerPluginBase.
If you look at the methods in PagerPluginBase you will see the setItemsPerPage method.
So you should be able to do something like:
$view->pager->setItemsPerPage(5);


Como colorir células de uma tabela com Javascript?

Question: Ja fiz o codigo da tabela, porem não sei como colorir as colunas.

Comment: Dei uma formatada no seu código, mas precisa arrumar a indentação e ver se realmente falta um `}` no final. Por favor, dê uma revisada no código se possível. Tirei umas linhas em branco apenas para evitar a necessidade de fazer scroll ao ler seu código. Para alterar/corrigir, basta um clique em [edit].
Answer: Podes usar CSS para fazer isso:
td:nth-child(odd){
    background-color: yellow;
}
td:nth-child(even){
    background-color: green;
}

jsFiddle: https://jsfiddle.net/07q0dub2/
Se quiseres mesmo usar JavaScript podes fazer assim no loop interno:
for (j = 1; j <= col; j++) {
    var cor = (j % 2 == 0) ? 'green' : 'yellow';
    conteudo += "" + (i + "," + j) + "	"
}

jsFiddle: https://jsfiddle.net/07q0dub2/2/


Injective map from sigma algebras to partitions

Question: I want to show that for every sigma-algebra $\mathfrak A$, you can define for all $x\in X$ the set of all $A_x:=\bigcap_{A\in \mathfrak A,x\in A}A$( a partition of the set $X$) and that this map is injective. Thus, for different sigma-algebras we get different partitions. Does anybody have a good hint how to start with this?
Answer: This is not true.  Look at the Borel sets on $[0,1]$ and the power set on $[0,1]$  At each point, this intersection is the point itself. They are clearly different $\sigma$-algebras.
Comment: For some value of "clearly" ;)
Comment: This construction is done in almost any basic analysis book like Royden's.


One question about conditional expectation

Question: Let $X,Y\in L^1(\Omega,\mathfrak{F}, P)$, where $\mathfrak{F}$ is a $\sigma$-algebra and $P$ is the probability measure on $\Omega$. If $E[X|Y]=Y$ a.s. $E[Y|X]=X$ a.s., then prove that $X=Y$ a.s..
Now I can prove it is true for $X,Y$ are simple function, but I stuck at how to pass it to general measurable functions.
Comment: Can you extend it by the monotone convergence theorem?
Comment: possible dublicate of https://math.stackexchange.com/questions/666843/if-exy-y-almost-surely-and-eyx-x-almost-surely-then-x-y-almost-surel
Comment: @E-A, To use monotone convergence theorem, we should find pairs of simple functions $(X_n,Y_n)$ satisfying the above conditions. I failed to find them.
Comment: @aurora_borealis, yeah I thought you proved it simple functions; either way; this question as Shashi pointed out, is a duplicate
Comment: @Shashi I see...many thanks!
Answer: Hints:

Show that $$\mathbb{E}[(X-Y) 1_{\{X>q\} \cap \{Y \leq q\}}] =0$$ for any $q \in \mathbb{R}$.
Prove that $$\{X>Y\} = \bigcup_{q \in \mathbb{Q}} \{Y \leq q\} \cap \{X>q\}$$
Combine Step 1 and 2 to conclude that $\mathbb{P}(X>Y)=0$.
Interchange the roles of $X$ and $Y$ to get $\mathbb{P}(Y>X)=0$. Thus $$\mathbb{P}(X \neq Y) = \mathbb{P}(X>Y)+\mathbb{P}(Y>X)=0.$$


Zabbix icmp pinger processes more than 75% busy

Question: In my zabbix server I have this error.

Zabbix icmp pinger processes more than 75% busy

Anybody have some advice how fix it?
Regards
Comment: O.k I found how fix it.

http://it.kuchuk.net/2013/04/zabbix.html
Answer: The answer from Mick's comment:
Problem: Zabbix proxy poller processes more than 75% busy
Solution: In zabbix_server.conf

StartPollers=20

Problem: Zabbix icmp pinger processes more than 75% busy
Solution: In zabbix_server.conf

StartPingers=10
  StartDiscoverers=10

Problem: Zabbix unreachable poller processes more than 75% busy
Solution: In zabbix_server.conf

StartPollersUnreachable=10


indent lines equally with echo

Question: I am struggling to cat a file while print it along with some words.
For example:
/root/file contains:
line1
line2
line3

Script:
#!/bin/bash
echo -en "Printing Line of the file: `cat /root/file`\n"

Result:
Printing Line of the file: line1
 line2
 line3

Expected Result:
Printing Line of the file:  line1
                            line2
                            line3

How can I get the output I want?
Comment: Thanks. But its still printing the same way only. My expectation is to use single space on first line and from second line onwards need to use three tabs
Comment: Is the output format what you positively need? It isn't very easy for humans or computers to read. Something like `echo Printing... ; sed 's/^/    /' /root/file` is easier to code and easier to read its output.
Answer: Just bash:
(
    first="Printing Line of the file:"
    IFS=
    read -r line
    printf "%*s %s\n" ${#first} "$first" "$line"
    while read -r line; do
        printf "%*s %s\n" ${#first} "" "$line"
    done
) < file

Printing Line of the file: line1
                           line2
                           line3

With printf, you can use * as the field width, then provide a number in the arguments. I'm running this in a subshell so altering IFS does not affect the parent shell.

To achieve your written goal with the tabs:
echo "Printing Line of the file: $(awk -v ORS="\n\t\t\t" 1 file)"

Answer: You can use existing utilities like this:
myvar="Printing Line of the file:  "
size=${#myvar}
# getting the right size is the tricky part
var_final_size=$((size+5))
echo -en "${myvar}`awk -F\; -v fmt="%${var_final_size}s\n" '{if (NR==1) {print $1} else {printf fmt, $1}}'  test.txt`\n"

Or you can script something like this:
#!/bin/bash
myvar="Printing Line of the file:  "
size=${#myvar}
var_counter=0
for r in  `cat /root/file`
do
   var_size=${#r}
   var_final_size=$((size+var_size))
   if [ $var_counter -eq 0 ]; then
      printf "%${var_final_size}s\n" "${myvar}${r}"
   else
      printf "%${var_final_size}s\n" "${r}"
   fi
   var_counter=$((var_counter+1))
done

Output
Printing Line of the file: line1
                           line2
                           line3

Answer: The following prints line by line -- right justify at 32 characters:
awk '{ printf("%32s\n", $0) }'

Assuming same length lines... we could peak at first line, count characters and set the pattern for printf on all lines.
awk 'NR==1 { f = "%" length "s\n" } { printf(f, $0) }'

If lines are not the same length, the same idea can be used with sprintf to create a pad of spaces:
awk -v x='Printing Line of the file:  ' 'NR==1 { pad = sprintf("%" length(x) "s", ""); print x $0; next } { print pad $0 }' /root/file

Answer: echo -en "Printing Line: `awk '{if (NR==1) {print " "$0} else {print "\t\t\t"$0}}' file`\n"

Printing Line:  line1
                        line2
                        line3

(That seems to work, even though it's nesting " inside "", it might need to be print \" \"$0 and similar to escape them properly, I don't know).

indent lines equally with echo


Check if passed parameter is a type of class

Question: I want to call the following function:
fun <T> isCurrentActivity( t: Class<T>): Boolean {
    return (currentActivity != null) &&  (currentActivity is t)
}

if (isCurrentActivity(MainActivity::class.java)) {

}

But t is an unresolved reference. How can I fix that? I can't use an inline reified function because the function needs to be publicly available.
Comment: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isInstance-java.lang.Object-
Answer: The problem is that JVM erase generic type, so type of parameter T is not accessible at runtime.
That's why in Java a popular pattern is passing instance of Class<T> as a param. It's not required in Kotlin, because in Kotlin we can define reified type and that type is accessible at runtime.
Example:
inline fun <reified T> isCurrentActivity(): Boolean {
    return (currentActivity != null) &&  (currentActivity is T)
}

fun example() {
    if (isCurrentActivity<MainActivity>()) {
        // it is!
    }
}

Requirements for marking T as reified is marking a function as inline. See more at docs: https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters
An example above is a "kotlin way to do that". If you would like to stay with "java like code" the mistake you do is that you try to check if a currentActivity is an instance of variable - what is not possible. Correct way would be:
fun <T> isCurrentActivity(t: Class<T>): Boolean {
    return (currentActivity != null) && currentActivity.javaClass == t
}

Please see @gidds comment about the check above.
But, I still recommend using reified type parameter, as it's a really nice way to check the type.
Comment: The equivalent of an `is` check would be `t.isInstance(currentActivity)`.  Checking `javaClass` is not a direct equivalent, because it fails if the `currentActivity` is a _subtype_ of `T`.


Manter Bean vivo mesmo depois de um redirect - JSF

Question: Alguém sabe alguma maneira de deixar um Bean vivo mesmo depois de dar um redirect?
A situação é assim: estou desenvolvendo um projeto em que, na teoria, o usuario fizesse login e o usuário e senha que ele digitou fiquem salvas em algum lugar (provavelmente junto com o bean) até que ele clique em LogOut.
Eu procurei uma solução na internet e encontrei o Flash do JSF porém no flash ele não guarda os dados pra sempre, ele perde os dados depois de 2 ou mais redirects, testei também o @ConversationScoped do CDI porém o bean morre quando eu dou redirect então eu não sei como manter esse bean vivo, alguém pode me ajudar?
Answer: Você pode colocar na sessão atributos e/ou objetos que serão mantidos até que ela seja destruída. Meu código abaixo se refere á um método de uma classe que obtêm o e-mail do cliente setado por outro método, tudo dentro da mesma sessão que pode ser pego em qualquer Bean.
<code>@SessionScoped
@Named
public class SessaoObjeto implements Serializable {
    private static final long serialVersionUID = 1L;

    public String obterClienteEmail() {
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = (HttpSession) request.getSession();
        String email = (String) session.getAttribute("CLIENTEID");
        return email;
    }

public void inserirClienteEmail(Cliente cliente, boolean clienteLogado) {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
    session.setAttribute("LOGADO", clienteLogado);
    session.setAttribute("CLIENTEID", cliente.getEmail());
}
</code>
Utilizo desta forma para sempre que eu precisar dos dados é só utilizar estes métodos =D Espero ter ajudado


Erro ao montar um Json via código

Question: Estou tentando montar um Json na seguinte estrutura:
"contatos":[{"contato":{"sequencia":"2046","codigo":"2046","nome":"teste balizador","tipo_pessoa":"PJ","cpf_cnpj":"32337775000143","ie":"","im":"","rg":"","tipo_negocio":"","endereco":"Rua Três Pontas","numero":"440","complemento":"","bairro":"Aparecida","cidade":"","cep":"30710-560","uf":"","pais":"","contatos":"Tiny","fone":"(31) 2526-0565","fax":"","celular":"","email":"firstname.lastname@example.com","id_vendedor":"4","situacao":"A","obs":""}}]

porém ao montar o Json o meu arquivo fica sem o contatos:
{"contato":{"sequencia":"2046","codigo":"2046","nome":"teste balizador","tipo_pessoa":"PJ","cpf_cnpj":"32337775000143","ie":"","im":"","rg":"","tipo_negocio":"","endereco":"Rua Três Pontas","numero":"440","complemento":"","bairro":"Aparecida","cidade":"","cep":"30710-560","uf":"","pais":"","contatos":"Tiny","fone":"(31) 2526-0565","fax":"","celular":"","email":"firstname.lastname@example.com","id_vendedor":"4","situacao":"A","obs":""}}

acredito que eu esteja esquecendo de algo  que ainda não percebi.
segue o trecho do meu código:
public class contato
        {

            public string sequencia { get; set; }
            public string codigo { get; set; }
             ...
            public string obs { get; set; }

        }

        public class Contatos
        {
            public contato contato { get; set; }
        }

 var contato = new contato
            {
                sequencia = cliente.CodCliente.ToString(),
                codigo = cliente.CodCliente.ToString(),
                ...
                obs = cliente.Observacoes
            };

            var contatosList = new Contatos() { contato = contato };
            var contatos = new JavaScriptSerializer().Serialize(contatosList);

Comment: Seu código está faltando padronização de nomenclatura de classes. Normalmente com Maiúscula inicial. você está criando uma variável e instanciando ela mesmo? var contato = new contato
Comment: Qual sentido de criar uma classe Contatos, a partir de contato?
Comment: foi a forma que consegui para chegar ao padrão do Json, estou analisando o codigo e refazendo de forma mais clara e correta.
Comment: O Seu Json tem que ser na primeira estrutura? Alguma regra do front? No caso ele é um Contatos que possui uma lista do objeto de Contato. Certo?
Comment: exatamente, porque pode acontecer que dentro de contatos tenha mais de um contato exemplo:
Comment: "contatos":[{"contato":{"sequencia":"2046","codigo":"2046","nome":"teste balizador","tipo_pessoa":"PJ","cpf_cnpj":"32337775000143","ie":"","im":"","rg":"","tipo_negocio":""},... "contato":{"sequencia": .....}
Comment: Não precisa fazer a roda duas vezes.
A sua lista vc declara assim
List Contatos = new List();
Comment: Preenche contato = new Contato {} e depois Contatos.Add(contato);
Answer: Tenta algo assim:
Declara a classe Contato. (mantenha padrão das regras de nomenclaturas)
public class Contato
{

    public string sequencia { get; set; }
    public string codigo { get; set; }
     ...
    public string obs { get; set; }

}

List<Contato> Contatos = new List<Contato>(); // Na sua função vc declara a lista da classe de Contato. No caso, Contatos.

Contato contatoAux = new Contato { // Preenche a Contato.
     sequencia = cliente.CodCliente.ToString(),
     codigo = cliente.CodCliente.ToString(),
     ...
     obs = cliente.Observacoes
};

Contatos.Add(contatoAux); // adiciona na lista.

// obviamente passou de uma inserção você irá utilizar um foreach.
contatoAux = new Contato {
     sequencia = cliente2.CodCliente.ToString(),
     codigo = cliente2.CodCliente.ToString(),
     ...
     obs = cliente2.Observacoes
};

Contatos.Add(contatoAux);

Comment: Muito obrigado Rebecca, entendi perfeitamente, porém depois de serializar não ficou no padrão e o post não foi realizado, como ficou depois: [{"sequencia":"2052","codigo":"2052"......"obs":""}] e o padrão é esse: "contatos"[{ "contato": {"sequencia":"2052","codigo":"2052","...."obs":""}}]
Comment: Como vc fez a serialização?
Comment: bom dia!! desa forma:  var contatos = new JavaScriptSerializer().Serialize(Contatos);
Comment: Me passa seu código e como executa, pode ser por aqui https://dotnetfiddle.net/  Cria ele e salva e me envia o link
Comment: Acho que isso aqui vai te ajudar. http://www.macoratti.net/16/07/c_jsonob1.htm
Comment: desculpa a demora. tive outras demandas urgentes aqui. vou criar.
Comment: li o artigo, utilizei o mesmo método e ainda continuo tropeçando na montagem do Json: segue o trecho que realiza o post:
Comment: List Contatos = new List();

            Contato contato = new Contato
            {
                sequencia = cliente.CodCliente.ToString(),

            };

            Contatos.Add(contato);
Comment: var contatos = JsonConvert.SerializeObject(Contatos.ToList(), Formatting.Indented);
            var stringContent = new StringContent(contatos, Encoding.UTF8, "application/json");
            var result = await new HttpClient().PostAsync($"https://api.tiny.com.br/api2/contato.incluir.php/authorize?token={token}&contato={contatos}&formato=json", stringContent);

            string retorno = await result.Content.ReadAsStringAsync();
Comment: @Gustavo.NET Coloca o código em algum executável como  dotnetfiddle.net  para poder simular, só assim, não consigo ajudar. srsrsr Ou me chama nas redes sociais que vc me passa o código rebecanonato89
Comment: chamei no instagram.
Comment: bom dia segue o link: https://dotnetfiddle.net/iZX8Ou

Erro ao montar um Json via código


How to set a default value in an AngularJS Directive Scope?

Question: In AngularJS, I have the following scenario where a directive can accept an optional boolean parameter which should default to true by default, whenever it is not specified.
Example:
<my-directive data-allow-something="false">
    ... this works as expected as no default value should be set in this case ...
</my-directive>

<my-directive>
    ... but in this case i'd like allowSomething to equal true  ...
</my-directive>

I've tried the following approach, but for some reason the true value doesn't stick on allowSomething. making it a '=?' optional two way binding doesn't work neither as my passed value should be a concrete true/false and not a field reference.
angular.module('myApp').directive('myDirective') {
    ...
    controller: function($scope){
        if (!$scope.allowSomething)
            $scope.allowSomething = true;
    },
    ....
    scope: function(){
        allowSomething: '@'
    }
    ...
}

I'm sure there should be a simple way to achieve this, so what am i missing?
The solutions given at the following ticket: AngularJS directive with default options
are not sufficient for my needs since the $compile function will prevent the link function from working. plus, the passed-in boolean value is not a reference type and i cannot give it a two-way binding.
Comment: It could be because controller is instantiated before binding the isolated scope to the directive element. So the value you set would have got overwritten by the new scope created for the directive from the bindings. Try setting defaults in a $timeout in the controller or try doing it in the link function or call the directive controller function to set the value from link function. Also on another note: you have allowSomething as text binding and you are setting boolean as default to it, what you set in the attribute will arrive as text "false"?
Comment: tried to put this in the link function with no luck. I'm also trying to avoid the $timeout approach. i think there should be a cleaner way to do this.
Comment: possible duplicate of [Angular directive with default options](http://stackoverflow.com/questions/18784520/angular-directive-with-default-options)
Answer: I think a better way to check that value is look for an undefined value like this:
controller: function($scope){
    if (angular.isUndefined($scope.allowSomething))
        $scope.allowSomething = true;
}

I had the same issue once and this worked for me.  I think the best method is to use angular's methods for handling things.
Comment: also if you do `if (!$scope.allowSomething) $scope.allowSomething = true;` it will set it true when you explicitly set it to false.
Comment: Instead of `$scope`, I use `$attrs` like `if (!$attrs.hasOwnProperty('allowSomething'))`.
Answer: This is how I have been doing it:
html:
<my-directive allow-something="false"></my-directive>
<my-directive></my-directive>

directive:
angular
.module('app')
.directive('myDirective', function() {

var defaults = {
  allowSomething: true
};

return {
  restrict: 'E',
  templateUrl: '',
  scope: {},
  compile: function() {
    return {
      pre: function(scope, el, attrs) {
        scope.allowSomething = attrs.allowSomething || defaults.allowSomething;
      },

      post: function(scope, el) {
        // this is link
        // scope.allowSomething = default or whatever you enter as the attribute "false"
      }
    };
  }
};
}

The pre is fired before anything happens then the post is like the link function. This has allowed me to do dynamic things based on the attributes I set.
Comment: I think this is cleaner than accepted answer, also I've seen some known plugins using this pattern with a `defaults` object containing default configurations.
Answer: Given your template is

  <my-directive></my-directive>

Then you can  either use link (preferred if no interaction with other directives is needed) or controller.
angular.module('myApp', [])
  .directive('myDirective', function() {
    return {
      scope: {},
      link: function(scope, element, attrs) {
        scope.allowSomething = ('allowSomething' in attrs) ? attrs.allowSomething : true;
      },
      template: '
allow:{{ allowSomething }}
'
    };
  });

// or
angular.module('myApp', [])
  .directive('myDirective', function() {
    return {
      scope: {
        allowSomething: '@'
      },
      controller: function($scope, $timeout) {
        $timeout(function() {
          if (angular.isUndefined($scope.allowSomething)) {
            $scope.allowSomething = true;
          }
        });
      },
      template: '
allow:{{ allowSomething }}
'
    };
  });

Answer: I think you can do something like this:
 scope : true,
  link : function(scope, element, attrs){
    scope.allowSomething = $parse(attrs.allowSomething)(scope) || true;
    console.log(scope)
  }

Comment: this will not work, as I'd like to keep the scope of the directive isolated, as it should be an independent reusable directive.


Asp.net WebApi add one item in nested child list when list is set to null in json

Question: I have  the following json Object which i am sending to Web Api controller Using ajax.
var dataObject = {
                    LanguageId: 1,
                    SubTenantId: 1,
                    Object:{"TestApplication":{"Aplication":null}}
                }

Controller function RequestObject generic class.
 public IHttpActionResult ComplexObject(RequestObject<TestApplicationMain> pubRequestObject)

I am using following Class hierarchy.
public class TestApplicationMain
{
    public TestApplicationMain()
    {
        TestApplication = new TestApplication();
    }
 public TestApplication TestApplication{get; set;}

}

public class TestApplication
{
    public TestApplication()
    {
        Aplication = new List<ApplicationSearchParam>();
    }
    public List<ApplicationSearchParam> Aplication { get; set; }

}

public class ApplicationSearchParam
{
    public ApplicationSearch ApplicationSearch { get; set; }
    public string OrderBy { get; set; }
}

When i send {"TestApplication":{"Aplication":null}} json to the controller. I receive One item Aplication .
Api controller works as expected when i send    {"TestApplication":{"Aplication":undefined}} OR  {"TestApplication":{"Aplication":[]}}
My Question is Why Asp.net WebApi Controller add one item in nested child list when its set to null ?.
Comment: Include `RequestObject` in the [mcve]
Comment: What is the item inside `Aplication` ? When I test your code, what I've seen for `Aplication` is `List` with 0 count. And this is normal beacuse, you are instantiating in constructor.
Comment: ApplicationSerachParam is a class having a number of. with Appliacation:null i receive one List with 1 count
Comment: i think you missing something in your code can you post the rest of the controller and models?
Comment: I would suggest you work with the Framework as you have evaluated.  In my experience, always pass a value (non-NULL) to Web API, so that it will properly map to properties.  Also, best to accept a JSON object into your Web API and try not to Auto-Map the JSON to .Net Object.  You are adding many layers of obscurity that will be hard to track-down.
Answer: First Problem Spotted:
var dataObject = {
                    LanguageId: 1,
                    SubTenantId: 1,
                    Object:{"TestApplication":{"Aplication":null}}
                }

Your JSON is at a level higher than TestApplicationMain
You defined LanguageId and SubTenantId but your receiving class TestApplicationMain does not handle either of the values.
You have not defined Object in TestApplicationMain

The reason your first test scenario {"TestApplication":{"Aplication":null}} works is because TestApplication is a property of TestApplicationmain
When you are automapping JSon Key-Value pairs, the name of the Key needs to match the name of the Property you wish its value to be assigned.
You test JSON should be:
var dataObject = {"TestApplication":{"Aplication":""}}

as this structure would map to:
TestApplicationMain -> TestApplication -> Aplication = ""

My Suggestions:

https://stackoverflow.com/a/31022729/659246
https://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/
Comment: I new this work with [] undefined and "" but  i want to make work with null
Comment: then wrap NULL in text `"null"` or handle the NULL value in Web API...be prepared for unhandle situations when relying on automapping.  I accept JSON as a string and parse using JsonSerializer object and manually map the fields I am expecting to the class/properties.


Receiving Image file in java

Question: I am  using basic java Server Client module to send a picture.
I am using this link for guidance
Below is my source code for the client.I have issues while receiving the file.
<code>package sclient;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;

public class Sclient {
  public static void main(String[] argv) throws Exception {
    Socket sock = new Socket("192.168.0.10", 123);
    byte[] mybytearray = new byte[1024*1024];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir")+"/imageTest.jpg");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
    bos.write(mybytearray, 0, bytesRead);
    bos.close();
    sock.close();
  }
}
</code>
Comment: You doint just a single read of bytes, you need to interate over the read Method until it returns -1 as a result. Also close and flush your streams in a finally block!
Comment: How big is your file?
Comment: will try that thanks... but y they are down-voting my question? do u know?
Comment: can u give my an example of that? @Kitesurfer
Comment: So you are trying to read 1.2 MB into a 1 MB buffer ... think about it ...
Comment: Downvotes mostly are due to lack of own research and effort shown.
Answer: Thats one util method of an android project, but its does the same. Reads and write is somewhere
<code>/**
 * @param inputStream
 * @param inClose
 * @return
 * @throws IOException
 */
public static byte[] readContent(@NonNull final InputStream inputStream, final boolean inClose)
        throws IOException {
    Preconditions.checkNotNull(inClose, "InputStream");
    //
    final ByteArrayOutputStream theStream = new ByteArrayOutputStream(BUFFER_2K);
    final byte[] theBuffer = new byte[BUFFER_2K];

    try {
        int theLength = inputStream.read(theBuffer);

        while (theLength >= 0) {
            theStream.write(theBuffer, 0, theLength);
            theLength = inputStream.read(theBuffer);
        }
        return theStream.toByteArray();
    } finally {
        if (inClose) {
            close(theStream);
        }
    }
}
</code>

Receiving Image file in java


solve for the values of A, B, and C.

Question: I need help with this problem,  please.
If we have a number $ABC$ written in "decimal form" that is, its value is:
$$100A+10B+C.$$
If each letter represents the same digit (and different letters mean different digits), solve for the values of $A$, $B$, and $C$.
$$ABC+AB+A=300.$$
Comment: $271+27+2=300$ is one solution
Comment: \begin{align}
100a + 10b + c + 10a + b + a &= 300\\
111a+11b +c &= 300\\
a+b+c &\equiv 0 \mod 10\\
2b + c &\equiv 0 \mod 3\\
\end{align}

Also, note that $a \lt 3$
Answer: As you've stated the number $ABC$, written in decimal form can be expressed as:
$A × 100 + B × 10 + C × 1$
Therefore,
$ABC + AB + A = (A × 100 + B × 10 + C × 1) + (A × 10 + B × 1) + (A × 1)$
$ = 111A + 11B + C = 300$
Now, check for yourself that $A$ must be $2$  (What happens if $A > 2$? If $A < 2$?)
So we see that $11B + C = 78$
Similarly to above, we see that $B=7$, finally giving us that $C=1$
Thus, your solution, as Dr. Graubner stated above, is $271$
Answer: First we can see that the only choice for A is 2 (if it's 3, the sum is too large, if it's 1 then AB is less than 20 and the sum is too small).
So we have
$100A+10B+C+10A+B+A=222+11B+C=300$. After simplifying, we get $11B+C=78$ and it's not difficult to see that the only solutions are $B=7$, $C=1$
Answer: Just do it.
$ABC + AB + A = (100A + 10B + C) + (10A + B) + A = 111A + 11B + C = 300$.
$C$ is at most $9$ and $11B$ is at most $99$ so $111A$ is at least $300 - 108=196$ so $196 \le 111A \le 300$ and $\frac {196}{111} \le A \le \frac {300}{111}$.
So $A = 2$ and $11B+ C= 300 -222 = 78$.
$C$ is at most $9$ so $11B$ is at least $69$.  So $69\le 11B \le 78$ so $\frac {69}{11} \le B \le \frac {78}{11}$ so $B = 7$.
So $C = 78 - 77= 1$
So $271 + 27 + 2 = 300$.
Answer: Obviously $A=1\text{ or } 2$ and since $198+19+1\lt300$ we have $A=2$
$$\begin{align}\frac{ABC+\\\space\space AB\\\space {} \space \space  A}{300}\end{align}$$
It follows $A+B+C\equiv 0\pmod{10}\Rightarrow A+B+C=10 \text{ or }20\Rightarrow B+C=8$.
There are only four possibilities $(B,C)=(7,1),(1,7),(5,3),(3,5)$ from which only $(7,1)$ fits. The only solution is $$271$$

solve for the values of A, B, and C.


Posicionar botão em cima do do anúncio

Question: Olá, gostaria de saber como coloco um botão de fechar anúncio no canto da tela, em cima do anúncio.
Até tentei aqui mais pega espaço da webview acima e não fica transparente a parte, por exemplo: O botão fica no canto mais toma espaço da webview e o fundo não fica transparente.
Veja o exemplo:

Veja que no X tem na esquerda todo azul, não queria isso, apenas o X ali onde está mesmo, mas sem essa parte azul.
Código:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/adsContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xxxxxxxxxx.android.MainActivity"
android:padding="0dp"
android:orientation="vertical"
android:weightSum="1"
android:background="#2c3e50">
<FrameLayout
    android:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="invisible"
        android:indeterminate="false" />
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webview"
        android:visibility="invisible"/>
</FrameLayout>
<LinearLayout
    android:id="@+id/frameAds"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
<Button
        android:id="@+id/closeAd"
        android:background="@android:drawable/ic_menu_close_clear_cancel"
        android:layout_gravity="end"
        android:layout_width="25dp"
        android:layout_height="25dp"
        ads:backgroundTint="@android:drawable/screen_background_dark_transparent"
        android:visibility="visible" />
    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/ID_ANUNCIO_BANNER"/>
    </LinearLayout>
     </LinearLayout>

Alguém pode me ajudar?
Comment: Não está claro o que pretende. Se possível coloque uma imagem de como está e outra de como quer que apareça.
Comment: Coloquei uma imagem de exemplo. Espero que você entenda
Answer: Use relative layout pra agrupar o bottom de fechar e o anúncio.
Quando o usuário clicar em fechar tu muda o relative layout pra visibilidade GONE.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adsContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.xxxxxxxxxx.android.MainActivity"
    android:padding="0dp"
    android:orientation="vertical"
    android:weightSum="1"
    android:background="#2c3e50">
    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:visibility="invisible"
            android:indeterminate="false" />
        <WebView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/webview"
            android:visibility="invisible"/>
    </FrameLayout>
    <LinearLayout
        android:id="@+id/frameAds"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <Button
            android:id="@+id/closeAd"
            android:background="@android:drawable/ic_menu_close_clear_cancel"
            android:layout_gravity="end"
            android:layout_width="25dp"
            android:layout_height="25dp"
            ads:backgroundTint="@android:drawable/screen_background_dark_transparent"
            android:visibility="visible" />
        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            ads:adSize="SMART_BANNER"
            ads:adUnitId="@string/ID_ANUNCIO_BANNER"/>
    </LinearLayout>
</LinearLayout>

Comment: Ajustei a resposta com base na imagem que voce postou.
Comment: Obrigado pela a resposta! Mas não consigo entender assim, ainda sou novato na área de Android!
Comment: Esqueci de vir aqui a tarde! Amanhã vou testar e posto o resultado! Obrigado!
Comment: Corrigir um erro e editei sua resposta! Muito obrigado!

Posicionar botão em cima do do anúncio


Show that $\sum_{n=0}^{\infty} a_{f(n)}$ is also an absolutely convergent series.

Question: Let $\sum_{n=0}^{\infty} a_n$ be an absolutely convergent series of real numbers. Let $f:N \to N$ be an increasing function (i.e., $f(n+1) > f(n)$ for all $n\in N$). Show that $\sum_{n=0}^{\infty} a_{f(n)}$ is also an absolutely convergent series.
Hint: Try to compare each partial sum of $\sum_{n=0}^{\infty} a_{f(n)}$  with a (slightly different) partial sum of $\sum_{n=0}^{\infty} a_n.$
My attempt:
If $\sum_{n=0}^{\infty} a_n$ is absolutely convergent, then by definition, $\sum_{n=0}^{\infty} a_n$ and $\sum_{n=0}^{\infty} |a_n|$ converges. By the Proposition of "Rearrangement of series," Let: $$L= \sum_{n=0}^{\infty} |a_n|.$$ Then,
$\sum_{n=0}^{\infty} a_{f(n)}$ converges to $L$. Let:
$$L'=\sum_{n=0}^{\infty} a_n.$$ Then, we want to show that $\sum_{n=0}^{\infty} a_{f(n)}$ also converges to $L'$. In other words, given any $\epsilon>0$, we have to find an $M$ such that  $\sum_{n=0}^{M'} a_{f(n)}$ is $\epsilon$-close to $L'$ for every $M'>M$.
Comment: How do you know that $\sum a_{f(n)}$ converges to $L$?
Comment: @LionelRicci it's a proposition in the book
Comment: $\sum_{n=0}^{\infty} a_{f(n)}$ will, in general, NOT converge to $L$. For example, let $f(n) = 2n$.
Comment: Also, you only need $f(n+1) \ge f(n)+1$.
Answer: Observe that $$\sum_{k=0}^n |a_{f(k)}| \le \sum_{k=0}^{f(n)} |a_k| \le L$$ so that the absolute series has bounded partial sums and is thus absolutely convergent.
Answer: I think the proof is easier. Let me sketch my thoughts. If $f$ is strictly increasing, then the image of $f$ is some subset of $\mathbb N$ which may be all of $\mathbb N$ or could be smaller. (To see this, observe that $f(1) = n$ need not imply $f(2) = n+1$ - it could be larger, so there could be a gap which we never come back to since this function is strictly increasing). If $f$ is the identity, then there's nothing to prove. Otherwise, $f$ amounts to a deletion of some collection of terms, which, upon taking absolute values, is strictly smaller than the absolute value of the series you started with.
Answer: $f$ is injective. Any injective function works. In fact, consider
$$\sum_{n=1}^N a_{f(n)}$$
and let $M$ be the biggest value taken on by $f(n)$ i.e. $M = \max_{ n \le N} f(n)$
Then $$\sum_{n=1}^N a_{f(n)} \le \sum_{n=1}^M |a_{n}| \le L$$
where $L = \sum_{n=1}^\infty |a_n|$. Then taking the limit as $N \to \infty$ you get the result. Notice that we only used (in the first inequality) the property that $f$ is injective.


Test method is skipped even though the dependsOnGroups method is passed

Question: I have the following structure in testng.xml
<code><test name="test">
<groups>
<run>
<include name ="E"/>
<include name ="Sanity"/>
</run>
<groups/>
<classes>
<class name="com.test.testcases.Test2"/>
<class name="com.test.testcases.Test1"/>
</classes>
</test>
</code>
Test2 belongs to group Sanity and Test1 belongs to group E. The test method in group "Sanity" depends on the test method in group "E". I have used dependsOnGroups as both the methods are in different classes. Now, on running the suite, I see that the test method in Test2 is skipped even though Test1 has passed. Could anyone help in this regard?
Comment: Looks ok... you may try to make a SSCCE and post the code.
Comment: I believe there is no issue with the code inside the class files. Probably something that I am missing in testng.xml which is causing this.
Comment: Same question than http://stackoverflow.com/questions/19445344/tests-skipped-inspite-the-dependant-method-passed-testng?rq=1
Comment: Could you set verbose to 10 and share the output? ``
Comment: @JulienHerr - That helped bigtime. There was an error in the dataprovider name that was given for the skipped method which was not shown earlier. Thanks a ton!
Answer: There was an error in the dataprovider name that was given for the skipped method which was not shown earlier.


Can I prove Pythagoras Theorem by concatenating four right triangles?

Question: I was considering ways to visually prove Pythagoras' Theorem.
I was reasoning if I could concatenate the same right triangle four times, as if it was reflected from both axis.

Why can't I just calculate the area of this diamond to know c?
What am I doing wrong? Why does it make no sense?
Please, excuse me if I'm doing an obvious mistake or wrong assumption.
Thanks.
Comment: If you imagine $a$ to be really small, you can see that the area is almost zero.  If $a$ is about equal to $b$, then the area is relatively large, but $c$ is the same in both cases.  The point here is that the area doesn't determine $c$.
Comment: You can just as easily rearrange those four triangles to construct a rectangle of area $4ab$. That tells you nothing about $c$.
Comment: Here there is something to visually understand it better https://math.stackexchange.com/q/1562759/436114. I will learn more about rhombus properties.
Comment: @B.Goddard, Thanks for your answer. Is there a particular resource you would recommend to continue exploring these geometry basics that also kind of brings together Pythagoras theorem?
Answer: Problem
The shape you have drawn is a rhombus. The area of a rhombus is defined to be $\frac{pq}2$ where $p$ and $q$ are the lengths of both the diagonals.
Therefore, the area of the shape you have drawn is calculated by considering the fact that $p=2b$ and $q=2a$. And so the area would be $\frac{(2a)(2b)}2=2ab$.
We can of course verify this by calculating the area of one of the right angle triangles and then multiplying by $4$. The area of one triangle is $\frac{ab}2$ and so multiplied by $4$ gives us the same answer for the total area as $2ab$.
However, this doesn't help us to find $c$, since the formula for the area is independent of $c$
Note: c is not independent of the area. We just need Pythagoras' Theorem to show that this is the case. Since we are trying to proof Pythagoras' Theorem, we must use a formula in terms of a and b which make the area independent of c.
So you haven't written anything explicitly wrong. The only problem is that, this doesn't prove Pythagoras' theorem.
Expanding upon something correctly stated in the comments, we also have the problem of the fact that we are stating the formula for the area of a rhombus without any explicit proof. And so this is also a consideration we need to make before even making an attempt to use the formula for a proof.
Comment: Regarding resources,  there is a huge amount of research on geometry and so it's difficult to recommend one in particular. If you are looking for a very rigorous, undergraduate level geometry book then I can make some recommendations. If you are looking for something a bit more basic, then there are some great playlists on youtube depending on your focus. The resources very much depend on whether or not you're more interested in proofs, or learning about properties in order to solve problems @Aleix
Comment: You can equate $2ab$ with some other formula (that involves $c$) for the area of one of the triangles, and derive the Pythagorean theorem.
Comment: Thanks for your answer. I don't quite understand why c is independent of the area. I mean, it seems strange at first glance, also considering that a rhombus has similar characterstics to a square.
Comment: Yes, I acknowledge this at the end of my response. The problem is that we must first derive this formulae before going on to produce a proof. We cannot just state the formulae to prove another formula when they are require Pythagoras' Theorem to be true in the first place @Alex
Comment: @Aleix it is not very strange considering that the square is a (very) important special case of the rhobus, so needing $c$ in the case of a square kinda makes sense.
Comment: Your intuition is correct. The area is determined by a and b (which are linked by Pythagoras' Theorem) and so c isn't independent of the area in practice. However, because we cannot assume Pythagoras' Theorem (since we are looking for a proof), we cannot state that the area is dependent on c without having a formula to show that this is the case @Aleix
Comment: Is there a particular resource you recommend to continue exploring geometry? What  things are assumed, how to derive and prove its properties (sort of for inexperienced people)?
Comment: In terms of proof writing, the best approach to take is to look up the proofs of certain properties. For example, when you came up with this idea, a good idea would be to look up "proof of the area of a rhombus", which would have shown you that we need Pythagoras' Theorem in the first place before we can use this formula @Aleix
Comment: I would be more interested in proofs, at a basic level @FD_bfa.


Negate field value to set control visiblity

Question: I have a control with the visible property set to the value of a boolean field. However, I want the visiblity to be the opposite of the boolean field. How do I do this?
This code shows the visible property set to the value of the field. I want to negate that value.
<span runat="server" id="toMonthYear" visible='<%#Eval("isAttending")%>'>
     <%#Eval("toMonthName")%>

Answer: Simply cast it to bool and use the negation operator (NOT in VB.NET).
Visible='<%# !(bool)Eval("isAttending") %>'

Answer: Try this
<span runat="server" id="toMonthYear" visible='<%#(!Boolean.Parse(Eval("isAttending"))%>'>


Proof of Folkman's lemma.

Question: In combinatorics,in particular,in Ramsey theory,there is a theorem called Folkman's theorem which is as follows:

Given any positive integers $r,k$ there exists $f(r,k)\in \mathbb Z^+$ such that if $\{1,2,...,f(r,k)\}$ is $r$-colored then there exist $1\leq a_1<a_2<...<a_k\leq f(r,k)$ such that $P(a_1,a_2,...,a_k)=\{\sum\limits_{i} c_ia_i: c_i=0,1$ for all $1\leq i\leq k$ and not all $0\}$ is monochromatic.

I am looking for a proof of this theorem.Can someone please provide me a proof or give me a reference where I can find the proof?
Answer: There are several proofs of this theorem in Graham, Rothschild, and Spencer's Ramsey Theory which actually appears to be the source that first names this theorem as Folkman's.
Because I feel incapable of leaving it at that, here is my favorite of their proofs.
We begin by proving a lemma: there is a $g(r,k) \in \mathbb Z^+$ such that, in the same setup as Folkman's theorem but coloring up to $g(r,k)$, we can find $a_1, \dots, a_k$ where $P(a_1, \dots, a_k)$ satisfies a weaker condition. Rather than asking for it to be monochromatic, we ask for it to be "striped": the color of a sum $\sum_i c_i a_i$ depends only on $\max\{i : c_i = 1\}$, the largest index of a term $a_i$ included in the sum. (Variants of "striped" colorings appear in many proofs in Ramsey theory.)
We prove the lemma by induction using van der Waerden's theorem. Choose $n$ so that an $r$-coloring of $n$ consecutive integers contains an arithmetic progression of length $g(r,k)$, and let $g(r,k+1) = 2n$. Now, after $r$-coloring $\{1,\dots,2n\}$ arbitrarily:

Find such an arithmetic progression $a+d, a+2d, \dots, a+g(r,k)d$ in $\{n+1, \dots, 2n\}$.
Color $X = \{1,2,\dots, g(r,k)\}$ by giving $x \in X$ the color of $dx \in \{1,\dots,2n\}$, and find a striped $P(a_1, \dots, a_k)$ in $X$ with respect to this coloring.
We claim that $P(da_1, da_2, \dots, da_k, a)$ is striped in the original $r$-coloring of $\{1,\dots,2n\}$. Sums including $a$ are all the same color because they land in the arithmetic progression, and sums not including $a$ are striped by induction.

Also, by construction, $da_1, \dots, da_k$ are all at most $n$, while $a$ is at least $n+1$, ensuring that all $k+1$ values are distinct.
Once we have $g(r,k)$, we can take $f(r,k) = g(r,r(k-1)+1)$ and finish by pigeonhole: we find $\{b_1, \dots, b_k\} \subseteq \{a_1, \dots, a_{r(k-1)+1}\}$ that are the same color. Then their "stripes" in the striped coloring of $P(a_1, \dots, a_{r(k-1)+1})$ are also all the same color, so $P(b_1, \dots, b_k)$ is actually monochromatic.
(Another proof that's shorter but unsatisfying is that Rado's theorem has this theorem as a corollary. This will not make sure that $a_1, \dots, a_k$ are all distinct, but that can be fixed with a bit more work.)

Proof of Folkman's lemma.


WCF and code generation from WSDL

Question: I am writing a "universal" client for Web services, and have hit an unexpected problem. I generate the code for the client dynamically by retrieving the Web services WSDL, and using the following (simplified a little) code to generate the client code:
<code>ServiceDescription serviceDescription = ServiceDescription.Read(xmlTextReader(WSDL));
ServiceDescriptionImporter descriptionImporter = new ServiceDescriptionImporter();
descriptionImporter.ProtocolName = "Soap";
descriptionImporter.Style = ServiceDescriptionImportStyle.Client;
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, new CodeGeneratorOptions());
</code>
I am testing this using a simple WCF Web service that exposes two methods:
<code>[OperationContract]
int GetInteger();

[OperationContract]
string GetString();
</code>
If I examine the client-side generated code, then I can see that the GetString() returns a string, but the GetInteger() method returns void! I assume that this is something to do with value and reference types. Is there some way to force the code generator to make the GetInteger() method return an int?
Comment: In C# 'int' type is a primitive , whereas the 'Integer' type is an object, try using 'Integer'. (string is an alias for System.String. So technically there is no difference. Thats why your GetString() method returns string)
Comment: I was under the impression that you can't pass integers using SOAP and WCF architecture but I might be wrong
Comment: Hi - thanks for your comments. I don't think that there is an Integer type in C#, is there? However, more importantly, I'd like my client application to work against any Web service (the one I created is just a simple test one), and so I have to allow for the possibility that Web services have methods as I describe above.
Answer: Returning an int over WCF should not be a problem.
Check the code that produces the client side generated code.
The hack to get around the problem would be to return an object that had a single property that was an int.
Comment: The code that generates the client-side code is all standard C# classes (see above). I may be misusing one of the classes or is there maybe a flag I can set to get an int returned?
Comment: Check the WSDL file, is the return type void in the WSDL file?
Comment: Hi - no, as far as I can tell both return types are what you would expect:

    `

`
Answer: From various experiments, I believe that my problem is an inherent limitation of using the ServiceDescriptionImporter to generate the client code. I am going to try to "upgrade" to using the System.ServiceModel.Description.WsdlImporter and System.ServiceModel.Description.ServiceContractGenerator framework, in the hopes that improves things.

WCF and code generation from WSDL


Writing our own iterator for a java hashtable with nodes

Question: For our java class, we are expected to implement our own iterator in our SymbolTable class (essentially just a hashtable). I am done with the SymbolTable class, but not the iterator class. I am not sure how to build the constructor, as well as how to properly fill out the hasNext(); method.
For reference, here is the inner node class:
private class Node {
    // nodes used to build the linked lists used in a
    // separate chaining hash table
    private String key;
    private Object data;
    private Node next;

    private Node(String k, Object d, Node n) {
        key = k;
        data = d;
        next = n;
    }
}

private Node table[];
private int tableSize;
//Used in iterator

Now, here is what I have so far for the iterator:
public class STIterator implements Iterator<String> {
    // An iterator that iterates through the keys in the table
    // each call to next returns the next key in the table
    Node head;
    Node current;
    int pos = 0;

    public STIterator() {
        current = table[0];

    }

    public boolean hasNext() {
        return current != null;
    }

    public String next() {
        // have to move down to location i+1 usually
        // move to next element in table thats not null
        // PRE: hasNext()
        if (hasNext()) {
            String data = (String) current.data;
            current = current.next;
            return data;
        }
        return null;
    }

}

So essentially, this iterator scans through a hashtable which holds certain words (scanned in from a book). So, we want the iterator to loop through the table until it finds data (an object, d) that is not null. Meaning a specific "slot" in the hashtable that includes a word (which is given by key in the node class)/
Comment: What exactly is your question, that is, what is your iterator doing (or not doing)? What are you unsure about regarding the constructor?
Comment: Yes sorry, new to SO. I need the iterator to go through the String keys in my hashtable. I know I start the iterator at the beginning (hence starting at table[0], but I am unsure how to write the constructor to correctly build the iterator, as well as use the next and hasNext methods to manually iterate (meaning not using utils java has given us).
Comment: Let's say you have a hash table where tableSize is 2 and table[0] and table[1] each has a node where next is null. Does your iterator return each of those two nodes in turn?
Comment: It is supposed to call the next until it finds an element at that specific data. So, it should cycle until it finds a value(Which is our String key), so it should exit the iteration if none are found. I have it simply returning null.
Comment: You are iterating only through the list which is on the first bucket. You need also to iterate over buckets once you reached the end of the list from current bucket
Answer: I suppose at present your code looks like this:
public class SymbolTable {
...
   private class Node {
   ...
   }
   public class STIterator implements Iterator<String> {
   ...
   }
}

Let's add a main method in SymbolTable:
   public static void main(String... args) {
      SymbolTable map = new SymbolTable();
      map.put("foo", "foo data");
      map.put("bar", "bar data");

      Iterator<String> i = map.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }

Now you have some runnable code, and you can ask questions about it. Please try that and edit your question with your new code and any compilation errors, exceptions or undesired behaviour your program has.
Answer: This is a genuinely tricky problem, and I don't know any better way to really answer it than to give you the answer.  I'm assuming you don't need to support remove(); if you do, I'll leave that part as an exercise.
// FYI: this class doesn't have to be, and arguably shouldn't be, public
public class STIterator implements Iterator<String> {
    // An iterator that iterates through the keys in the table
    // each call to next returns the next key in the table
    Node current = null;
    int pos = 0;

    public STIterator() {}

    public boolean hasNext() {
      while (current == null && pos < table.length) {
        current = table[pos++];
      }
      return current != null;
    }

    public String next() {
      if (!hasNext()) throw new NoSuchElementException();
      String k = current.key;
      current = current.next;
      return k;
    }
}

This is based on the assumption that you're trying to iterate over the entire table.  If you're looking for a specific key, you possibly shouldn't be using an iterator at all, just a loop.


Evaluate the integral $\int_{0}^{\frac{\pi}{3}}\sin(x)\ln(\cos(x))\,dx$

Question: $$\int_0^{\frac{\pi}{3}}\sin(x)\ln(\cos(x))\,dx $$
$$
\begin{align}
u &= \ln(\cos(x)) & dv &= \sin(x)\,dx \\
du &= \frac{-\sin(x)}{\cos(x)}\,dx & v &= -\cos(x)
\end{align}
$$
$$
\begin{align}
\int_0^{\frac{\pi}{3}}\sin(x)\ln(\cos(x))\,dx &=
-\cos(x)\ln(\cos(x)) - \int  \frac{-\cos(x)-\sin(x)}{\cos(x)}\,dx \\\\
&= -\cos(x)\ln(\cos(x)) - \int \sin(x)\,dx \\\\
&= -\cos(x)\ln(\cos(x)) + \cos(x) \\\\
F(g) &= -\cos(\pi/3)\ln(\cos(\pi/3)) + \cos(\pi/3) + \cos(0)\ln(\cos(0)) - \cos(0) \\\\
&= -\frac{1}{2}\ln\left(\frac{1}{2}\right) - \frac{1}{2} \\\\
\end{align}
$$
However, my textbook says that the answer is actually
$$\frac{1}{2}\ln(2) - \frac{1}{2}$$
Where does the $\ln(2)$ come from in the answer?
Comment: It's perfect! Just notice now that $\ln \frac12 = \ln 1 - \ln 2 =-\ln 2$.
Comment: @Zacky oh that makes sense. And that is where the (-) sign went as well!
Comment: I'll also note that there is a simpler way: with a substitution $u = \cos x$ and $du = -\sin x$ this integral becomes $\int_{1/2}^1 \ln u\, du$. (Finding the antiderivative of $\ln$, if you don't already know it, also requires integration by parts, but it's very simple.)
Comment: Hint: $\ln(x^a) = a \ln(x)$
Comment: I will try to solve the problem this way and see what happens
Answer: Well, we have:
$$\mathcal{I}_\text{n}:=\int_0^\text{n}\sin\left(x\right)\cdot\ln\left(\cos\left(x\right)\right)\space\text{d}x\tag1$$
Substitute $\text{u}:=\cos\left(x\right)$ so we get:
$$\mathcal{I}_\text{n}=-\int_1^{\cos\left(\text{n}\right)}\ln\left(\text{u}\right)\space\text{d}\text{u}\tag2$$
Using IBP, we get:
$$\mathcal{I}_\text{n}=\left[-\text{u}\cdot\ln\left(\text{u}\right)\right]_1^{\cos\left(\text{n}\right)}+\int_1^{\cos\left(\text{n}\right)}1\space\text{d}x=\left[-\text{u}\cdot\ln\left(\text{u}\right)\right]_1^{\cos\left(\text{n}\right)}+\left[\text{u}\right]_1^{\cos\left(\text{n}\right)}=$$
$$-\cos\left(\text{n}\right)\cdot\ln\left(\cos\left(\text{n}\right)\right)+1\cdot\ln\left(1\right)+\cos\left(\text{n}\right)-1=\cos\left(\text{n}\right)\cdot\left(1-\ln\left(\cos\left(\text{n}\right)\right)\right)-1\tag3$$

So, when $\text{n}=\frac{\pi}{2}$ we get:
$$\mathcal{I}_{\frac{\pi}{3}}:=\int_0^\frac{\pi}{2}\sin\left(x\right)\cdot\ln\left(\cos\left(x\right)\right)\space\text{d}x=\cos\left(\frac{\pi}{3}\right)\cdot\left(1-\ln\left(\cos\left(\frac{\pi}{3}\right)\right)\right)-1=\frac{\ln\left(2\right)-1}{2}\tag4$$
Answer: $$-\ln(\frac{1}{2}) = \ln(2)$$
$$\ln(x^a) = a \ln(x)$$
Answer: Perhaps an easier method:
$$I=\int_0^{\pi/3}\sin(x)\ln(\cos x)dx=-\int_0^{\pi/3}-\sin(x)\ln(\cos x)dx$$
Sub:
$$u=\cos x\Rightarrow du=-\sin(x)dx$$
which gives
$$I=\int_{1/2}^1\ln u\ du$$
Since $$\int\ln x\,dx=x(\ln x-1)=x\ln\frac{x}e$$
We have $$I=\ln\frac1e-\frac12\ln\frac1{2e}$$
Then using $$\ln(x^a)=\ln(e^{a\ln x})=a\ln x$$
We have
$$I=-1+\frac12\ln2e=-1+\frac12\ln2+\frac12=\frac12\ln2-\frac12$$


jQuery-ui Autocomplete not finding control on Master page

Question: I'm struggling with the jQuery-UI Autocomplete on a master page.
I've loaded the jQuery.js and jQuery-ui.js in that order, in the head section of the master page.
What I need to do is very common, I'm sure, but perhaps the idea it's on a master page is getting in the way.
Here is  code that will fill the autocomplete input (id=autocomplete) with hard-coded values outside an ajax call.
I realize it's useless to call ajax for data and not use it, but I'll deal with that later...baby steps
<%-- Trying some autocomplete stuff --%>
Language:
<input id="autocomplete" />

Again, this WORKS (but the data is hardcoded).  I get the alerts in the following order: success from ajax, then the autodata, then the filled notice.
Additionally, it works if I use the fillMe variable set to "#autocomplete" or if I hard code it in the FillAutocomplete function.
Obviously, since it works, the input is able to have the autocomplete property.
Here's everywhere else where I tried that I simply get
Object doesn't support property or method 'autocomplete'

Putting the autocomplete code directly inside the success
Call the filling of the autocomplete INSIDE the success of the ajax call (uncomment //FillAutocomplete) (comment the other call)
Starting with $(function() {
$('#autocomplete).autcomplete({...
Using some form of <#='autocomplete.ClientID()'#>

I have a sneaking suspicion it's not finding the control, not really that the control doesn't have support it.
Any ideas?

UPDATE: More Information
I've added the screenshot below to show the error in its full glory.  And sorry for repeating myself but I'm wondering if it's due to master page somehow, or somehow the jquery-ui is NOT loading before the call to the autocomplete method (since it's "object doesn't support....")

The Cause and Solution:
It seems that the Ajax call was trying to complete before the remote file jQuery-UI was loaded.  As RAM suggested in the comments below, I downloaded all remote files and they're part of the project now.  Now the scripts load in the correct order and the autocomplete method is available on the input.  Thanks RAM.
Answer: Here is an example to how to use jquery autocomplete in asp.net
http://www.dotnetlearners.com/blogs/view/102/JQuery-ajax-autocomplete-extender-textbox-using-json-response-type.aspx
Comment: Download the jquery js files locally and place them in your project and refer them in your page locally.
Comment: Nope, still getting Object doesn't support property or method 'autocomplete'
Comment: It is "finding" the control, because when I change
'("autocomplete").autocomplete' to
'("bill").autocomplete' I get a compilation error.
Comment: Where you added your jquery-ui reference? add it right after jquery.js reference.
Comment: `

`
Comment: Sorry that's a mess, I don't have the 'comments' here down, but they're added one right after the other.
Comment: Can you check jquery-ui.js loaded or not in your chrome browser developer tools sources?
Comment: It does load it, but I can't tell when.  Could it be somehow AFTER the ajax call?  And can I force it  to load first?  I thought that might be what the `$(document).ready` was for, but I might have that wrong.
Comment: OK, I know this is getting ridiculous, but I put them in my project (main directory, not /scripts folder) and referenced them in the  section and now I really don't think jquery is loading, as I get "$" undefined.  And I tried moving it to the  as well.
Comment: And that's probably due to the child page not finding the master page main directory as easily since the master page is a virtual directory.
Comment: Place the css and js in root directory of project and give ref as
Comment: I put it in the root directory called CommonContent.  Then I put the references as
Comment: '

'
Comment: THAT DID IT.  Thanks for sticking with me, RAM!
Comment: So it was running the AJAX (asynch) **before** finishing the page loading even though I had the document.ready() function being used?
Answer: The Ajax call was trying to complete before the remote file jQuery-UI was loaded. As RAM suggested in the comments, I downloaded all remote files and they're part of the project. Now the scripts load in the correct order and the autocomplete method is available on the input.
Thanks RAM - that did it.


How to treat an isomorphism between vector spaces as an isomorphism between many sorted structures

Question: According to this PDF, p.29, a vector space is a strict many sorted structure, where strict means that the scalar set and the vector set are disjoint (the definition is here, p.23).
For any field $K$, however, $K$ is also a vector space over $K$ and the scalar set and the vector set are the same, and therefore not disjoint.
So we have to adopt a lax structure, where lax means not-strict(the definition is here, p.23), to formalize this vector space as many sorted structure.
But if we adopt a lax structure, (it seems to me) another problem arises.
Let $V$ be a one-dimensional vector space over $K$ satisfying $V \cap K = \emptyset$.
It is well known that $V$ is isomorphic to the vector space $K$ mentioned above.
But we cannot create the isomorphism between $V$ and $K$ as an isomorphism between many sorted structures(the definition is here, p.40), because if $\pi: K \cup V \to K \cup K = K$ is a isomorphism, $\pi\upharpoonright K: K \to K$ must be a bijection, but this is impossible since $\pi$ is a bijection between $K \cup V$ and $K$.
So I think we must modify or extend the definition of an isomorphism between many sorted structure to treat an isomorphism between vector spaces as an isomorphism between many sorted structures.
I would appreciate it if you could show me how to do this.
Comment: The notion of **lax** many sorted structure is new to me. Does it appear anywhere else?
Comment: In addition to the PDF, the definition of a many sorted structure in the book [Extensions of First-Order Logic](https://books.google.co.jp/books/about/Extensions_of_First_Order_Logic.html?id=GYSZ0AdppgMC&redir_esc=y) also allows the universes in a many sorted structure not to be disjoint.
Answer: My personal take is that the distinction between strict and lax structures is abstraction-breaking because we're checking equality across sorts. That being said, it seems like a good distinction to have for pragmatic purposes because it lets us know exactly how careful we have to be when building a model out of set-theoretic raw materials.
You can turn any lax many-sorted structure into a strict many-sorted structure in a straightforward, fairly brute-force way. For this reason, hypothesizing a strict model satisfying some theory is not really making a stronger claim than hypothesizing a lax one.
This is conceptually analogous to emulating a statically typed programming language in a dynamically typed programming language by tagging every value with its formerly-static type.
The definition of a many-sorted logic given on page 93 restricts us to finitely many sorts. We don't need the assumption of finitely many sorts, but it prevents us from needing to talk about ordinals explicitly.
We can define the following map $\varphi$ on each of the sorts.
If $s$ is in $M_n$, the $n$th sort, then let $\varphi(s)$ be equal to $(n, s)_K$ where $(\cdot, \cdot)_K$ denote the Kuratowski pair.
Let $\varphi$ perform similar replacements in the interpretation of every relation, function, and constant symbol.
$\varphi$ is an isomorphism when looking at each sort individually.
However, it has the nice property that we force every pair of elements of the original model that were in different sorts to have different first elements in their new interpretation.


How can I add a legend to geom_function in ggplot2

Question: In ggplot, how can I add a legend entry for each of the geom_functions so that the color and linetype are displayed (e.g for fun1 a short dotted red line), along with a custom name that I choose?
ggplot(data = data.frame(x = seq(0, 1, by=0.01)), mapping = aes(x=x)) +
  geom_function(fun = fun1, linetype='11', color='red') +
  geom_function(fun = fun2, color='dark green') +
  geom_function(fun = fun3, linetype='dashed', color='blue')

Answer: You can define them inside aes, here is an example with 3 random functions
Code
ggplot(data = data.frame(x = seq(0, 1, by=0.01)), mapping = aes(x=x)) +
  geom_function(fun = dnorm,aes(col = "fun1"))+
  geom_function(fun = dexp,aes(col = "fun2"))+
  geom_function(fun = sin,aes(col = "fun3"))+
  #Defining the colors
  scale_colour_manual(values = c("red","black","purple"))

Output
Comment: But what if I want to use specific colors for each function?
Comment: You can set them with `scale_colour_manual`, for example, `scale_colour_manual(values= c("black","red","purple")`
Comment: I updated my answer @AnIgnorantWanderer
Comment: what about the linetype? is it not possible for it to appear in the legend?