Writing an if statement in axios setting URL

Question: I want to write an if statement in axios setting URL config to check if the method is post do not send the params but I get syntax error.
Something like code below
    if (method = 'GET') {
        params: req.params,
    },

Code without if statement that works fine:
    axios({
      url: API_URL + req.url,
      method: req.method,
      params: req.params,
      data: req.body,
      if (body) {

      }
    })

Comment: When one uses `someMethod({ .... })` it means one is passing an object as a parameter to a method named `someMethod`. If one needs to add an `optional` key-value pair into the parameter, this may be useful: `someMethod({ key1: "val1", key2: "val2", ...( someCondition ? {optionalKey1: "optionalVal1"} : {}) });`
Answer: Assuming that params needs to be passed optional [from question: check if the method is post do not send the params] in the below code-sample:
axios({
  url: API_URL + req.url,
  method: req.method,
  params: req.params, // make this optional based on method != POST
  data: req.body,
})

Please try something like this:
axios({
  url: API_URL + req.url,
  method: req.method,
  data: req.body,
  ...(
    (req.method !== 'POST')
    ? { params: req.params }
    : {}
  )
});


How to modify if a field is required in a form?

Question: Use case: I have added a required field for users. When user 1 (or an administrator) adds a user, the field should not be required.
Code that doesn't work (in Drupal 8):
<code>function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    if (\Drupal::currentUser()->id() == 1) {
      $form['field_fieldname']['#required'] = FALSE; // No effect
      $form['field_fieldname']['widget']['#required'] = FALSE;
    }
  }
}
</code>
Changing the widget "works", but the validation fails. The solution for Drupal 7 doesn't seem to be usable anymore.
<code>$form['field_fieldname'][<lang>][0]['value']['#required'] = FALSE;
</code>
Comment: Not sure try $form['account']['field_fieldname'][][0]['value']['#required'] = FALSE;
Answer: It can be tricky to bybass D8 entity validation scheme in this way.
Why don't you just set this field settings as "not required" and then set
<code>$form['field_fieldname']['widget'][0]['#required'] = TRUE
</code>
when
<code>\Drupal::currentUser()->id() != 1
</code>
Comment: Basically the right approach, make it not required by default and then change it to required conditionally. Keep in mind that this will *only* protect the form, you should also implement a validation constraint to validate this on the API level, in case you ever need this validation to work for REST or other API oriented things. Also, I'd recommend to not hardcode uid 1, instead work with permissions, for example \Drupal::currentUser()->hasPermission('administer users') in such a case.
Comment: Nikko: I prefer that the website/UI shows the default behavior (required) and that custom code handles the exceptions, but this is definitely a work-around. (Is the extra nesting, "[0]", a typo?)
Berdir: The code was written for user 1 - and nobody else.
Comment: hansfn: did you find a way to do this, without inverting the behavior? So that for most users the field is required, except for the defined user? Nikko: you state "It can be tricky to bybass D8 entity validation scheme in this way" - do we know if Drupal 8 has a documented, correct way to do this? Currently I am setting $form['field_name']['#access'] = FALSE; in my hook_form_alter. This works, because core's EntityConstraintViolationList class respects '#access' in its filterByFieldAccess method. It's not user-friendly though, because the field disappears from the form completely for the user.


C# Syntax SQL Error Select ... Insert

Question:
"The select list for the INSERT statement contains fewer items than
  the insert list. The number of SELECT values must match the number of
  INSERT columns."

I have a question is this right? The construction of my codes?
private void btnCheckOut_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("Are you done adding your items?","Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (res == DialogResult.Yes)
            {
                Conn = k.getConn();
                Conn.Open();
                str = "INSERT INTO Items (itemCode, itemBrand, itemColor , qty) SELECT itemCode, itemBrand, itemColor FROM Purchase";
                cmd = new SqlCommand(str, Conn);
                cmd.ExecuteNonQuery();
                dr = cmd.ExecuteReader();
                cmd.Dispose();
                Conn.Close();

            MessageBox.Show("Successfully Added to your CART" ,"Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else if (res == DialogResult.No)
        {

        }
    }`

And i want to transfer that in the database named Items
Comment: `Insert` column list has **four** columns and `Select` column list **three** columns.
Comment: And what is the purpose of the call to ExecuteReader after the ExecuteNonQuery?
Comment: `INSERT INTO Items (itemCode, itemBrand, itemColor , qty) SELECT itemCode, itemBrand, itemColor, qty FROM Purchase`
Comment: you need key word VALUES instead of SELECT
Comment: @ChenChi No no no, definitely `SELECT` is the easier and correct way here
Comment: @Prdp thank you for reminding me that
Answer: In the query for insert there are 4 columns
INSERT INTO Items (itemCode, itemBrand, itemColor , qty)

in the select there are only 3 columns
 SELECT itemCode, itemBrand, itemColor FROM Purchase

It should be as follows
INSERT INTO Items (itemCode, itemBrand, itemColor , qty)
SELECT itemCode, itemBrand, itemColor,qty FROM Purchase

Comment: What if i add something like this , please check if this is right or wrong
INSERT INTO Items(itemCode, itemBrand, itemColor, qty , itemPrice)
SELECT itemCode, itemBrand, itemColor, qty ," + tb1.Text " + " @Berkay
Comment: @AllemMontinola I am not owner of the solution, I just corrected the format.
Answer: In the query below:
str = "INSERT INTO Items (itemCode, itemBrand, itemColor , qty) SELECT itemCode, itemBrand, itemColor FROM Purchase";
cmd = new SqlCommand(str, Conn);

you must pass exactly four column names in the select query so that the clumn list matches the columns list of insert query. If you donot want to fetch data for quantity column, then remove it from the INSERT query.
You can also set a default value for the quantity column in your database to ensure that it gets a default integral value instead of NULL.
Secondaly, there is no need to use the following statement after ExecuteNonQuery():
dr = cmd.ExecuteReader();

because you are not doin anything with the data that may be conming to dr.
Instead, if you are trying to get the number of rows affected by the insert query, you can use the following code:
int cnt = cmd.ExecuteNonQuery();

and then show the value of this variable where ever you want, may be in a label.
Hope this helps.
Comment: See, ExecuteReader returns a resultset containing data fetched by select statement. It is strictly used for fetching records. Please tell me the purpose of using ExecuteReader in your code so that I can guide you in a better way.
Comment: It really WORKS thanks ! and one last question what will I do to
Comment: I need your help.. is this right? @Shobit Gupta
INSERT INTO Items(itemCode, itemBrand, itemColor, qty , itemPrice) SELECT itemCode, itemBrand, itemColor, qty ," + tb1.Text " + "
Comment: Hi. This is not the right implementation. In the list of columns, you need to put up the names of columns that exist in the database and not the data from textboxes.

C# Syntax SQL Error Select ... Insert


Node - Test if function call with 2 arguments using mocha/chai

Question: How can i test if function call with 2 arguments using mocha/chai?
describe('EncryptCode Test', () => {

   it('EncryptCode function return a string', () => {
    expect(EncryptCode.Encrypt('fArgs','sArgs')).to.be.an('string');
   });

   it('EncryptCode function call with 2 arguments', () => {
     ???????????
   });

});

Answer: You can do some analysis/manipulation on the stringified function declaration.
let args = EncryptCode.Encrypt.toString().match(/\((.*)\)/)[1].split(',');
expect(args).length(2);

Comment: Best to add supporting text to your code snippets so they don't get flagged for deletion


Error to report with median and graphical representations?

Question: I've used a wide array of tests for my thesis data, from parametric ANOVAs and t-tests to non-parametric Kruskal-Wallis tests and Mann-Whitneys, as well as rank-transformed 2-way ANOVAs, and GzLMs with binary, poisson and proportional data. Now I need to report everything as I write all of this up in my results.
I've already asked here how to report asymmetrical confidence intervals for proportion data. I know that standard deviation, standard error or confidence intervals are appropriate for means, which is what I'd report if all my tests were nicely parametric. However, for my non-parametric tests, should I be reporting medians and not means? If so, what error would I report with it?
Associated with this is how best to present non-parametric test results graphically. Since I largely have continuous or interval data within categories, I'm generally using bar graphs, with the top of the bar being the mean and error bars showing 95% CI. For NP tests, can I still use bar graphs, but have the top of the bar represent the median?
Thanks for your suggestions!
Comment: Something doesn't compute.  How can you have means or medians or CIs with categorical data?
Comment: Sorry that wasn't clear @rolando2...I have categories in which I have continuous or interval data (original question was edited to clarify now).
Answer: You can report a confidence interval for the median.  In R, you can use wilcox.test with the argument conf.int=TRUE.  There's a tiny discussion of this in John Verzani's simpleR notes: see here.
Regarding plots: I don't really like using bar plots even for representing a set of means.  I'd prefer to just plot little line segments for the CI:

The plot on the right was made with errbar() from the Hmisc package [CRAN page].
You could make the same sort of plot for the medians and the related confidence intervals, or you could use box plots (which, in the same amount of space, describe the entire distribution).
Comment: @Mog: The bars seem a waste of ink/space; they force you to include 0 on the y-axis, which is often not necessary; and they prevent you from showing the lower halves of the intervals. The bars could be made worse (eg with gratuitous 3d).  With small datasets, I prefer to show the actual data points.
Comment: Thanks for the tips Karl! Is there a particular reason you don't like bars, or is it personal preference?


Add html widget programmatically to the list "Add fields" in views in Drupal 7

Question: I'm trying to create a html widget that will be available in all views. I would like to have the widget available in the list "Add fields" in views.
The module Easy social have this functionality, but I can't figure out how they did that.
So how can I from my module programmatically add fields to the list "Add fields" for views?
Any help appreciated.
Answer: This documentation will help you, just add a field handler then you are done! Click here

Add html widget programmatically to the list “Add fields” in views in Drupal 7


OLS interpretation - if Y increases due to X increasing, can I say that if X decreases, Y will decrease with the same magnitude?

Question: $$ \ln(y)=b + 0.25\ln(X) + \epsilon $$,
i.e. for $10\%$ increase in $X$, we observe about $2.5\%$ increase in $Y$.
Can I claim that if I reduce $X$ by $10\%$, then Y will drop $2.5\%$?
Can such two-way conclusions be derived always from an OLS regression? If we plot it, you can move up and down the line, the slope is always the same, therefore the answer should be Yes?
Comment: Be careful with "Y will drop": there is an error term, so even if the model is correct you're only talking about the expected value given X.
Comment: No.  You can't say that.  As Adrian indicated, you must make this statement in terms of means, or expected values as that's what the result of OLS tells you.  But you could say, "if land decreases by 1% then sales are expected to decrease by .5% on average.
Comment: Thanks, Adrian, i get your point. I am wondering, if I can say that e.g.: 1% increase in agricultural land can result in 0.5% increase in company sales; than I can also say that if land decreases by 1%, than sales can be expected to decrease by 0.5%? Can the interpretation of OLS results be done this way, two-way?
Answer: On top of what other users said in the comments that emphasize the importance of mean, here is another alternate point of view that's too long as a comment:
You can work this out. For x to increase by 10%, the difference is:
$\ln(y_{10\%up}) - \ln(y) = b + 0.25\ln(1.1x) - b - 0.25\ln(x)$
$\ln(y_{10\%up}/y) = 0.25\ln(1.1)$
$y_{10\%up}/y = 1.024114$
Which is about 2.4% increase.
Now for 10% decrease:
$\ln(y_{10\%down}) - \ln(y) = b + 0.25\ln(0.9x) - b - 0.25\ln(x)$
$\ln(y_{10\%down}/y) = 0.25\ln(0.9)$
$y_{10\%down}/y = 0.97400037$
Which is about a 2.6% drop.
So, I guess there are two points:

Multiplicative interpretation like this probably does not work like usual linear regression with untransformed variables because the denominators are different.
The statement "when it's ln(y) and ln(x), the regression coefficient can be interpreted as elasticity" is approximated, when the coefficient gets bigger and bigger this rule of thumb may deviate more and more from the actual number.


Vaught's theorem on number of countable nonisomorphic models

Question:
D.Marker Model Theory:
  Theorem 4.4.6: $I(T,\aleph_0)\neq2$
  Proof. Suppose that $I(T,\aleph_0)=2$. By Corollary 4.3.8 ii), there is $\mathcal{N}$ a prime model of $T$ and $\mathcal{M}$ a countable saturated model of $T$. Because $T$ is not $\aleph_0$-categorical, by Theorem 4.4.1, there is a nonisolated type $p \in S_n(T)$ for some $n$. The type $p$ is realized in $\mathcal{M}$ and omitted in $\mathcal{N}$. Let $a \in M$ realize $p$. Let $T^*$ be the $L_ \overline{a}$-theory of $\mathcal{M}_\overline{a}$ (in the notation of the previous lemma).
  By Theorem 4.4.1, there are infinitely many $T$-inequivalent formulas in the free variables $v_1,...,v_n$. As they are still $T^*$-inequivalent, $T^*$ is not $\aleph_0$-categorical. By Lemma 4.4.5, $M_\overline{a}$ is a saturated $L_\overline{a}$-structure. Thus, by Corollary 4.3.8 i), $T^*$ has a countable atomic model $\mathcal{A}$. Let $\mathcal{B}$ denote the $L$-reduct of $\mathcal{B}$. Because $\mathcal{A} \models T^*$, $\mathcal{B}$ contains a realization of $p$, thus $\mathcal{B} \not\cong  \mathcal{N}$. Because $T^∗$ is not $\aleph_0$-categorical, there is a nonisolated $L_\overline{a}-$type. This type is not realized in $\mathcal{A}$. Thus $\mathcal{A}$ is not saturated. If $\mathcal{B}$ were saturated, then, by Lemma 4.4.5, $\mathcal{A}$ would be saturated. Thus, $\mathcal{B} \not\cong \mathcal{M}$ and $I(T,\aleph_0)   \geq 3$.

I have a questions on this proof, which I would be happy for your hints or answers.
Why is this true that "Because $\mathcal{A} \models T^*$, $\mathcal{B}$ contains a realization of $p$"?
Answer: Remember that $T^*$ is the $L_{\overline{a}}$-theory of $\mathcal{M}_{\overline{a}}$. So the language of $T^*$ contains a new sequence $\overline{c}$ of constant symbols (intended to refer to the elements of the tuple $\overline{a}$), and - among other things - contains the sentence "$\varphi(\overline{c})$" whenever $\varphi\in p$ (since whenever $\varphi\in p$, we have $\mathcal{M}_{\overline{a}}\models\varphi(\overline{a})$).
So suppose $\mathcal{A}\models T^*$. Then the tuple in $\mathcal{A}$ corresponding to the constant symbols $\overline{c}$ - call this tuple "$\overline{u}$" - satisfies each $\varphi\in p$. But these $\varphi$s are $L$-formulas! So in the reduct $\mathcal{B}$, the same tuple $\overline{u}$ still satisfies each $\varphi$. So $\overline{u}$ realizes $p$ in $\mathcal{B}$.
Remember that $\mathcal{B}$ is the same structure as $\mathcal{A}$, with the same elements - only we "forget" about the structure beyond $L$. But "realizing $p$" is purely $L$-ish; so if $\overline{u}$ realizes $p$ in $\mathcal{A}$, it still realizes $p$ in $\mathcal{B}$.

Based on the comments below, I think it would be useful to give an example of this process.
Suppose my structure $\mathcal{M}$ is $(\mathbb{N}; +, \times, 0, 1)$. So the language has two binary function symbols, and two constant symbols, say $L=\{\oplus, \otimes, d_0, d_1\}$, interpreted in $\mathcal{M}$ in the obvious way.
And suppose my $T$ is the whole theory of $\mathcal{M}$ (that is, true arithmetic) and my $a$ (a single element for simplicity) is $17$. Then:

$L_a$ is the same language as $L$, but with a new constant symbol $c$; so $L_a=\{\oplus, \otimes, d_0, d_1, c\}$.
$\mathcal{M}_a$ has the same underlying set as $\mathcal{M}$, and $+$, $\times$, $0$, $1$ are interpreted in the same way; and the constant $c$ is interpreted as $17$.
$T^*$ contains $T$, but also contains new sentences involving the symbol "$c$". For example, it contains each of the following sentences:

$\forall x\forall y(x\otimes y=c\implies(x=d_1\vee y=d_1))$ $\quad$("$c$ is prime")
$\exists x[((d_1\oplus d_1)\otimes x)\oplus d_1=c]$ $\quad$("$c$ is odd")
$(d_1\oplus d_1)\otimes (d_1\oplus d_1)\otimes (d_1\oplus d_1)\otimes (d_1\oplus d_1)\oplus d_1=c$ $\quad$("$c$ is seventeen"),

because they are each true statements about $17$ in the structure $\mathcal{M}$.

Now, some other model $\mathcal{A}$ of $T^*$ will be a model of $T$, together with a "named element" $u$ (the thing named by the symbol "$c$"), and $\mathcal{A}$ will believe that $u$ satisfies every formula that $17$ did in $\mathcal{M}$ - because every such formula, with the variable replaced by the symbol "$c$", is in $T^*$, which $\mathcal{A}$ is a model of. For instance, the formula "$x$ is odd" will be true, in $\mathcal{A}$, of $u$, because the sentence "$c$ is odd" is in $T^*$, and in $c^\mathcal{A}=u$.
So in particular, in the reduct $\mathcal{B}$ of $\mathcal{A}$, the element $u$ (which is still in $\mathcal{B}$ - the underlying set of the structure hasn't changed at all, only the language is different) satisfies every formula that $17$ satisfies in $\mathcal{M}$. So - if $p$ is the type of $17$ in $\mathcal{M}$ - $u$ realizes $p$ in $\mathcal{B}$.
Comment: @Aref Um, what? Sentences are *most definitely* in a language - the language refers to the set of non-logical symbols (e.g. "$\forall x\exists y(P(x, y))$" is a sentence in the language $\{P\}$). The language $L_{\overline{a}}$ consists of the old language, plus some new constant symbols $c_1, c_2, ..., c_n$ - as many as there are elements in the tuple $\overline{a}=(a_1, a_2, ..., a_n)$. The theory $T^*$ consists of the old theory $T$ plus every sentence true of $\mathcal{M}$ about the parameters $\overline{a}$, with the *object* $a_i$ replaced with the *symbol* $c_i$
Comment: @Aref Re: your second question, $\mathcal{A}$ is an $L_{\overline{a}}$-structure - that means the new constant symbols $\overline{c}$ are *interpreted* in $\mathcal{A}$, that is, each $c_i$ "names" some $u_i\in \mathcal{A}$. That's what I mean by "the tuple corresponding to the constant symbols $\overline{c}$" - I mean the tuple named by those constant symbols.
Comment: @Aref I've edited my answer to contain a detailed example of this construction. Hopefully this clarifies what's going on (I think you might be confusing a couple things).
Comment: Thank you for your through answer. There are still questions I need to ask, first you've said "the language of $T^*$ contains a new sequence $\overline{c}$ of constant symbols and contains the sentence $\phi(\overline{c})$; but sentences can not be in a language and why you say a sequence of symbols, I think we have just added a constant symbol to our new structure! Second, what do you mean by the tuple in $\mathcal{A}$ corresponding to the constant symbols $\overline{c}$?
Comment: Thank you dear Noah, splendid work you've done. Thank you! I said a language does not contain a sentence because of this definition from Lou Van Den Dries lecture notes on logic:                                                            A language $L$ is a disjoint union of:
(i) a set $L^r$ of relation symbols; each $R \in L^r $ has associated arity $a(R) \in N$; (ii) a set $L^f$ of function symbols; each $F \in L^f$ has associated arity $a(F) \in N$.


Populando um dicionário de dicionários através de um loop for

Question: To tentando criar um loop para adicionar informações em um dicionário de dicionário. A chave mais externa do dicionário será o nome de um curso, e o valor será outro dicionário, haverão 6 chaves, referentes a forma de ingresso na faculdade, e o valor dessas chave será a média do preço da mensalidade para aquele grupo (curso e forma de entrada)
entrada = {}
cursos = {}

for curso in toledo.curso.unique():
    materia = toledo[toledo['curso'] == curso]
    for forma_de_entrada in materia.forma_de_entrada.unique():
        media = materia[materia['forma_de_entrada'] == forma_de_entrada].valor_liquido_da_mensalidade.mean()
        entrada[forma_de_entrada] = media
    cursos[curso] = entrada

Até consegui popular o dicionário, porém os valores das médias são iguais para todos os cursos. Também tentei limpar o dicionário entrada depois de ter adicionado ele ao dicionário cursos, mas também não da certo.
Comment: Ninguém teve como ajudar você nessa questão por que o código está incompleto - olhando só o código que você colocou quem está olhando tem que adivinhar que "toledo" é um dataframe do pandas - é importante colocar no código algo "mimamente reprodutível" - inclusive com uma linha que crie um dataframe mínimo com os exemplos de dados que você tem
Answer: Consegui fazer de outra maneira, ao invés de popular um dicionário de outros dicionários, populei ele com objetos groupby.
dic = {}

for curso in toledo.curso.unique():
    media_curso = toledo[(toledo['curso'] == curso) & (toledo['status'] == 'matriculado')].groupby('forma_de_entrada')\
                  .valor_liquido_da_mensalidade.mean()
    dic[curso] = media_curso

Apesar de eu ter conseguido, queria saber se é possível fazer isso com um dicionário de dicionários, e se tem um jeito melhor para resolver isso.
Valeu.


Can we turn $\mathbb{R}^n$ into a field by changing the multiplication?

Question: Of course $\mathbb{R}$ is a field with usual addition and multiplication.  When we move up a dimension into $\mathbb{R}^2$, however, there is not a clear way to multiply two vectors together to get something useful.  In fact, if we define multiplication of two vectors component-wise (as is arguably the most natural way), we get something that isn't even an integral domain.  However, if we implement the multiplication
$$ (a, b)(c, d) \mapsto (ac - bd, ad + bc), $$
then we obtain a copy of $\mathbb{C}$, which is again a field.  Can we do this for higher dimensions? That is, is there some clever multiplicative structure on $\mathbb{R}^3$ that produces a field? $\mathbb{R}^n$?
Comment: it depends on how much structure do you want to preserve?
Comment: http://mathoverflow.net/questions/9014/field-structure-for-rn
Comment: @bubba The resulting structure is not an integral domain, because $(1,0)*(0,1) = (0,0)$, and hence not a field.
Comment: @azarel I'm not sure what you mean.  Retain the structure of $\mathbb{R}^n$ as a vector space?
Comment: I mean you can make $\mathbb R^3$ isomorphic to any field of cardinality continuum, without any further restrictions
Comment: I'm puzzled. If we define multiplication (*) componentwise by $(a,b)*(c,d) = (ac,bd)$, then doesn't $\mathbb{R}^2$ become a field?? If not, what goes wrong?
Answer: It is a consequence of the theory of characteristic classes of vector bundles that the existence of a bilinear product $\mathbb{R}^n \times \mathbb{R}^n \rightarrow \mathbb{R}^n$ without zero divisors implies that $n$ is a power of 2. In fact it is only possible for $n=1,2,4,8$ where in dimensions 4 and 8 we get quaternions and octonions both of which are not fields because commutativity fails for both and associativity of the product fails for the octonions.
Comment: Could you add a source to this powerful claim?
Comment: You do not get the algebras you listed —in fact, the possible algebras have not yet been classified,  afaict. We do get the four algebras you mention if we restrict to composition algebras or add some other such hypothesis.
Comment: There is a nice proof in Milnor's Characteristic Classes book that the existence of the product implies paralelizability of $RP^{n-1}$ and that $n$ must be a power of 2. To show that $RP^{n-1}$ is not parallelizable for $n>8$ he refers to an article of Kervaire: Non-paralellizability ofthe sphere for $n>7$.

@Mariano you are right, this only gives a restriction on the dimension, not a classification as I said.
Answer: No, there is no field extension of $\mathbb R$ of degree $n$ other than for $n=2$, and we get something isomorphic to the complex numbers.
At least with hindsight, this is not so surprising, if not "obvious", because $\mathbb C$ is algebraically closed (from Liouville's theorem, a corollary of Cauchy's theorems).
Yes, in some ways this is unfortunate, since certain scenarios are precluded. An example of a way to circumvent these obstacles is Hamilton's creation of "quaternions", a four-dimensional $\mathbb R$-vectorspace, which unfortunately (and surprisingly, tittilatingly, in Hamilton's time) produces a non-commutative ... thing.
That is, $\mathbb R$ is "so close" to being algebraically closed that it admits only something isomorphic to $\mathbb C$ as literal field extension. And, perhaps even-more-disappointingly, only $\mathbb H$ as division-algebra extension.
Comment: Don't forget the even "worse" [Octonions](https://en.wikipedia.org/wiki/Octonion) which aren't even associative...
Answer: As an abelian group $\mathbb R^n$ is isomorphic to $\mathbb R$, so you just need to fix an isomorphism and use it to transport the structure.
Comment: This way you get a field without changing the way addition works.
Comment: (I edited a typo. I guess this was from a device, so TeXing was not nice to type down, so I added it.)
Comment: @MarianoSuárez-Alvarez Sorry by my ignorance: how can one prove that $(\mathbb R^n,\boldsymbol{+})$ and $(\mathbb R,+)$ are isomorphic (abelian) groups?
Comment: @MatemáticosChibchas They both have dimension $2^{\aleph_0}$ as vector spaces over $\mathbb{Q}$, so they are abstractly isomorphic.
Comment: @MarianoSuárez-Alvarez Highly non-explicit, as I suspected...thanks anyway (it is not your fault ;-) ).
Answer: A clifford algebra gives a natural way to talk about products of vectors, using the geometric product.  The geometric product of vectors is the associative and distributive.  If $a, b, c$ are vectors, then
$$(a + b) c = ab + ac, \quad a(b+c) = ab + ac, \quad (ab)c = a(bc) = abc$$
These products of several vectors, along with their linear combinations, are referred to as multivectors.  The clifford, or "geometric", algebra thus forms a ring.  However, you might notice that I left out commutativity of multiplication.  The geometric product is not in general commutative, so while a field cannot in general be built this way, the ring structure of a geometric algebra can be quite useful and generalizes to all dimensions.


Criar virtualhost no windows (apache no ubuntu)

Question: Estou tentando configurar o meu apache para acessar uma pasta que se encontra no meu HD com windows, tenho 2 hds na máquina, um roda o ubuntu e o outro o windows.
O apache já esta instalado, inclusive eu já criei o arquivo:
/etc/apache2/sites-avaliable/vip.localhost.conf

Adicionei as linhas:

   ServerName vip.localhost
   ServerAlias vip.localhost
   ServerAdmin webmaster@localhost
   DocumentRoot /media/name/2E4C85684C852BA1/development
   ErrorLog ${APACHE_LOG_DIR}/error.log
   CustomLog ${APACHE_LOG_DIR}/access.log

E também fiz a alteração no arquivo de hosts, mas quando eu tento acessar vip.localhsot eu recebo o código:

403 Forbiden

No caso diz que eu não tenho acesso a esse diretório.
Alguém tem ideia do que tenho que fazer? Será que preciso montar uma pasta no ubuntu para ele conseguir acessar meus arquivos? Se sim como faço?
Comment: 403 significa acesso negado, existe condições de fornecer as permissões necessárias para essa pasta?
Comment: Provável causa é a falta da permissão de acesso que está na resposta do Ricardo (configurada na tag Directory). Estranhei a falta de tags na configuração, mas não sei como está a estrutura de includes, talvez tenham sido omitidas apenas para postar aqui.
Answer: Primeiro de tudo, verifique se na montagem do seu HD do Windows, ele possui permissão de leitura e escrita para o usuário www-data, que é o usuário que o Apache roda no Ubuntu.
Depois, crie um arquivo em /etc/apache2/sites-avaliable/seuvhost.conf e o conteúdo tem que ser parecido com esse aqui (para Apache 2.4.X):
<VirtualHost *:80>
    DocumentRoot /media/name/2E4C85684C852BA1/development
    ServerName yourserver.example.com

    <Directory /media/name/2E4C85684C852BA1/development>
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Order Allow,Deny
        Allow from all
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Feito isso, habilite esse novo VirtualHost com o comando:
sudo a2ensite seuvhost

E reinicie o Apache:
sudo service apache2 restart

Answer: Outro solução é Ter um servidor completo com o XAMPP(lampp).
só instalar o xampp
Dai é só iniciar o servidor e fazer as configurações no VirtualHost.


Prove that $ \lim_{n\to\infty}\frac{(2n-1)!!}{(2n)!!}=0 $

Question:
How do you prove:
  $$ \lim_{n\to\infty}\frac{(2n-1)!!}{(2n)!!}=0 $$
  where $(2n)!!=2n(2n-2)(2n-4)\cdots6\cdot 4\cdot2.$

I would do the trick $$2n=\frac{(2n-1)+(2n+1)}{2}\ge\sqrt{2n-1}\cdot\sqrt{2n+1}.$$ Therefore we have:
$$ 0\le\frac{(2n-1)!!}{(2n)!!}\le\frac{(2n-1)\cdot(2n-3)\cdots}{\sqrt{2n+1}\cdot\sqrt{2n-1}\cdot\sqrt{2n-1}\cdot\sqrt{2n-3}\cdots}=\frac{1}{\sqrt{2n+1}}\xrightarrow{n\to\infty} 0 .$$
But I think this is somewhat tricky. What are other ways to prove this limit? Thanks.
Comment: see (https://math.stackexchange.com/questions/1334359/determine-convergence-of-the-series-sum-n-1-infty-frac2n-12n?noredirect=1&lq=1). actually the corresponding  series diverges but Mark Viola answer really helps you!
Answer: A brute force solution would be to rewrite everything with proper factorials and then use Stirling's approximation.
A neater one would consist in taking the log:
$$\ln\left(\frac{(2n-1)!!}{(2n)!!}\right)=\sum \ln\left(\frac{2k-1}{2k}\right)=\sum \ln\left(1-1/2k\right)$$
Then using the fact that $\ln\left(1-1/2k\right)\sim -1/2k$ and that the harmonic series diverges, you may conclude that the log goes to $-\infty$, and that your limit is $0$.
Comment: https://en.wikipedia.org/wiki/Limit_comparison_test
Comment: How will you prove the substitution of $\ln (1-1/2k)$ into the series strictly?
Answer: Another way to do it.
$$a_n=\frac{(2n-1)!!}{(2n)!!}\implies \log(a_n)=\log((2n-1)!!)-\log((2n)!!)$$
Using the less used Stirling like approximation
$$\log(p!!)=\frac{1}{4} \log
   \left(\frac{\pi }{2}\right) \cos (\pi  p)+\frac{1}{2} ( \log (p)-1) p+\frac{1}{4} \left(\log (2 \pi )+2 \log
   \left({p}\right)\right)+\frac{1}{6 p}+O\left(\frac{1}{p^3}\right)$$ Using it twice and continuing with Taylor series gives
$$\log(a_n)=\frac{1}{2} \log \left(\frac{1}{\pi  n}\right)-\frac{1}{8 n}+O\left(\frac{1}{n^3}\right)$$  making
$$a_n \sim \frac{e^{-\frac{1}{8 n}}}{\sqrt{\pi n} }$$
For illustration purposes $S_5=\frac{63}{256}\approx 0.246094$ while the approximation gives $\frac{1}{\sqrt[40]{e} \sqrt{5 \pi }}\approx 0.246084$.


Parametric equation of a plane

Question: This is from the book An introduction to differential geometry by Willmore.

What function $f(u)$ would make the curve $\vec r=(a\cos u,a \sin u,
f(u))$ a plane?

My solution: If for example, I take $z=-a\cos u-a\sin u+c$ (where $c$ is a constant) then $x+y+z=c$ which is an equation of a plane.
Is this correct and if so are there any other solutions?
Answer: Any $a x+b y+c z= d$ is a plane, and so $$f(u)= d+ \lambda a \cos u + \mu a \sin u$$ is the function you are looking for.

Parametric equation of a plane


Define trailing stop in pinescript

Question: Is there a possibility in the pinescript code to include an initial stop order that is, for example, at 65 pips and then updates according to price changes with the trailling stop?
Can define and initial stop loss and after chage this stop loss with the trailing stop
Comment: Please show what you tried or reproduce the unexpected behavior you are asking about.
Answer: With the information you provided, it's difficult to answer your question.
Try strategy.exit with trail_offset
Something like this:
<code>// Return the entry price for the latest closed trade.
currEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)

//Stop loss (specified in ticks)
SL_ticks = 65

//Trailling Stop (specified in ticks)
TR_ticks = 10

if strategy.position_size > 0
    strategy.exit(
      id               = 'Long Exit',
      from_entry       = 'Long',
      loss             = SL_ticks,
      trail_price      = currEntryPrice,
      trail_offset     = TR_ticks)
</code>

Define trailing stop in pinescript


GAE Datastore and security risks with JDOQL

Question: I just started working on a project that will run on google app engine (GAE).  I'm using java (wicket) with some ajax.
I'm experienced with relational databases and typically use something like iBatis.  When going through the docs and examples for the GAE datastore using JDO I see that they're executing stuff like:
String query = "select from " + Employee.class.getName() + " where lastName == 'Smith'";
List<Employee> employees = (List<Employee>) pm.newQuery(query).execute();

Does anyone know if this JDOQL query is subject to security problems like SQL injection?  If so, is there any way to remedy this?
Answer: Yes, that is subject to sql injection (well, JDOQL injection in this case).  You should use parameters instead, as in the examples in the GAE/J documentation.
Query query = pm.newQuery(Employee.class);
query.setFilter("lastName == lastNameParam");
query.setOrdering("hireDate desc");
query.declareParameters("String lastNameParam");

try {
    List<Employee> results = (List<Employee>) query.execute("Smith");
    if (results.iterator().hasNext()) {
        for (Employee e : results) {
            // ...
        }
    } else {
        // ... no results ...
    }
} finally {
    query.closeAll();
}

Answer: Yes, in general it's vulnerable to injection vulnerabilities. In the examples in the docs, though, it doesn't apply - the class name is controlled by the author of the app, and the the last name in this case is a literal string.
Answer: Any JDOQL query is translated into the equivalent underlying query. In RDBMS it just happens to be SQL. In GAE/J it is their query API. That means it isn't definite that there is any "injection" of anything. You are the application developer and you define the queries, hence you have full control over such things.


What is kvm reboot?

Question: Some web hosting providers offer "kvm reboot" for their dedicated servers? What does that mean?
Does it mean the server reboots automatically after a crash or freeze?
Comment: KVM as in KeyboardVideoMouse or as in KernelVirtualMachine?
Answer: Often this means that you can remotely access the console over the network (KVM standing for Keyboard, Video, Mouse) and, further, trigger a reboot remotely even if the OS has completely gone to lunch.
Answer: Both bdonlan and Tom may be right - KVM stands both for Keyboard Video Mouse, which will give you remote access even to the BIOS pre boot stage of your server, or for Kernel Virtual Machine, which your server might be virtualized on.
You should contact the host you are considering to use and ask which of these they mean - know what you pay for.
Answer: KVM is a kernel-based virtual machine, and virtual machines typically reboot much faster than physical systems.  (However, I do not believe it will necessarily automatically reboot)  When using KVM, you also do not need to reboot the system to run a VM guest [1].
[1] http://searchservervirtualization.techtarget.com/news/article/0,289142,sid94_gci1318772,00.html
Answer: Kvm (Keyboard Video Mouse) is needed when your server does not come online or has issues while booting.
Using kvm, you can access your server through vnc and troubleshoot.

What is kvm reboot?


Help needed with the solution about Differential Equations.

Question: $$(x^2 + 4y^2)\dfrac {dx}{dy} = xy$$
In my opinion, I should separate dx and dy into opposite sites then look for mx = my or not.
Is this true? Or is it that the constant C only influences F(x) and so that makes it an important only to that part of the solution?
Thanks for help, I appreciated.
Comment: first get $dy/dx, \,$ use substitution $u = y/x$
Comment: Your differential equations textbook should have a discussion of "homogeneous" first-order DEs.  Presumably that is how @MathLover came up with the proper substitution.
Answer: $$(x^2 + 4y^2)\dfrac {dx}{dy} = xy$$
$$(x^2 + 4y^2) = xyy'$$
$$(x^2 + 4y^2)=\dfrac x2 (y^2)'$$
$$x^2 + 4v=\dfrac x2 v'$$
$$uv' -4v=u$$
$$\left ( \dfrac v {u^4}\right)'=\dfrac 1 {u^4}$$
Where $v=y^2,u=x^2$. Integrate both sides.
Comment: Thank you so much.
Answer: Hints: $$(x^2+4y^2)\frac{dx}{dy}=xy$$
This is a homogeneous differential equation.
Put $y=vx$.then,
$$(x^2+4v^2x^2)=x^2v(v+x\frac{dv}{dx})$$
Now you can proceed. Good luck!
Comment: thank you so much.
Comment: You're welcome:)


R - Update elements in ... (dot-dot-dot) and return

Question: I want to change some elements of ... argument in the child function and return it back to the parent function. So the ... is updated within the parent function. I give my idea and a simple example below (not working yet):
parent <- function(x, ...){
  ... <- child(x, ...) # expect to return and update ...
  child_2(x, ...)
}
child <- function(x, ...){
  args <- list(...)
  args$y = 10 # change value
  return(args)
}
child_2 <- function(x, ...){
  args <- list(...)
  print(args$y = 10) # expect y = 10
}
parent(x=1,y=2)

How can I realize my idea and make it workable?
Answer: Use do.call:
parent <- function(x, ...){
  args <- child(x, ...) # expect to return and update ...
  do.call("child_2", c(x = x, args))
}

child <- function(x, ...){
  args <- list(...)
  args$y = 10 # change value
  return(args)
}

child_2 <- function(x, ...){
  args <- list(...)
  print(args$y) # expect y = 10
}

parent(x=1,y=2)
## [1] 10

Old
The question was changed. This was the answer to the original question.
Change parent as shown.  child is unchanged.
parent <- function(x, ...) {
  args <- child(x, ...)
  args$y
}
parent(x=1,y=2)
## [1] 10

Comment: Thank you for the answer. I have made my question more specific. I like the `...` updated and can be used in another function (see child_2 function in my post).


Calcular tamanho de vetor

Question: Como calcular o tamanho do vetor?
Meu código:
#include <stdio.h>
#include <stdlib.h>

int retornaMediana(int *vetor){

int tam=0;

    tam = sizeof(vetor);

    printf("TESTE: %d, %d, %d\n\n",vetor[0],vetor[1],vetor[2]);

    return tam;

}

void main(){

int vetor[] = {5,25,7,10,13,33,45,11,60};
int n = retornaMediana(&vetor);
int n2;

n2 = sizeof(vetor)/sizeof(int);

    printf("TAMANHO = %d\n\n",n);
    printf("TAMANHO = %d\n\n",n2);

}

Como que eu faço pra função retornar o real tamanho do vetor ? Já passei por parâmetro, referência e nada, só recebo esse 4 como resposta.
Comment: E qual o resultado que você espera? Porque?
Comment: Qual é a finalidade do `n2 = sizeof(vetor) / sizeof(int);`?
Comment: Por favor, não altere o código na pergunta depois que ela foi feita - uma das respostas aponta para partes do código que mudaram e isso torna muito difícil acompanhar qualquer coisa.
Comment: Essa função era pra retornar tam, sendo o tamanho do vetor, ou seja, uma função que recebesse um vetor, e retornasse o seu tamanho.
Comment: o n2 era apenas um teste na main para testar se o sizeof funcionava.
Comment: Você quer o tamanho do vetor em bytes? é isso?
Comment: Aconselho uma leitura do [c-faq](http://c-faq.com/), especialmente a secção 6.
Answer: Esta linha está calculando o tamanho corretamente:
int len = sizeof(vetor)/sizeof(int);

Melhor seria
int len = sizeof(vetor)/sizeof(vetor[0]);

pois, caso você mude o tipo do vetor, não será surpreendido por um bug difícil de se perceber dependendo do contexto.
Importante entender que o sizeof já é resolvido pelo compilador, pois ele simplesmente já sabe o que foi feito na definição da variável, portanto, se precisar saber o tamanho de um vetor passado por parâmetro, a solução que resta é sempre passar o vetor e o tamanho.
Voltando ao seu código, o problema é que você está calculando certo o tamanho, porém acaba sobreescrevendo o valor nesta outra linha, desta vez com o tamanho do ponteiro:
tam = sizeof(vetor);

Uma saída seria calcular o tamanho dentro do escopo da declaração, como você já estava fazendo, e enviar o tamanho para a função da mediana.
Veja a diferença:
#include <stdio.h>
#include <stdlib.h>

int retornaMediana(int *vetor, int tam){
    // -- aqui você corre os ítens e calcula a mediana --
    // return mediana;
    printf("TESTE: %d, %d, %d\n\n",vetor[0],vetor[1],vetor[2]);
    return tam;
}

void main(){
    int vetor[] = {5,25,7,10,13,33,45,11,60};
    int len = sizeof(vetor)/sizeof(vetor[0]);

    int n  = retornaMediana( vetor, len );

    printf("TAMANHO = %d\n\n",n);
    printf("TAMANHO = %d\n\n",len);
}

Aqui tem uma demonstração no IDEONE.
Comment: mas vamos supor que eu queira uma função que receba apenas um vetor, e retorne o seu tamanho..
Comment: Sempre você vai precisar passar o tamanho. O `sizeof` funciona no momento da compilação.
Answer: Localmente se pode simplesmente chamar sizeof para calcular o tamanho do array, porém é sabido que em C, somente é passado o ponteiro do vetor para determinada função, então necessário percorrer o ponteiro para calcular o tamanho do vetor
#include <stdio.h>
#include <stdlib.h>

#define lenvetor(vetor)    (sizeof(vetor)/sizeof(vetor[0]))
#define VECSIZE            19

/*----------------------------------------------------------------------------*/

int lenarraychar(char *a[]) {
   int nlen = 0;

   while(*(a++)) {
      //while(*(a+nlen)){
      //while(a[nlen]){
      nlen++;
   }
   return nlen;
}

/*----------------------------------------------------------------------------*/

int lenarrayint(int p[]) {
   int nlen = 0;

   while(*(p++) || *p == 0 ) {
      nlen++;
   }
   return(nlen);
}

/*----------------------------------------------------------------------------*/

int main() {
   char *menustatic[VECSIZE] = {"Incluir", "Remover", "Listar", "Imprimir", 0};
   char *menudinamic[]       = {"Incluir", "Remover", "Listar", "Imprimir", 0};
   int vetorstatic[VECSIZE]  = {5,25,7,10,13,33,45,11,60,-1};
   int vetordinamic[]        = {5,25,7,10,13,33,45,11,60,-1};

   for(int i=0; i<VECSIZE; i++)
      printf("vetor[%d] = %02d\n", i, vetorstatic[i]);

   printf("============================\n");
   printf("TAMANHO menustatic   = %d\n",  lenarraychar(menustatic));
   printf("TAMANHO menustatic   = %d\n",  lenvetor(menustatic));
   printf("============================\n");
   printf("TAMANHO vetorstatic  = %d\n",  sizeof(vetorstatic)/sizeof(vetorstatic[0]));
   printf("TAMANHO vetorstatic  = %d\n",  lenvetor(vetorstatic));
   printf("TAMANHO vetorstatic  = %d\n",  lenarrayint(vetorstatic));
   printf("============================\n");
   printf("TAMANHO vetordinamic = %d\n",  sizeof(vetordinamic)/sizeof(vetordinamic[0]));
   printf("TAMANHO vetordinamic = %d\n",  lenvetor(vetordinamic));
   printf("TAMANHO vetordinamic = %d\n",  lenarrayint(vetordinamic));

   return 0;
}

Result:
vetor[0] = 05
vetor[1] = 25
vetor[2] = 07
vetor[3] = 10
vetor[4] = 13
vetor[5] = 33
vetor[6] = 45
vetor[7] = 11
vetor[8] = 60
vetor[9] = -1
vetor[10] = 00
vetor[11] = 00
vetor[12] = 00
vetor[13] = 00
vetor[14] = 00
vetor[15] = 00
vetor[16] = 00
vetor[17] = 00
vetor[18] = 00
============================
TAMANHO menustatic   = 4
TAMANHO menustatic   = 19
============================
TAMANHO vetorstatic  = 19
TAMANHO vetorstatic  = 19
TAMANHO vetorstatic  = 19
============================
TAMANHO vetordinamic = 10
TAMANHO vetordinamic = 10
TAMANHO vetordinamic = 11

O cálculo do tamanho com array de tamanho estático é calculado corretamente, porém é necessário algum ajuste para calcular corretamente um vetor dinâmico, mas já e algum começo
int lenarrayint(int p[]) {
   int nlen = 0;

   while(*(p++) || *p == 0 ) {
      nlen++;
   }
   return(nlen);
}

Answer: O vetor dentro do metodo agora é um ponteiro, então o tamanho será sempre 8 (se o seu arquivo for 64x), para calcular o tamanho dele, você deve criar um método que percorre o ponteiro e conte as posições.
int vec_len(int *vec){
    int c = -1;
    while(*(vec++))
        c++;
    return c;
}

Recomendo que use algum valor como 0 para identificar quando chegar no final do vetor.
Comment: Isto não faz o menor sentido.
Comment: Claro que faz, como se pega o tamanho de um ponteiro? Apenas percorrendo até a posição final, o `sizeof` em um ponteiro sempre retorna um númeroespecífico, e não acho que exista algo pronto em C que pegue quantos itens tem dentro de um ponteiro.
Comment: E como você sabe quando é o último elemento do ponteiro?
Comment: Então essa é a parte faltnado na resposta - o programador tem que convencionar um elemento que eserá o "marcador de final" - no caso, ele conta com uma convençao implicita de que ovetor se encerra no primeiro elemento de valor 0  - mas fora isso, esta é a rspotsa correta, e a outra é que não faz o menor sentido.

O que tem que ficar claro para o OP é que em C, não há metadados associados há um vetor  a não ser aqeules que você associa explicitamente,

As opçẽos são: ou ter um valro sentinela que indica o final (esse caso), ou contablizar o tamanho do vetor explicitamente em outra variável.
Comment: é um problema meio que sem solução então, se tivermos uma função que receba APENAS o vetor, e retorne o seu tamanho.

Calcular tamanho de vetor


Integrate $\int\limits_0^\infty \frac{{1}}{(a^2+x^2)^7}\,dx\\$

Question: $$\int\limits_0^\infty \frac{{1}}{(a^2+x^2)^7}\,dx\\$$
tried with $x = a\tan(y)$.
Comment: Welcome to the MSE community! Could you please show your own efforts at trying to solve it?
Comment: x=atan(y)
dx=asec^2(y)
integral changes to 0 to pi/2 1/a^13 * cos^12y
Comment: Looks about right, now you have a very annoying but also rather straightforward trigonometric integral to do. (This is of course assuming that you don't know anything about residue calculus. If you do then you can use that to take a shortcut.)
Answer: Let's consider a more general case,let $$I_n=\int_0^{+\infty} \frac{{1}}{(a^2+x^2)^n}dx$$Using partial integration, we have$$I_n=\frac{x}{(a^2+x^2)^n}\bigg|_{0}^{+\infty}+2n\int_0^{+\infty} \frac{{x^2}}{(a^2+x^2)^{n+1}}dx=2n\int_0^{+\infty} \frac{{a^2+x^2-a^2}}{(a^2+x^2)^{n+1}}dx=2nI_n-2na^2I_{n+1}$$We got it$$2na^2I_{n+1}=(2n-1)I_n,(2n-2)a^2I_n=(2n-3)I_{n-1}$$
So$$I_n=\frac{2n-3}{2n-2}\frac{2n-5}{2n-4}\cdots\frac{1}{2}\cdot I_1\cdot\left(\frac{1}{a^2}\right)^{n-1}=\frac{2n-3}{2n-2}\frac{2n-5}{2n-4}\cdots\frac{1}{2}\frac{1}{a^{2n-1}}\int_{0}^{+\infty}\frac{dx}{a^2+x^2}$$
Thus$$I_n=\frac{2n-3}{2n-2}\frac{2n-5}{2n-4}\cdots\frac{1}{2}\frac{1}{a^{2n-1}}\frac{\pi}{2}\cdot\varepsilon$$
Among$$\varepsilon=\begin{cases}
1,&a>0\\
-1,&a<0
\end{cases}$$
Comment: can you confirm my solution above in comments is correct or wrong?
Comment: @111111 First,the sign of the final result depends on $a$.Then,I'm sorry your result is not correct.You can compare the results I gave you.If my answer is helpful to you, please press Accepted
Comment: thanks for help got the correct ans did a silly mistake in calculation


Detecting a gate underwater composed of different colors

Question: I am participating in an Underwater Robotics Competition and the first task is to make AUV(Autonomous Underwater Vehicle) pass through a gate. The gate is composed of three colors - Image of gate
I have tried implementing a simple program to convert the image to grey scale and then use canny edge detection. The problem is that the yellow side is ignored by the edge detector. Moreover, the gate isn't exactly a rectangle, that is the bottom part is not exactly a pole.
I have also tried using the HSV color scheme to try and extract colors but this wouldn't work because colors get distorted underwater.
Any suggestions on what I should do?
Comment: Take multiple pictures underwater to get the color values for the gate. Then set  ranges based on that data set. If you want to go overboard with it, you could implement a learning algorithm.
Comment: This is way too broad. What have you tried codewise? Where exactly are you stuck?
Comment: It's good when posting a question to be ready to put a small program that you have attempted along with the desired goal(s).  BTW, your rectangle can be described by the yellow bottom and side...take a bunch of images and figure out how to threshold the yellow-ish colour and you'll have a good start.
Comment: This seems a bit too broad at the moment. It's not clear to me why you are doing this edge detection, I think you need to explain your overall plan an thought process here. Also, what exactly is your code responsible for in the end? Is it just a detection that you plug in some sort of SLAM at the end, or something more complete?
Comment: It seems to me that the gate is coloured in that unusual fashion for a reason, and that the yellow colour is the first thing that catches your eye. I think that converting to greyscale as the first step and discarding all that information is probably an error...
Answer: You can adjust a sensor in your robot at proper centre of you robot and set any distance of sensor that if any device come into there range then it will change its direction and also if it come in the centre of your gate then it will move in simple way


Collection  class location in the .net framework

Question: The Collection <T> class exists under the System.Collections.ObjectModel namespace. Why does it not exist under System.Collections.Generic instead?
Comment: mww thanks for thz improvement.  i m using my phone so it skeeped all this issues :)
Answer: It's because:

The System.Collections.ObjectModel namespace contains classes that can
  be used as collections in the object model of a reusable library. Use
  these classes when properties or methods return collections.

and Collection<T> can be used as a collection in the object model of a reusable library.
See
https://msdn.microsoft.com/en-us/library/system.collections.objectmodel(v=vs.110).aspx
The full explanation is here: https://blogs.msdn.microsoft.com/kcwalina/2005/03/15/the-reason-why-collection-readonlycollection-and-keyedcollection-were-moved-to-system-collections-objectmodel-namespace/
(That appears to explain the real reason, if you ask me...)
Comment: Great catch!!!!
Comment: BTW what seems very obvious it's just a design decision. I mean, who returns `Collection` instead of `ICollection`?
Comment: @MatíasFidemraizer Yes, I agree.


The method getActivity in the type PendingIntent is not applicable for the arguements

Question: I am getting this error while implementing SMS sending in android. Attaching the image as the error is too long :)
Answer: Bit hard to see but try this.
<code>PendingIntent pi = PendingIntent.getActivity(<YourActivityClass>.this, 0, ...
</code>


Password generation in C# using Membership.GeneratePassword and without white spaces

Question: Could anyone confirm me if this method generates a password without white spaces (blanks)?
I think it generates without white spaces, but I would like someone confirm me this.
In the msdn documentation it is not talked about white spaces.
Comment: Well, [here's the code](https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/Membership.cs#L302-L365)
Answer: It seems pretty clear from the documentation to me:

The generated password only contains alphanumeric characters and the following punctuation marks: !@#$%^&*()_-+=[{]};:<>|./?. No hidden or non-printable control characters are included in the generated password.

No mention of including whitespace characters.
Answer: According to MSDN:

The generated password only contains alphanumeric characters and the following punctuation marks: !@#$%^&*()_-+=[{]};:<>|./?. No hidden or non-printable control characters are included in the generated password.

So it shouldn't contain whitespace characters
Answer: According to the code, it generates passwords using the characters:

A-Z
a-z
0-9
any of !@#$%^&*()_-+=[{]};:>|./?


Find the limit $\lim_{(x,y)\to (0,0)}\frac{x\sin(y)}{x^2+\sin^2(y)} $

Question: Consider the limit
$$\lim_{(x,y) \to (0,0) }\frac{x\sin(y)}{x^2+\sin^2(y)} $$
I thought the limit does not exist, but plotting by software showed the limit should be 0. I've tried squeeze and episilon-delta proof, but haven't make any progress yet. Any hint or help are appreciated.
Answer: let $x=k\sin y$, than the given fraction is equal to $\frac k {k^2+1}$. Since $x$ is independent to $y$ we know that the given limit diverging.


Run time error '9' ,Subscript out of range error

Question: I am new to Excel and VBA programming, I have made attendance sheet and want to copy data from one sheet to other ( month wise) by pressing button.
I am getting error at the following line
lastrow1 = Sheets("Sheet14").Range("A" & Rows.Count).End(xlUp).Row
My code
Sub Button2_Click()

    Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
    Dim myname As String
    lastrow1 = Sheets("Sheet14").Range("A" & Rows.Count).End(xlUp).Row

    For i = 7 To lastrow1
        myname = Sheets("Sheet14").Cells(i, "A").Value

        Sheets("sheet2").Activate
        lastrow2 = Sheets("sheet2").Range("A" & Rows.Count).End(xlUp).Row

        For j = 7 To lastrow2

            If Sheets("sheet2").Cells(j, "A").Value = myname Then
                Sheets("Sheet14").Activate
                Sheets("Sheet14").Range(Cells(i, "D"), Cells(i, "AH")).Copy
                Sheets("sheet2").Activate
                Sheets("sheet2").Range(Cells(j, "D"), Cells(j, "AH")).Select
                ActiveSheet.Paste
            End If

        Next j
        Application.CutCopyMode = False
    Next i
    Sheets("Sheet14").Activate
    Sheets("Sheet14").Range("D7").Select
End Sub

Comment: @YowE3K  You're right, I've noticed afterwards , thanks :)
Comment: lastrow2 = Sheets("sheet2").Range("A" & Sheets("sheet2").Rows.Count).End(xlUp).Row
Answer: Your code had the wrong type of " , instead of ".
It's better to stay away from Activate , Select and ActiveSheet and use referenced Worksheet and Ranges instead (it will also be faster).
Try the code below, it will do the same, just a little faster (and more reliable not depending on the ActiveSheet.
Modified Code
Sub Button2_Click()

Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
Dim myname As String

With Sheets("Sheet14")
    lastrow1 = .Range("A" & .Rows.Count).End(xlUp).Row

    ' take the line below outside the For loop, there is no need to get the last row evey time
    lastrow2 = Sheets("sheet2").Range("A" & Sheets("sheet2").Rows.Count).End(xlUp).Row
    For i = 7 To lastrow1
        myname = .Range("A" & i).Value

        For j = 7 To lastrow2
            If Sheets("sheet2").Range("A" & j).Value = myname Then
                .Range("D" & i & ":AH" & i).Copy Destination:=Sheets("sheet2").Range(Range("D" & j & ":AH" & j))
            End If
        Next j
        Application.CutCopyMode = False
    Next i
End With

End Sub

Note: if the data in sheet2 and sheet14 are unique (appear only once in  the entire sheet) consider using the Match function, it will save you 1 For loop.
Comment: @Kanan I've just tested it now and it works for me, are you sure you have "sheet2" in your workbook ? spelled like this ?
Comment: @Kanan you copied my entire code from above ? all of it ? with al; `"` and not your `"` and still got this error ? can't trace it, sorry
Comment: @Kanan ok, but please open  a chat
Comment: @Kanan it's somewhere here in SO
Comment: I have not earn reputation for chat...not eligible...as this is first time.If you can provide me your email id I can send you file.


Proving that ${\rm Aut } G$ has an identity element

Question: In proving the set of automorphisms of a group $G$ is a group, I need to verify the existence of an identity element. I can manage to show that the identity map is an element of this group, but demonstrating that it performs the operation of an identity (which should be the easiest part) is confusing.
First, we take the map $e: G \to G$ defined by $x \mapsto x$. This map is surjective since for any $y \in G$, $\exists x = y$ such that $e(x) = y$. This map is injective since $e(x) = e(y)$ implies $x = y$ for any $x, y \in G$. Thus, $e$ is bijective. Since for any $x, y \in G$, we have
\begin{align*}
e(xy) = xy = e(x)e(y),
\end{align*}
$e$ possesses the homomorphism property. Thus, $e$ is an isomomorphism from $G$ to itself, and is hence an element of ${\rm Aut } G$.
The role that this map $e$ should play is that for any $f \in {\rm Aut }G$, we have
\begin{align*}
e \circ f = f \circ e = f.
\end{align*}
For the map $f: G \to G$, $x \mapsto y$, where $f \in {\rm Aut } G$, we have
\begin{align*}
(e \circ f)(x)  &= e(f(x)) = e(y) = y \\
(f \circ e)(x) & = f(e(x)) = f(x) = y.
\end{align*}
Hence, $e \circ f = f \circ e$ since $x \in G$ was arbitrary.
Is this a valid proof? Have I missed anything?
Comment: Did you rename $i$ to $e$ on the fly?
Comment: In the second last equation it should be $f(x)$ not $e(x)$.
Comment: @PrudiiArca It's $e(y)$, but I agree the notation is confusing.
Comment: I accidently used $i$ and $e$ interchangeably. Sorry about that. I'll use more consistent notation.
Comment: I apologize. Why is it $f(x)$? I must be missing something.
Comment: @Christoph But how is $e(f(x)) = e(x)$? This does not make sense to me. It should be $e(f(x)) = f(x)$, which is precisely what we want to show...
Comment: @PrudiiArca It says $e(f(x)) = e(y)$, since $f(x)=y$. There is no $e(x)$ there.
Comment: Sorry I did not notice the change from $f(x)$ to $y$, what you wrote is absolutely correct. My bad. This kind of highlights the point of part 2 of @Christoph 's answer...
Answer: Your proof is fine. I'd just suggest two modifications:

Instead of calling the identity map on $G$ by names like $i$ or $e$, just stick to the usual convention of $\operatorname{id}_G$.
When you consider an arbitrary automorphism $f\colon G\to G$, don't define it as "$x\mapsto y$". This "$y$" depends on the choice of $x$, and that gets lost in your notation. Just keep referring to it as $f(x)$.

Hence, your equations become:
\begin{align*}
(\operatorname{id_G}\circ f)(x) &=
\operatorname{id_G}(f(x)) = f(x), \\
(f\circ \operatorname{id_G})(x) &=
f(\operatorname{id_G}(x)) = f(x). \\
\end{align*}
Furthermore, in the conclusion you need
$$
\operatorname{id_G}\circ f =
f\circ\operatorname{id_G} = f.
$$
You missed the last part.


DHCP server can't assign addresses to some machines

Question: I have a dhcp server here, running the isc-dhcpd daemon.
Some machines get an IP address fine, from syslog:
Dec  8 08:42:21 nethandler dhcpd: DHCPDISCOVER from 90:e6:ba:f6:xx:xx via eth0
Dec  8 08:42:21 nethandler dhcpd: DHCPOFFER on 10.0.0.202 to 90:e6:ba:f6:xx:xx via eth0
Dec  8 08:42:21 nethandler dhcpd: DHCPREQUEST for 10.0.0.202 (127.0.1.1) from 90:e6:ba:f6:xx:xx via eth0
Dec  8 08:42:21 nethandler dhcpd: DHCPACK on 10.0.0.202 to 90:e6:ba:f6:xx:xx via eth0

Others don't
Dec  8 08:42:04 nethandler dhcpd: DHCPDISCOVER from 08:00:27:d5:xx:xx (WIN-3053MGTDBGP) via eth0
Dec  8 08:42:04 nethandler dhcpd: DHCPOFFER on 10.0.0.132 to 08:00:27:d5:xx:xx  (WIN-3053MGTDBGP) via eth0
Dec  8 08:42:08 nethandler dhcpd: DHCPDISCOVER from 08:00:27:d5:xx:xx  (WIN-3053MGTDBGP) via eth0
Dec  8 08:42:08 nethandler dhcpd: DHCPOFFER on 10.0.0.132 to 08:00:27:d5:xx:xx  (WIN-3053MGTDBGP) via eth0

And continue ad infinatum. I can't find any pattern to the machines that can't connect. Some wireless clients can't connect, some can. An ubuntu vm can connect, a windows 7 vm on the same hardware can. A windows server on the same hardware can't. A few macs here can't.
Any help would be appreciated, or a point to what I can use to further debug the problem.
Answer: Try doing a packet capture on the client. dhcpd thinks it's sending out an OFFER, either the client is ignoring it or (more likely) the offer never makes it to the client.
While you're at it, also do a packet capture on the server, and if you can, on something in-between (a SPAN/Mirror port on the switch, router port, etc.).
Comment: I have solved the problem. server-identier was incorrectly set in my dhcpd.conf, so the DHCPACK's would have been incorrectly addressed. Updated that and everything went. Thankyou.
Answer: Look for a DHCP rogue server on your network. There is a free microsoft tool to search.  Also, make sure you are using IPhelpers on your switches.
Comment: No rogue servers, or evidence that there were.
I'm not sure what made you think there would have been?
Comment: IP helpers are on routers, not switches. If the DHCP server has an interface on the network, IPhelper is not needed.
Comment: As to rogue DHCP servers, no need for a Microsoft tool, just tcpdump for DHCP traffic and look at the source ports.


ArcGIS JavaScript API Geodatabase

Question: I am looking to use the ArcGIS JavaScript API for my website, but I do not want to buy a overly priced ArcServer license. I have an ArcGIS Desktop license, so can I use the ArcGIS Javascript API with a Geodatabase as my back end? If so How?
Comment: If you're OK with a "Developer Plan" instead of an ArcGIS Server license, you might want to look at https://developers.arcgis.com/plans/
Answer: As far as I know, you can not, sorry. If you want to publish you maps/layers/etc, you need to use ArcServer.
However, if using ArcGIS is not crucial for you, you might want to take a look at other free open source solutions like Mapbox, for example. Depending on what exactly you need to achieve and how much extra coding work you are willing to do, Mapbox may be even better solution for you. From my own experience, it has a nice, easy to follow API with a bunch of examples, which allow you to start developing right away (assuming you have some experience with JavaScript).
Answer: The ArcGIS JavaScript API is used to access and manipulate Services (i.e. data and functionality) published (i.e. made available) via ArcGIS Server. There are many sites that make available ArcGIS Services to the general public and you will be able to access these via the ArcGIS JavaScript API. However, if you want to access your own data, you must publish it somewhere. Esri Online provides some ability to upload small datasets.
Answer: You could publish your data to AGOL if it fits the Public License constraints - 1000 features I believe?
If you're ambitious, you could create your own Geoserver to host your data. You will need a way to get your data from ArcSDE to PostGIS database.
Answer: You can use ArcGis Developer, here you can publish your maps on ArcGis Online
Check this link ArcGis Developer

ArcGIS JavaScript API Geodatabase


How to choice between paired sample and Independent sample

Question: I don't know how to decide to choose between pair and Independent to compare mean of two groups. Here is the excersise from a book:
DS 9.2.1 shows the data obtained from a paired
experiment performed to examine which of two assembly
methods is quicker on average. A random sample of 35
workers on an assembly line were selected and all were
timed while they assembled an item in the standard
manner (method A) and while they assembled an item in
the new manner (method B). The times in seconds are
recorded. Analyze the data set and present your
conclusions on how the new assembly method differs
from the standard assembly method. Why are the two
data samples paired? Why did the experimenter decide to
perform a paired experiment rather than an unpaired
experiment?

First i think it bases on split or not the group. But, in the second problem, they still split, but its still paired sample
A new teaching method for a calculus class is being
evaluated. A set of 80 students is formed into 40 pairs,
where the two-pair members have roughly equal
mathematics test scores. The pairs are then randomly
split, with one member being assigned to section A where
the standard teaching method is used and with one
member being assigned to section B where the new
teaching method is tried. At the end of the course all the
students take the same exam and their scores are shown in
DS 9.2.4. Analyze the data and present your conclusions
regarding how the new teaching method compares with
the standard approach. Why is this a paired experiment?
Why was it decided to perform a paired experiment rather
than an unpaired experiment?

I don't know how to answer two last question. And in fact how to choose between paired and independent. Pls help me make it clearly
Answer: You choose a paired experiment when you have reason to believe that for each pair, the distributions for each sample in the pair are the same under the null hypothesis that the two treatments have the same effect. (Note that the distribution does not have to be the same between different pairs though, e.g. they could have different means). If you cannot use a paired experiment then you do an unpaired experiment, under the hypothesis that the two groups were sampled from the same population distribution under the null hypothesis that the two treatments have the same effect. The paired experiment design gives stronger statistical results when it can be used. In this case, you can use paired experiment design in both cases because the same factory worker uses both procedures in the first case, and the paired students have nearly identical previous scores in the second case.


Finding confidence interval for unimodal function equivalent to and comparable with standard deviation of normal

Question: I'm trying to characterise an arbitrary, unimodal distribution in a way that is a) easily understandable (to a physics audience) and b) comparable with a normal distribution.
My thinking goes like this:
The interval [$\mu-\sigma$, $\mu+\sigma$] contains ~68% of the probability mass of a normal distribution N($\mu, \sigma$), so by quoting $\mu$ and $\sigma$ I can characterise the interval in which typical values lie.
If for an arbitrary, unimodal distribution I (numerically) find interval bounds $\sigma_-$ and $\sigma_+$ such that [$\nu-\sigma_-, \nu$] and [$\nu, \nu+\sigma_+$] each contain ~34% of that distributions probability mass, where $\nu$ is its mode, those values are characteristic and comparable.
In my intuition typical values will fall inside the range in both cases and it will represent the same probability mass. This is notably different from the Half Maximum values of both distributions, which I will call $a_-$ and $a_+$ and define as $p(a_{\pm})=0.5 p(\nu)$. The interval [$a_-, a_+$] might contain more or less of the probability mass, depending on the shape, and is thus not comparable for normals and non-normals.
My question is whether this logic is flawed and if there are any references to support it. The fact that I haven't found any so far makes me think my idea is either wrong or trivial. If it's wrong I'd like to understand why, if it's trivial a reputable quote would put my mind at ease. Since the goal is a numerical implementation in python, any code or links to libraries is also appreciated, but not necessary.
Assumptions made:

My distributions are sufficiently symmetric (un-skewed) that the 34% condition can be fulfilled for $\sigma_-$ and $\sigma_+$.
My distributions have zero or negative excess kurtosis such that the tails do not strongly affect the characteristics.
Comment: Related, Chebyshev's inequality: https://en.m.wikipedia.org/wiki/Chebyshev%27s_inequality
Answer: I believe what you are describing is typically referred to as the highest density interval or HDI. You can calculate the interval in R using the 'HDInterval' package. The documentation does a good job of describing the interval:

The HDI is the interval that contains the required mass such that all points within the interval have a higher probability density than points outside the interval.

However, I think the best explanation is given by the following set of graphs which I have lifted from John K. Kruschke's book, Doing Bayesian Data Analysis. Notice how in the second example, the interval is not symmetric, and how in the third example with bimodal data, it is not even continuous!
The HDI is most often used and discussed in applications related to Bayesian statistics. However, it applies to any probability distribution.
Comment: Awesome, thank you very much! All I was looking for and more!


Optimal way to decide Blackjack play with a soft score

Question: I am designing a Blackjack AI such that it would try to play optimally each hand against the dealer.
When I'm having a hard score the algorithm is easy: as long as my risk of busting is lower than the dealer's risk of busting (based on its visible card) I will hit, otherwise stand.
My problem is when I have a soft score. If both scores are under 21, I will have two probabilities of busting based on each version. I do not know however which score should I keep track of.
For example, if I have a soft 21, even though I have a 0% risk of busting the lower score on my next hit, it is better to stand since 21 is a very good score.
On the other hand, if I have a soft 15, it might be better to hit against a dealer's 2, even though the risk of the higher score going over 21 is larger than the risk of the dealer going bust with a 2 showing.
Could you please tell me if there is another parameter that should be considered regarding the soft scores (preferably easy to calculate)? If so, how should I use it on top of the bust probabilities?
N.B.
The only two actions I am able to do are hitting and standing. I am not using any other actions such as doubling down, splitting or surrendering.
Answer: First of all I don't classify blackjack as an AI project. Second of all you seem to consider the probability of busting only. What about not busting but winning because of greater score?
In the soft(15) case the player always hits because there is no risk of busting but there is some probability of improving his score. Against all dealer up cards.
If you want to get more into this I can instruct you as to how you'd do it.
Also you might find interesting my solution here for the complete stand/hit/double/split case.


Proving inequality for all real $a$ and $b$.

Question: I am trying to prove the following two inequalities
My first intuition was to take the natural log of both sides, then simplify them to get an obvious statement regarding a and b. But I can't reduce the natural log of the right hand-side of the inequality (because of the addition operator).
I'm feeling really stumped and dumb, so a hint would be great!
Answer: for the first one:
dividing by $$e^{a+2b}\ne 0$$ and we get
$$3\le e^{2(a-b)}+\frac{2}{e^{a-b}}$$
substituting $$z=e^{a-b}$$ then we get
$$3\le z^2+\frac{2}{z}$$
can you finish?
and this is equivalent to $$0\le (z+2)(z-2)^2$$ which is true. For your send question:
we get the general case : $$\frac{a^n+b^n}{2}\geq \left(\frac{a+b}{2}\right)^n$$
Comment: let me see, if this will work
Comment: Sonnhard, your last inequality is wrong for $n=\frac{1}{2}.$
Comment: Yeah that makes a lot of sense actually. Thanks! That was really smart
Comment: Then I would assume to take a similar approach of dividing by (a+b)^2018 for the second question
Comment: @Dr.SonnhardGraubner Does in German language sentence always start with small letter?
Comment: no it doesn't, why do you ask me?
Comment: the $n$ must be a natural number
Comment: $n$ can be any real number larger than $1$.  This is just the $s$-power mean.
Comment: thank you very much for your hints
Answer: The first inequality:
By AM-GM
$$\frac{e^{3a}+2e^{3b}}{3}\geq\sqrt[3]{e^{3a}\left(e^{3b}\right)^2}=e^{a+2b}$$
The second inequality it's Jensen for $f(x)=x^{2018}$:
$$\frac{a^{2018}+b^{2018}}{2}\geq\left(\frac{a+b}{2}\right)^{2018}.$$
Comment: Never heard of AM-GM before but wow that's a really useful inequality to have in your back pocket
Answer: If we divide first one with $e^{a+2b}$ we get $$3\leq (e^{a-b})^2+2e^{b-a}$$
Now let $x=e^{a-b}$ so we have to prove $$3\leq x^2+{2\over x}$$
which is true by inequality between arithmetic and geometric mean:
$$ x^2+{1\over x}+{1\over x} \geq 3\cdot \sqrt[3]{x^2{1\over x}{1\over x}}=3$$
Answer:
Use AM-GM on $e^{3a},e^{3b},e^{3b}$ so that $$\frac{e^{3a}+2e^{3b}}{3} \ge e^{a}e^{2b}$$
Use Jensen's inequality on $x\mapsto x^{2018}$, which is a convex function (since it has a positive second derivative except at $x=0$).
\begin{align}
\left(\frac{a+b}{2}\right)^{2018} &\le \frac12 a^{2018}+\frac12 b^{2018} \\
(a+b)^{2018} &\le 2^{2017} a^{2018} + 2^{2017} b^{2018}
\end{align}

Since OP starts by taking log, but none of the existing answers use log, I'll continue OP's work.

Take log on both sides to get

\begin{align}
e^{a+2b} &\le \frac13 e^{3a} + \frac23 e^{3b} \\
\iff a+2b &\le \log \left( \frac13 e^{3a} + \frac23 e^{3b} \right) \\
\iff \frac13 \log e^{3a} + \frac23 \log e^{3b} &\le \log \left( \frac13 e^{3a} + \frac23 e^{3b} \right) \\
\iff \frac13 f(e^{3a}) + \frac23 f(e^{3b}) &\le f \left( \frac13 e^{3a} + \frac23 e^{3b} \right),
\end{align}
which is Jensen's inequality for the concave function $f: x \mapsto \log x$.


Sequence $f_n$ of continuous functions on $[0,1]$, such that $0 \le f_n \le 1$ and $\lim\limits_{n\to\infty}\int_{0}^{1} f_n(x)\,\mathrm dx=0$

Question: Let $f_n$ be a sequence of continuous functions on $[0,1]$, such that $0 \le f_n \le 1$ and $$\lim_{n\to\infty}\int_{0}^{1} f_n(x)\,\mathrm dx=0.$$
a) The sequence ${f_n (x)}$ converges uniformly.
b) The sequence ${f_n (x)}$ converges for some $x$.
c) The sequence ${f_n (x)}$ might not converge for any $x$.
d) The sequence ${f_n (x)}$ converges for every $x$ but not necessarily uniformly.
The answer is c? I have no counter example in my hand.
Comment: for c) $\mathbb{1}_{[k/n,(k+1)/n]}, 0\leq k<n, n=1,2,3,...$ (edit appropriately for continuity)
Comment: For a), take $f_n(x)=x^n$
Comment: @yoyo You will have to make that a triangle to satisfy the continuity restriction.
Comment: @yoyo Is that continuous?
Comment: @Lord_Farin, yeah, and to take $k$ the right way, but it does work. Hence b) and d) are wrong, and we're done.
Answer: Consider the following sequence of sets, constructed as follows. Let $I_1=[0,1]$. Split $[0,1]$ in half, and let $I_2$ and $I_3$ be the first and second halves. Split $[0,1]$ in fourths, and let $I_4,I_5,I_6,I_7$ be the fourths in order. Continue this way, split $[0,1]$ in $2^n$ths and let $I_{2^n},\cdots, I_{2^{n+1}-1}$ be the $2^n$ pieces in order.
Now let $$f_n(x)=\text{ an isosceles triangle over } I_n \text{ of height } 1$$
Then $$\int_0^1 f_n\to 0$$ but if $x\neq m2^{-k}$ then $$\tag 1 \limsup_{n\to\infty} f_n(x)=1 \; ; \;\liminf_{n\to\infty} f_n(x)=0$$
ADD To fix the above, we can do the following: let $\langle g_n\rangle $ be the same as $\langle f_n\rangle $, but with the triangles shifted so that the peaks of the triangles fall on the binary rational points. Thus, $g_1$ will look like (the right) half an isosceles triangle on $[0,1/2]$ plus (the left) half of an isosceles triangle on $[3/4,1]$, $g_2$ will be an isosceles triangle over $[1/2,3/4]$, $g_3$ will be the two halves at $[0,1/4]$,$[7/8,1]$, and so on. Then $\langle g_1,f_1,g_2,f_2,g_3,f_3,\ldots\rangle$ should do: now the rational binary points oscillate between $0$ and $1$.
Comment: Yes, but I was awfully wrong: it does not prove that the function may not converge for any value. Silly me :-)
Comment: @arbautjc I like to imagine the sequence as a series of lights that light up from left to right in a nice way. Seems more entertaining.
Comment: @arbautjc True.
Comment: @Peter: I would add additional triangles in the middle, for example between the triangle $[0,\frac{1}{2}]$ and $[\frac{1}{2},1]$ insert $[\frac{1}{4},\frac{3}{4}]$. (Perhaps there is a better way to do it, I don't know.) Probably with judicious use of triangles you can assure the function may not converge anywhere.
Comment: @sdcvvc Oh, I see. Let me try.
Answer: How about this:
$f_1=1$ everywhere;
$f_2=1$ on the left half of $[0,1]$ and $0$ on the right half; $f_3=1$ on the right half and $0$ on the left;
$f_4$, $f_5$, $f_6$ are respectively equal to $1$ on the left third, the middle third, and the right third and $0$ elsewhere;
$f_7$, $f_8$, $f_9$, $f_{10}$ are equal to $1$ respectively on the first, second, third, and fourth quarters, and $0$ elsewhere;
and so on.
Then $f_n(x)$ diverges for every  $x$ as $n\to\infty$, but $\displaystyle\int_0^1 f_n\to0$.
Comment: @PeterTamaroff that's easy to fix: Just take $f_2$ to be $0$ on $[0,\tfrac12-\epsilon]$ and $1$ on $[\tfrac12,1]$ and join the graph up so it's piecewise linear. You'll still have that $f_n(x) = 1$ frequently for every $x \in [0,1]$ and that $\int_0^1 f_n(x) \,dx \to 0$.
Comment: But that is not **continuous.** That is the example I had in mind at first. When making it continuous with triangles instead of indicator functions, we loose the property that the sequence is nowhere convergent.
Comment: @kahen Awesome. I tried something like that. I ended up with a beautiful mess.


Given domain and range of a monotone function, what is the maximum slope?

Question: I'm looking for a reference in answer to one of the following questions:

Is there a general result out there that will give the maximum possible slope of a monotone function, given its domain and range?
Alternatively, is there a specific proof with regard to the cdf of the normal distribution?

I can prove to myself via simulation that the slope of a given normal cdf peaks at a certain value, but I would like to refer to a proved result. Thanks!
Comment: I do not think there would be a maximum possible slope. Think of a step function... The second part your question seems more attainable.
Comment: You're absolutely right about that. Thanks for pointing it out! The second part is the case I'm dealing with, anyway.
Comment: You might consider taking #2 and asking on [Cross Validated](stats.stackexchange.com).
Comment: @BenCollins - I think it's probably better here. That SE is a little more applied in my opinion, and this is a pretty analytically-oriented mathematics question.
Comment: @Shane that's true.
Answer: Does this work for 2?
CDF of a normal distribution is $\Phi(x)$
The slope at each point is the pdf: $\phi(x)$
Taking the derivative: $\phi'(x) = -x\phi(x)$
Thus, we can see there is a critical point at $x=0$ and the second derivative $-\phi(x) +x^2\phi(x) $ is clearly negative at $x=0$. So the maximum slope of the CDF is  $\phi(0) \approx 0.39$
Edit: I suppose this answer can also be generalized to cases where you're given a range of $x$.
Comment: I think this is what I'm looking for, and probably the best that can be done. Thank you for your answer!


Google API returning the server location, not user location

Question: Hello so I though I was getting user location through this code but im actually getting the server's location, any idea how can I change it so I get the user location?
    public void geolocate() {
            try {

            GeolocationPayloadBuilder payloadBuilder = new GeolocationPayload.GeolocationPayloadBuilder();
            GeolocationPayload payload = payloadBuilder.createGeolocationPayload();
            //GeoApiContext context = new GeoApiContext.Builder().apiKey("my api key").build();
            // I guess the payload needs to be build in a different way but no clue how it should be :/
            GeolocationApiRequest req = (GeolocationApiRequest) GeolocationApi.geolocate(context, payload);

            GeolocationResult res = req.await();
            String location = res.location.toString();
            String[] latLngArray = location.split(",");
            com.google.maps.model.LatLng latLng = new com.google.maps.model.LatLng(Double.parseDouble(latLngArray[0]),
                    Double.parseDouble(latLngArray[1]));
            GeocodingApiRequest geoReq = GeocodingApi.reverseGeocode(context, latLng);
            GeocodingResult[] geoRes = geoReq.await();
            // Setting the user location for view
            System.out.println(geoRes[0].formattedAddress);
            origen.setValue(geoRes[0].formattedAddress);

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
        }

this is the dependency where im getting the objects from:
<dependency>
            <groupId>com.google.maps</groupId>
            <artifactId>google-maps-services</artifactId>
            <version>0.9.3</version>
</dependency>

hope somebody can help me with this, thanks in advance
EDIT:
I have been searching and found out how to build the payload with help of https://developers.google.com/maps/documentation/geolocation/intro#cell_tower_object
But I have a couple of question which is how will I get my users mac address to create the wifiAccessPoint and also where do I find info of cell towers in my city (Cali, Colombia)? Just an update will keep searching any help is appreciated..
@POST
@Path("/geolocate")
public String geolocate() {
    try {
        CellTower newCellTower = new CellTower.CellTowerBuilder().CellId(42).LocationAreaCode(415)
                .MobileCountryCode(310).MobileNetworkCode(410).Age(0).createCellTower();
        WifiAccessPoint newWifiAccessPoint = new WifiAccessPoint.WifiAccessPointBuilder()
                .MacAddress("00:25:9c:cf:1c:ac").createWifiAccessPoint();
        WifiAccessPoint newWifiAccessPoint2 = new WifiAccessPoint.WifiAccessPointBuilder()
                .MacAddress("00:25:9c:cf:1c:ad").createWifiAccessPoint();

        GeolocationPayloadBuilder payloadBuilder = new GeolocationPayload.GeolocationPayloadBuilder()
                .HomeMobileCountryCode(310).HomeMobileNetworkCode(410).RadioType("gsm").Carrier("Vodafone")
                .ConsiderIp(false).AddCellTower(newCellTower).AddWifiAccessPoint(newWifiAccessPoint)
                .AddWifiAccessPoint(newWifiAccessPoint2);
        GeolocationPayload payload = payloadBuilder.createGeolocationPayload();
        GeoApiContext context = new GeoApiContext.Builder().apiKey("my api key")
                .build();

        GeolocationApiRequest req = (GeolocationApiRequest) GeolocationApi.geolocate(context, payload);

        GeolocationResult res = req.await();
        String location = res.location.toString();
        String[] latLngArray = location.split(",");
        com.google.maps.model.LatLng latLng = new com.google.maps.model.LatLng(Double.parseDouble(latLngArray[0]),
                Double.parseDouble(latLngArray[1]));
        GeocodingApiRequest geoReq = GeocodingApi.reverseGeocode(context, latLng);
        GeocodingResult[] geoRes = geoReq.await();
        // Setting the user location for view
        return geoRes[0].formattedAddress;

    } catch (Exception e) {
        System.out.println("Exception in NetClientGet:- " + e);
    }
    return "XD";
}

Answer: The Geolocation API of Google Maps Platform is not intended for getting user location, what I can suggest is that you use the HTML5 Geolocation instead, there's also a sample of that in the Google Maps Platform documentation. But please note that this is not supported by Google as this is using HTML5 Geolocation and not Google APIs, if you wish to get the address of the user location as well, you may Geocode the coordinates that will be returned by the HTML5 Geolocation. You may see the sample below (without the Geocoding function). Here's a working sample - https://jsfiddle.net/w2sad5pn/
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      infoWindow.setPosition(pos);
      infoWindow.setContent('Location found.');
      infoWindow.open(map);
      map.setCenter(pos);
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter());
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
  }
}

Comment: Hmm interesting, I will test this when I have time, thanks man, I tried to use the javascript way but I didn't manage to get the latitude and longitude that it returned to the backend, I used this https://www.w3schools.com/html/html5_geolocation.asp anyways I will try what you posted when I get sometime thanks
Comment: Hey I readed the code and thats exactly what I tried sometime ago, but I didn't manage to get that lat and lon to my backend (java) from the javascript, any idea how can I do that?


Remote Procedure Call (RPC) Performance in a Local Area Network

Question: We use a database that has separate client and server programs and they communicate with each other using RPC.  We have one computer running Windows Server 2003 SP2 and six workstations running Windows 7 Pro 32bit.  The network is a simple 100Mbps network with one network switch.
The server computer and two of the workstations have Gigabyte G31M-ES2L motherboards which have integrated Atheros network controllers.  The other workstations have Gigabyte H61MA-D2V motherboards which have integrated Realtek network controllers.
We are finding that the database performance is very good for the computers with the Atheros NICs but very poor for the computers with the Realtek NICs.
Thinking that the problem was to do with the database program itself, I decided to test the performance of the RPC protocol by using the program RpcPing.exe.
I have been using the following command to time how long it takes to do 1000 RPCs to various computers on the network:
rpcping -u 10 -a connect -s [ip address] -i 1000
My results, on average, are as follows:
Atheros to any Atheros:  200-250ms
Atheros to any Realtek:  800-1000ms
Realtek to any Atheros:  800-1000ms
Realtek to any Realtek:  1100-1200ms
The results are the same, regardless of whether the operating system is Windows Server 2003 or Windows 7.
As a test, I installed Windows XP on one of the boards with a Realtek NIC and found that I would get 200-250ms communicating with any Atheros NIC and 800-1000ms communicating with any Windows 7 computer with a Realtek NIC.  I also tested a basic install of Windows 7, just to make sure no programs were interfering with it, and the results were as bad as usual.
I have tried the latest NIC drivers as well as several earlier versions and have ruled out any physical problem with the network.  I have also tested it on other networks and occasionally find similar results to mine.  Certainly it makes no difference if it's a megabit or gigabit network.
So please can anyone offer an explanation as to why RPC performance is so poor for Windows 7 with these Realtek chipset NICs?
Comment: @HopelessN00b I've been through 3 different BIOS revisions for my motherboard and currently running the latest.  There appear to be no different BIOS versions for the Realtek NIC.  I would accept that Realteks just suck except that it works perfectly in Windows XP.
Comment: @tonyroth Sorry for the confusion, I just meant it's not a bandwidth problem.  If it's connected at 100Mbps or 1Gbps speeds, it makes no difference.  The drivers were from Realtek's site.  Windows update says they're already up to date.
Comment: @BretFisher I've already been through all the settings on the NIC properties advanced tab, of which TCP offloading was one.  The only setting that made any difference was 'Receive-side Scaling'.  When I disabled this, I got about a 5-10% improvement in speed.  The figures I quoted in my original message were with this already disabled.  Sorry I forgot to mention this, I've been through so many things, remembering them all is not easy.
Comment: So is your switch a managed or unmanaged switch, can you see if the realteks are running 100/full?
Comment: Have you tried updating the Realtek NIC/mainboard firmware too?  Might just be that Realtek does a crappy job with RPC calls, though.
Comment: I don't get this statement "Certainly it makes no difference if it's a megabit or gigabit network". So when you say the latest nic drivers where are you getting them from, windows update or realtek?
Comment: Try Disabling TCP Offloading?  BIOS or nic firmware update?
Answer: I sent an email to Realtek over a week ago but never expected a reply.  Surprisingly they've just got back to me.  They asked me to install the Windows XP driver on Windows 7.  This fixed the RPC performance problem but broke internet access.
They then asked me to re-install the Windows 7 driver and try disabling 'Interrupt Moderation' on the advanced settings of the NIC properties page.  This fixed it!
Apparently disabling 'interrupt moderation' increases the performance of your network card at the cost of extra CPU usage.
I presume I must have missed this setting when I went through testing each one in turn or perhaps a certain combination of those settings causes disabling 'interrupt moderation' to have no effect.  Regardless, it's sorted now.
The interesting thing is that the Atheros chipsets have this setting enabled but don't suffer from the RPC performance problem.
Thanks to those who replied.  I appreciate you taking the time to offer suggestions.
Comment: Great Matt, glad you got it fix and documented here for others.  Thanks.


Loop para caixa eletrônico

Question: Eu preciso executar esse código até que usuário solicite para sair.
No caso, ele vai informar o resultado no fim e seguir com uma pergunta para o usuário se ele deseja continuar utilizando, dai o código executa de novo ate que o usuário saia.
namespace Caixa_Eletronico
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Caixa Eletronico");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Digite o valor do saque: ");
            int valor = Convert.ToInt16(Console.ReadLine()); //recebendo o valor digitado pelo usuário.
            int n100 = valor / 100; //contagem das notas de 100R$
            int resto = valor - (n100 * 100); //valor menos as notas de 100.
            int n50 = resto / 50;//contagem das notas de 50R$
            resto = resto - (n50 * 50);
            int n20 = resto / 20;//contagem das notas de 20R$
            resto = resto - (n20 * 20);
            int n10 = resto / 10;//contagem das notas de 10R$
            resto = resto - (n10 * 10);
            int n5 = resto / 5;//contagem das notas de 5R$
            resto = resto - (n5 * 5);
            int n1 = resto / 1;//contagem das notas de 1R$
            resto = resto - (n1 * 1);
            Console.WriteLine();
            Console.WriteLine("Quantidade de notas:");
            Console.WriteLine();
            Console.WriteLine("Notas de 100R$:  " +n100);
            Console.WriteLine();
            Console.WriteLine("Notas de 50R$:  " +n50);
            Console.WriteLine();
            Console.WriteLine("Notas de 20R$:  " +n20);
            Console.WriteLine();
            Console.WriteLine("Notas de 10R$:  " +n10);
            Console.WriteLine();
            Console.WriteLine("Notas de 5R$:  " +n5);
            Console.WriteLine();
            Console.WriteLine("Notas de 1R$:  " +n1);
            Console.ReadKey();
        }
    }
}

Comment: Só colocar um while logo depois do Main...
Answer: Você precisa fazer um laço adicionando uma condição de saída. Optei por deixar a pessoa digitar um número negativo para sair, afinal na forma atual não faria sentido aceitar um número negativo.
Aproveitei e organizei e modernizei o código (padrão de nomenclatura), além de resolver o problema que quebraria a aplicação se a pessoa não digitasse um número válido, através do TryParse().
Com nomes melhores para os identificadores não precisa de comentários.
using static System.Console;

namespace CaixaEletronico {
    public class Program {
        public static void Main(string[] args) {
            WriteLine("Caixa Eletronico\n\n");
            var valor = 0;
            while (valor > -1) {
                Write("Digite o valor do saque (-1 para sair): ");
                if (int.TryParse(ReadLine(), out valor) && valor > -1) {
                    int notas100 = valor / 100;
                    int resto = valor - (notas100 * 100);
                    int notas50 = resto / 50;
                    resto -= notas50 * 50;
                    int notas20 = resto / 20;
                    resto -= notas20 * 20;
                    int notas10 = resto / 10;
                    resto -= notas10 * 10;
                    int notas5 = resto / 5;
                    resto -= notas5 * 5;
                    int notas1 = resto / 1;
                    resto -= notas1 * 1;
                    WriteLine($"\nQuantidade de notas:\nNotas de 100R$:  {notas100}\n");
                    WriteLine($"Notas de 50R$:  {notas50}\n");
                    WriteLine($"Notas de 20R$:  {notas20}\n");
                    WriteLine($"Notas de 10R$:  {notas10}\n");
                    WriteLine($"Notas de 5R$:  {notas5}\n");
                    WriteLine($"Notas de 1R$:  {notas1}\n");
                }
            }
        }
    }
}

Veja funcionando ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Answer: Para ficar repetindo até o usuário sair, use um while, eu já botei para você um sistema de sair simples, a pessoa só digita "sair" e pronto.
using System;

namespace Caixa_Eletronico
{
class Program
{
     static void Main(string[] args)
     {
        bool programa = true;
        while(programa){
        Console.WriteLine("Caixa Eletronico");
        Console.WriteLine("Para sair digite 'sair'");
        Console.WriteLine();
        Console.WriteLine();
        Console.Write("Digite o valor do saque: ");
        var r = Console.ReadLine();
        if (r == "sair")
        {
        Console.WriteLine(">> Deseja Mesmo sair? s/n <<");
        if (Console.ReadLine().ToUpper() != "n")
        {
        Console.Clear();
        continue;
        }
        programa = false;
        continue;
        }
        int valor = 0;
        try
        {
             valor = int.Parse(r);
        }
        catch {
            Console.WriteLine("Digite um número!");
            System.Threading.Thread.Sleep(2000);
            Console.Clear();
            continue;
        }
        int n100 = valor / 100; //contagem das notas de 100R$
        int resto = valor - (n100 * 100); //valor menos as notas de 100.
        int n50 = resto / 50;//contagem das notas de 50R$
        resto = resto - (n50 * 50);
        int n20 = resto / 20;//contagem das notas de 20R$
        resto = resto - (n20 * 20);
        int n10 = resto / 10;//contagem das notas de 10R$
        resto = resto - (n10 * 10);
        int n5 = resto / 5;//contagem das notas de 5R$
        resto = resto - (n5 * 5);
        int n1 = resto / 1;//contagem das notas de 1R$
        resto = resto - (n1 * 1);
        Console.WriteLine();
        Console.WriteLine("Quantidade de notas:");
        Console.WriteLine();
        Console.WriteLine("Notas de 100R$:  " +n100);
        Console.WriteLine();
        Console.WriteLine("Notas de 50R$:  " +n50);
        Console.WriteLine();
        Console.WriteLine("Notas de 20R$:  " +n20);
        Console.WriteLine();
        Console.WriteLine("Notas de 10R$:  " +n10);
        Console.WriteLine();
        Console.WriteLine("Notas de 5R$:  " +n5);
        Console.WriteLine();
        Console.WriteLine("Notas de 1R$:  " +n1);
        Console.ReadKey();
        Console.Clear();
        }
    }
}
}

Loop para caixa eletrônico