How to visually determine whether bell-shaped curves are normal?

Question: Suppose we have the following three curves and we know that one of them is normal. How can we prove that the other two curves cannot be normal? (We don't have to determine which one of the three curves is normal)
Are there any theorems that normal distributions follow that other bell-shaped curves don't? How can one sho, preferably rigorously, that two of the three curves below cannot be normal given that one of the curves is normal?
Comment: In this particular case, all three shapes look normal shaped and they seem to stretch to match each other, so you are just left with the area/total probability test. You do not have a vertical scale, so deciding which may be difficult.  There are other bell shaped curves which would not match and you could demonstrate this graphically or numerically
Comment: As you said, the one with a total probability (i.e. area under the density curve) of $1$ is a probability density curve.  Those with a different area under the curve are not.  Visually the black/solid curve has the greatest area, and then I think the green/dotted curve, followed by the red/dashed curve.  So the areas are different, and at most one can be $1$.
Comment: How do you generate those curves? $\text{//}$ If your "density" doesn't integrate to $1$, it isn't a density, so I do not follow what you mean.
Comment: There isn't anything specific to the normal distribution about the textbook question. The question could have been "explain why at most one of these three curves is a probability density function" and the answer would have been the same.
Comment: @Dave I found these curves in a textbook. I think my idea about the area under the curves not being 1 was incorrect. I'll edit my question.
Comment: What did the textbook say about them that makes you skeptical that they're normal?
Comment: @Dave This was a question in the textbook. It was a multi-part question. The first part was: "What is the total area under any normal curve?" and the second part was: "(b) Consider the three bell-shaped curves shown on the same horizontal axis below. Explain why if one of these curves is normal, the other two curves cannot be normal." I could solve the first part but not the second, so I asked that one here.
Comment: @Henry Could you please expand upon how one can use the "area/total probability test" in this case?
Answer: Here is a path as to how to visually determine whether bell-shaped curves are normal.
Start by drawing equal probability mass cut points on the graph. This produces quantile (cut point) estimates. Per a source, to quote:

In statistics and probability, quantiles are cut points dividing the range of a probability distribution into continuous intervals with equal probabilities, or dividing the observations in a sample in the same way. There is one fewer quantile than the number of groups created.

Next, examine the cut-points and visually (or more rigorously) construct a QQ Plot. Per an educational source:

One way to assess how well a particular theoretical model describes a data distribution is to plot data quantiles against theoretical quantiles...For a large sample from the theoretical distribution the plot should be a straight line through the origin with slope 1...

where the theoretical distribution here is taken to be the Normal distribution.
To obtain a probability that the slope estimate per a Least-Squares fit is indeed here equal to 1, more work can be performed as detailed in this source: Non-Zero Null Tests for Simple Linear Regression.
Optionally, I suggest you actually simulate a Normal and other distributions based on the sample size used to construct the graph, and test for accuracy over repeated runs the suggested methodology.
I hope this answer is of assistance.
Comment: @whuber: Yes, difficult perhaps, but not impossible. For example, draw line segments over the curve, and use geometry to estimate sector areas. Total the area estimates and divide by a select # of proposed cuts. Per the geometry exercise, estimate where such approximate equal area sectors cuts would be located. Tedious, but perhaps a quantitatively rewarding/revealing exercise nevertheless.
Comment: Now, if someone would suggest how large a # of random say normal (or other) deviates to generate, I may find time to run a few simulations, then generate the graphs and perform various linear sector examinations and subsequent quantile estimation. Knowing the true distribution and parameters used to perform the simulation may allow me to assess general accuracy and possible feasibility.  Preferably,  someone else should perform this exercise (credibility). No assertion to have completely developed all the best practices here to necessarily best address this distribution ID exploratory study.
Comment: -1 This answer misses the point of the question, which is elaborated in comments to the question.
Comment: Whuber: Yes, I did want to avoid comment on a fundamental mischaracterization of a potentially interesting problem. In essence, I am assuming the point of the comments are to state that for curves to be truly representative of potential distributions, they all must (obviously) sum to unity. That being finally agreed upon, how could one ever even proceed? To that end, assuming the question is edited, I have presented a workable testable valid methodology. I would be interested if you have any conceivable alternative paths in mind?
Comment: At the very beginning, you ask the viewer to perform a nearly impossible task: namely, to slice the area under the curve into vertical strips having equal areas.  Very few people will be able to do that with any accuracy. At that point we have gone so far astray from the essential point of the question that it's not suitable to discuss any further steps.


Angular service with providedIn: 'root' is an empty object

Question: I just created a brand new service inside an angular application and use providedIn: 'root' to make it available anywhere in the application.
But when I import it and try to use it says its methods are undefined.
Here is the code
service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class Service {
  public publicMethod() {}
}

component.ts
import { Service } from 'path/to/service';
import { Component } from '@angular/core';
import { AccountService } from 'app/core';
@Component({
    selector: 'footer',
    templateUrl: './footer.component.html',
})
export class FooterComponent {
  constructor(private readonly service: Service) {
     this.service.publicMethod // undefined
  }
}

Other services imported the same way are working fine.
What can cause this issue?
Comment: The code you've given works fine: https://stackblitz.com/edit/angular-ivy-skq1o2?file=src/app/app.component.ts. Maybe you need to add more details to reproduce your problem.
Comment: @ChrisHamilton you are right, an imported module to that service caused the issue, it was not provided anywhere. Added providedIn: root to there was solved the issue.
Answer: Try to add your service you want to inject in providers : [ ] in your core.module
and in your AccountService replace @Injectable({ providedIn: 'root' }) with @Injectable()
Answer: @ChrisHamilton you are right, an imported module to that service caused the issue, it was not provided anywhere. Added providedIn: root to there was solved the issue.


Exercise II 3.22 Hartshrone: would like a clarification of the statement

Question: In Exercise II 3.22 Hartshorne says let $f:X \to Y$ be a dominant morphism of integral schemes of finite type over a field.
Let $k$ be a field.
I just wanted to verify that this actually means (1) $f$ is dominant (2) $X$ and $Y$ are integral schemes of finite type over $k$?
I was getting slightly confused with the wording, and I just wanted to make sure I had the right meaning. I think it's unlikely but I thought maybe $X$ is an integral schemes of finite type over $k_1$ and $Y$ is an integral scheme of finite type over $k_2$, where $k_1$ and $k_2$ are different fields?. Or possibly that this means $f: X \to Y$ is a morphism of integral schemes and this $f$ is of finite type..
Any clarification would be appreciated. Thank you.
Comment: "of finite type" is a property of $f$. See the definitions that precede example 3.2.1. And yes, $X$ and $Y$ are integral schemes over the same field $k$.
Comment: @AymanHourieh Thank you for your comment. Are you saying the same thing as in the answer by EricWolfsey, or do you mean that $f: X \to Y$ is a morphism of finite type?
Answer: Your interpretation is almost correct: $X$ and $Y$ are each integral schemes of finite type over $k$, and $f:X\to Y$ is a dominant morphism of schemes over $k$ (so, it forms a commutative diagram with the morphisms to $\operatorname{Spec} k$).  In general, when one speaks of a "morphism of [...] schemes over $T$", then that means a morphism in the category of schemes over $T$ rather than just the category of schemes.
Comment: This makes more sense, thank you!
Comment: One could also add that a morphism $f: X \to Y$ where $X, Y$ are of finite type over $k$, is also a morphism of finite type.


Find the limit of $\lim_{n\to\infty}((n^3+n^2)^{1/3}-(n^3+1)^{1/3})$ without using the identity $a^3-b^3=(a-b)(a^2+ab+b^2)$

Question: Find the limit of the sequence $$\lim_{n\to\infty}((n^3+n^2)^{1/3}-(n^3+1)^{1/3})$$
I showed that the limit is $1/3$, using the identity $$a^3-b^3=(a-b)(a^2+ab+b^2)$$
we get the sequence is equal to
$$\frac{n^3+n^2-n^3-1}{(n^3+n^2)^{2/3}+(n^6+n^5+n^3+n^2)^{1/3}+(n^3+1)^{2/3}}\longrightarrow\frac{1}{3}$$
but I couldn't manage to solve it without using the above identity, and I was wondering if it is possible.
Comment: That's a sequence, not a series.
Comment: Oops, corrected it.
Answer: $$
\begin{align}
\lim_{n\to\infty}((n^3+n^2)^{1/3}-(n^3+1)^{1/3})
&=\lim_{n\to\infty}n\left(\left(1+\frac1n\right)^{1/3}-\left(1+\frac1{n^3}\right)^{1/3}\right)\\
&=\lim_{n\to\infty}n\left(\left[1+\frac1{3n}+O\!\left(\frac1{n^2}\right)\right]-\left[1+O\!\left(\frac1{n^3}\right)\right]\right)\\
&=\lim_{n\to\infty}\left(\frac13+O\!\left(\frac1n\right)\right)\\
&=\frac13
\end{align}
$$
Answer: My favorite way is to consider
$$
f(x)=\left(\frac{1}{x^3}+\frac{1}{x^2}\right)^{1/3}-\left(\frac{1}{x^3}+1\right)^{1/3}
=\frac{\sqrt[3]{1+x}-\sqrt[3]{1+x^3}}{x}
$$
so that your sequence is $f(1/n)$ and so you can compute
$$
\lim_{x\to0^+}f(x)=\lim_{x\to0}\frac{(1+x/3+o(x)-(1+x^3/3+o(x^3))}{x}=\frac{1}{3}
$$
Without Taylor expansion, the sought limit is the derivative at $0$ of $g(x)=\sqrt[3]{1+x}-\sqrt[3]{1+x^3}$, so
$$
g'(x)=\frac{1}{3\sqrt[3]{(1+x)^2}}-\frac{3x^2}{3\sqrt[3]{(1+x^3)^2}}
$$
and $g'(0)=1/3$.
Answer: 1) $n(1+1/n )^{1/3} = $
$\dfrac{(1+1/n)^{1/3}}{1/n}.$
2) $n(1+1/n^3 )^{1/3} =$
$\dfrac{(1+1/n^3)^{1/3}}{1/n}.$
$\small{\dfrac{((1+1/n)^{1/3} -1) -((1+1/n^3)^{1/3}-1)}{1/n}}$
$\small{=\dfrac{(1+1/n)^{1/3} -1}{1/n} - (1/n^2)\dfrac{(1+1/n^3)^{1/3} -1}{1/n^3}.}$
First term:
Let $f(x)=x^{1/3}$:
$\lim_{n \rightarrow \infty}\dfrac{(1+1/n)^{1/3} -1}{1/n}=$
$f'(x)_{x=1}= (1/3);$
Second term:
$\small{-\lim_{n \rightarrow \infty}(1/n^2)\dfrac{(1+1/n^3)^{1/3}-1}{1/n^3}= }$
$\small{\lim_{n \rightarrow \infty}(1/n^2)×}$
$\small{\lim_{n \rightarrow \infty}\dfrac{(1+1/n^3)^{1/3}-1}{1/n^3}=}$
$\small{0 \cdot (1/3)=0.}$


Javascript: using eval() to load functions dynamically

Question: I want to load more than one function dynamically:
var str = "function foo() {} function bar() {}";
var functions = eval(???);
functions.foo();

Can this be done with eval? I was only successful with a single function.
Comment: What is the use case where you want to use that? Using `eval` for this task is most likely wrong.
Answer: With eval. Not recommended.

var str = "function foo() { console.log('foo'); } function bar() { console.log('bar'); }";
eval(str);
foo();

You could use an object and put the functions inside. You can later add a function with assignment.

var functions = {
        foo: function () { console.log('foo'); },
        bar: function () { console.log('bar'); }
    };

functions.foo();

functions.baz = function () { console.log('baz'); }

functions.baz();
Comment: eval(str) - that easy :D Thx. In the environment where I use it, the evil things of eval do not matter.
Comment: then you can use a mixture of both proposals.
Answer: With functions.foo(); you try to access the property foo of the object functions and this will give you an undefined.
Solution
You could replace you string of functions simply with an object like
var functions = {
   foo: function() {},
   bar: function() {}
}

This avoids also the usege of eval().
Now you can access each property with functions.<functionName>;. You can add propertys dynamicly at runtime in JavaScript. So there is no usecase for eval in your problem
Example

var functions = {
   foo: function() { console.log('foo') },
   bar: function() { console.log('bar') }
}

function addNewFunction(object, functionName, functionImplementation) {
  object[functionName] = functionImplementation
}

addNewFunction(functions, 'ok', function() { console.log('ok') })

functions.foo()
functions.ok()
Answer: eval will execute certain string but it will not return anything. So functions will be undefined
eval will also run the given string in current scope. So the parsed functions will not necessarily be created in global scope.
Sample:

var str = "function foo1() {console.log('foo1')} function bar1() {console.log('bar1')}";
var functions = eval(str);
console.log(functions);
foo1();

(function() {
  var str = "function foo2() {console.log('foo2')} function bar2() {console.log('bar2')}";
  var functions = eval(str);
  foo2();
})()
try {
  foo2();
} catch (ex) {
  console.log(ex.message)
}

My suggestion, create a new JS file and load it dynamically.
Reference Links:

Why is using the JavaScript eval function a bad idea?
Eval is evil
Dynamically load a JavaScript file
Answer: var foo = '( function foo() {} )'
var bar = '( function bar() {} )'
declare function with variable, then use the eval
var result = eval(foo)
result variable get the result of the foo() function


Editar ações de botões do modal de forma programatica

Question: Estou criando um botão de forma programatica que assim que clicado, ira chamar um modal, porém, gostaria que assim que apertassem o botão de dentro do modal, a pagina reiniciasse e fechasse esse modal. Como eu faço a implementação?
sempre que eu coloco um .onClick = 'window.location.reload' com o id do botão do modal para reinciar a pagina assim que apertar no botão do MODAL, essa açaõ é acionada antes mesmo de chegar nessa parte, pois esta como ação do botão que aciona o modal, e não como ação do botão do modal em si.
--------------------------------------------------------- COMEÇO HTML ----------------------------------------------------------------------------------------

Erro na gravação

        <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
          ×
        </button>

        <button type="button" id="modal_botao" data-dismiss="modal"> Voltar e corrigir </button>

------------------------------------------------------- FIM HTML --------------------------------------------------------------------------------------------------
let btn = document.createElement('button')
        btn.className = 'btn btn-danger' // Colocando uma classe na tag
        btn.innerHTML = '' // Colocando um elemento dentro da tag
        btn.id = 'id_despesa'+d.id // Pegando o id criado dentro do objeto despesa
        btn.onclick = function() {
            let id = this.id.replace('id_despesa','') // Retirando o id_despesa
            bd.remover(id)

        // Editando o modal que sera exibido
        document.getElementById('modal_titulo').innerHTML= 'Erro!'
        document.getElementById('modal_titulo_div').className = 'modal-header text-danger'
        document.getElementById('modal_conteudo').innerHTML = 'Erro na gravação. Verifique se todos os campos foram preenchidos.'
        document.getElementById('modal_botao').innerHTML = 'V'

        // A grande duvida logo aqui
        document.getElementById('modal_botao').onclick = window.location.reload() // O onclick esta referenciando o botão que chama o modal, não o botão do proprio modal

        document.getElementById('modal_botao').className = 'btn btn-danger'
        $('#registraDespesa').modal('show')
        }

Answer: Sempre que o nome de uma função for usada seguida de (), ela estará sendo invocada, executando aquilo que está definido em seu corpo. Neste caso você não está compartilhando o comportamento da função nativa location.reload, mas invocando-a sempre que o seu código é executado no navegador. Atribua uma função à propriedade onclick desta forma:
document.getElementById('modal_botao').onclick = function() { window.location.reload() }


Is there a simple pattern to memorize the sine of $0^\circ$, $15^\circ$, $30^\circ$, $45^\circ$, $60^\circ$, $75^\circ$, $90^\circ$?

Question: We know there is a nice pattern to memorize the sine of $0^\circ$, $30^\circ$, $45^\circ$, $60^\circ$,  $90^\circ$ as follows.
\begin{align}
\sin 0^\circ &= \tfrac12\sqrt0\\
\sin 30^\circ &= \tfrac12\sqrt1\\
\sin 45^\circ &= \tfrac12\sqrt2\\
\sin 60^\circ &= \tfrac12\sqrt3\\
\sin 90^\circ &= \tfrac12\sqrt4
\end{align}
We also know that
\begin{align}
\sin 15^\circ &= \tfrac14(\sqrt6-\sqrt2)\\
\sin 75^\circ &= \tfrac14(\sqrt6+\sqrt2)
\end{align}
Question
If I want to combine these two groups, is there a simple nice pattern available for us to easily rote memorize them?
Comment: (+1) for this nice pattern, I was not aware of.
Comment: In [this answer](https://math.stackexchange.com/a/1541219/409), I give a unified form for sines of multiples of $3^\circ$. No particularly "nice" patterns, though.
Comment: @Blue: great info, entirely covers my small answer.
Comment: The sines below apparently do not fit in the pattern above.
Comment: One way: https://www.youtube.com/watch?v=hTGhCGrPLmw - Not sure if it helps.
Comment: I am not entirely sure what you want, but it shows a way of how the values were derived...:)
Comment: The "Nice" pattern you start with is itself less nice than it first appears. Because the gaps between the angles are $30^\circ, 15^\circ, 15^\circ, 30^\circ$, what first seems like a nice pattern suddenly is revealed to be more of a "pick out the values we like" pattern (though one with some symmetry).
Answer: Hmm, this pattern works:
$$
\sin 0^{\circ} = \frac{1}{2}\sqrt{2-\sqrt{4}}, \\
\sin 15^{\circ} = \frac{1}{2}\sqrt{2-\sqrt{3}}, \\
\color{gray}{\sin 22.5^{\circ} = \frac{1}{2}\sqrt{2-\sqrt{2}},} \\
\sin 30^{\circ} = \frac{1}{2}\sqrt{2-\sqrt{1}}, \\
\sin 45^{\circ} = \frac{1}{2}\sqrt{2\pm\sqrt{0}}, \\
\sin 60^{\circ} = \frac{1}{2}\sqrt{2+\sqrt{1}}, \\
\color{gray}{\sin 67.5^{\circ} = \frac{1}{2}\sqrt{2+\sqrt{2}},} \\
\sin 75^{\circ} = \frac{1}{2}\sqrt{2+\sqrt{3}}, \\
\sin 90^{\circ} = \frac{1}{2}\sqrt{2+\sqrt{4}}.
$$
Comment: Brilliant! That's why Maths are beautiful
Comment: "... of which fact you have discovered a truly marvelous sequence.  The narrowness of this margin doesn't permit [you to include the steps]."
Answer: This answer is inspired from Oleg567's answer. (I should say, I will explain why does this beautiful sequence appears.)
Firstly we know that: (It should be the really amazing and beautiful sequence)
$$\cos 0^\circ=\dfrac{\sqrt{4}}{2}\quad\cos 30^\circ=\dfrac{\sqrt{3}}{2}\quad\cos 45^\circ=\dfrac{\sqrt{2}}{2}\\\cos 60^\circ=\dfrac{\sqrt{1}}{2}\quad\cos 90^\circ=\dfrac{\sqrt{0}}{2}\quad\cos 120^\circ=-\dfrac{\sqrt{1}}{2}\\\cos 135^\circ=-\dfrac{\sqrt{2}}{2}\quad\cos 150^\circ=-\dfrac{\sqrt{3}}{2}\quad\cos 180^\circ=-\dfrac{\sqrt{4}}{2}\\$$
Then, we'll use the half-angle formula $\sin^2 \dfrac{\theta}{2} = \dfrac{1-\cos\theta}{2}$
$\because 0^\circ \le\theta\le 180^\circ \rightarrow 0^\circ \le\dfrac{\theta}{2}\le 90^\circ \\ \therefore \sin \dfrac{\theta}{2} = \sqrt{\dfrac{1-\cos\theta}{2}}\ge 0 \\ \text{The }\cos\theta\text{ we want are all in the form }\pm\dfrac{\sqrt{n}}{2}\text{ where }n=0,1,2,3,4 \\ \quad\sin \dfrac{\theta}{2}\\=\sqrt{\dfrac{1\mp\frac{\sqrt{n}}{2}}{2}}\\=\sqrt{\dfrac{2\mp\sqrt{n}}{4}}\\=\dfrac{1}{2}\sqrt{2\mp\sqrt{n}}$
Therefore, we get the the result below:
$$\sin 0^\circ=\sin \dfrac{1}{2}\left(0^\circ\right)=\dfrac{1}{2}\sqrt{2-\sqrt{4}}\quad\sin 15^\circ=\sin \dfrac{1}{2}\left(30^\circ\right)=\dfrac{1}{2}\sqrt{2-\sqrt{3}}\\\sin 22.5^\circ=\sin \dfrac{1}{2}\left(45^\circ\right)=\dfrac{1}{2}\sqrt{2-\sqrt{2}}\quad\sin 30^\circ=\sin \dfrac{1}{2}\left(60^\circ\right)=\dfrac{1}{2}\sqrt{2-\sqrt{1}}\\\sin 45^\circ=\sin \dfrac{1}{2}\left(90^\circ\right)=\dfrac{1}{2}\sqrt{2\mp\sqrt{0}}\quad\sin 60^\circ=\sin \dfrac{1}{2}\left(120^\circ\right)=\dfrac{1}{2}\sqrt{2+\sqrt{1}}\\\sin 67.5^\circ=\sin \dfrac{1}{2}\left(135^\circ\right)=\dfrac{1}{2}\sqrt{2+\sqrt{2}}\quad\sin 75^\circ=\sin \dfrac{1}{2}\left(150^\circ\right)=\dfrac{1}{2}\sqrt{2+\sqrt{3}}\\\sin 90^\circ=\sin \dfrac{1}{2}\left(180^\circ\right)=\dfrac{1}{2}\sqrt{2+\sqrt{4}}$$


Android Searchview filtering wrong on item click with ListView

Question: I have tried other solutions. But the problem is different for me.
I have implemented a SearchView with ListView in my app. When I search for something the first item of the array is opened on item click. But I need to open the same item which is listed on the search. The search result is filtering well, but onClick item is giving different item.
Please note that my question is different and not a duplicate.
My code is below:

public class Searchpage extends AppCompatActivity {
    SearchView searchView;
    ListView listView;
    ArrayAdapter<String> adapter;

    String[] name = {
           "General Science", "Social Science", "Maths", "English", "Politics", "IT"
  };
    String[] file= {
           "science.pdf", "social.pdf", "maths.pdf", "english.pdf", "politics.pdf", it.pdf"
    };
    int[] pagenum = {
            0,0,0,0,0,0
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchpage);
        searchView = findViewById(R.id.srch);
        listView = findViewById(R.id.searchlist);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
        listView.setAdapter(adapter);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                adapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent ij = new Intent(getApplicationContext(), PdfView.class);
                ij.putExtra("furl", "fl/" + pagenum[position]);
                ij.putExtra("pagenm", pagenum[position]);
                startActivity(ij);
            }
        });
    }

}

Comment: Is it your custom filter?
Comment: No! Everything is included in the same class ```Searchpage ```
Comment: Why you pass `pagenum[position]` for **furl**? Is it correct or wrong?
Answer: First of all use ArrayList instead of array to initialize ArrayAdapter
ArrayList<String> name = new ArrayList<>(Arrays.asList(
        "General Science", "Social Science", "Maths", "English", "Politics", "IT"
));

Then use below code to find out correct position of your filtered data
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    int actualPosition = name.indexOf(adapter.getItem(position));

    Intent ij = new Intent(getApplicationContext(), PdfView.class);
    ij.putExtra("furl", "fl/" + file[actualPosition]);
    ij.putExtra("pagenm", pagenum[actualPosition]);
    startActivity(ij);
}

Comment: This page number is given for opening the particular pages of each PDF. And the problem is occurring only while search filtering. It is OK when the item is opened without searching.


Prove $\sum_{n=1}^{\infty}|a_{n}b_{n}|$ converges if $\sum_{n=1}^{\infty}a_{n}^{2}$ and $\sum_{n=1}^{\infty}b_{n}^{2}$ converge

Question: This is a homework problem for an undergrad topology course.
Let $l^{2}$ be the set of all real-valued sequences $(c_{n})$ where $\sum_{n=1}^{\infty}c_{n}^{2}$ converges. Let $(a_{n}),(b_{n})\in l^{2}$.
Claim: $\sum_{n=1}^{\infty}|a_{n}b_{n}|$ converges.
I've done a couple of examples where $a_{n}$ and $b_{n}$ are general harmonic series. I've also written out the definition of convergence for $a_{n}$ and $b_{n}
$. My problem is that thus far I do not understand on any level why my claim is true.
Comment: Use the Cauchy-Schwarz inequality.
Comment: To understand why, consider the partial sums of the series you're trying to study.
Answer: No need to use
Cauchy Bunyakovsky Schwarz here.
We have $(a_n+b_n)^2 = a_n^2+ b_n^2 + 2 a_nb_n\ge0 $, hence $a_n^2+ b_n^2 \ge - 2 a_nb_n$.
We have $(a_n-b_n)^2 = a_n^2+ b_n^2 - 2 a_nb_n\ge0 $, hence $a_n^2+ b_n^2 \ge  2 a_nb_n$.
Hence $a_n^2+ b_n^2 \ge  2 |a_nb_n|$.
Then $2 \sum_{k=0}^N |a_nb_n| \le \sum_{k=1}^\infty ( a_n^2+b_n^2) $ for all $N$ and the result follows.
Comment: @Quickbeam2k1 The first and second inequality together make the third, there is no getting around that...
Comment: I just wrote the same but somehow my browser crashed. In addition you answer could be simplified using $|ab|=|a||b|$, then your first inequality is not used. By the way, in Evan's book on pde the inequality is also referred to as Cauchy's inequality
Comment: @Quickbeam2k1: That simplification works for $\mathbb{C}$ as well.
Comment: @5xum, i don't get your comment. There always holds $a_n^2+b_n^2 = |a_n|^2+|b_n|^2\geq 2|a_n||b_n|$ by means of the second inequality. Essentially, one only uses the second inequality for non negative numbers
Answer: By the Cauchy Schwarz inequality, $$\left(\sum_{n}a_n^2\right)^{1/2}\left(\sum_{n}b_n^2\right)^{1/2}\ge \left(\sum_{n}|a_nb_n|\right)$$
So we are done.
Answer: As mentioned before, by the Cauchy-Schwarz inequality $$\sum_{n=1}^\infty |a_nb_n| \leq \sqrt{\big(\sum_{n=1}^\infty a_n^2\big)} \sqrt{\big(\sum_{n=1}^\infty b_n^2\big)}$$
and you know the series inside the roots converge to real numbers by assumption. However, you may have to prove this statement. A hint for that would be to square both sides of this inequality, and then show the result by induction.


Como converter animação em Canvas/JS para SVG?

Question: Tenho usado uma biblioteca de JavaScript para fazer icones/simbolos de uma app de metereologia. Queria agora fazer em SVG o simbolo da nuvem (céu nublado), e questiono-me sobre qual a melhor abordagem.
Fiz um svg com a linha da nuvem, estática (jsFiddle), e uma rotação básica  que não é o efeito pretendido uma vez que a nuvem original (na animação com o canvas/js) tem 5 arcos que expandem e contraem à medida que rotacionam.
Possiveis abordagens que pensei:

fazer 5 circulos, usando "dash" para ter só arcos, e depois tentar animar esse valor e fazer tudo rodar à volta de um eixo
fazer 5 path, e depois tentar animar esse valor e fazer tudo rodar à volta de um eixo

Haverá uma maneira melhor (e que funcione em browsers modernos), de maneira a recriar a animação mas com SVG?
O exemplo de js, como no jsFiddle em cima:

var skycons = new Skycons({
    "color": "black"
});
var canvas = document.querySelectorAll('canvas');
[].forEach.call(canvas, function (el) {
    skycons.add(el, el.dataset.icon);
});

skycons.play();

        <canvas id="fe_current_icon" data-icon="cloudy" width="160" height="160" style="width:120px; height:120px"></canvas>

Comment: Sim a dificuldade está em manter as animações, eu até coagitei formas de ficar pegando pixel a pixel do canvas em um loop continuo mais mesmo otimizando não ficou nada performático.
Comment: @FelipeAssunção se concordares deixa a recompensa aberta até ao fim do tempo para outros terem possibilidade de contribuir com respostas também.
Comment: Sim, a resposta atual apesar de bem completa não é muito objetiva, achei ela muito teórica e eu procuro uma resposta mais técnica. Entendo que somos focados em coding e criar os svgs com o uso de um programa  basicamente foge ao escopo Javascript, eu procuro uma abordagem similar a esta: http://willianjusten.com.br/manipulando-svg-com-js/ focada na criação e manipulação por javascript
Comment: Vou ser mais especifico, considerando o uso de javascript como o principal ferramenta, a library que o Sergio utilizou https://rawgit.com/darkskyapp/skycons/master/skycons.js possui exatos 10 modelos de weather icons sendo totalmente feita em javascript, eu procuro uma abordagem que me permita fazer algo similar. O Sergio assim é um programador experiente basta ver as contribuições que ele fez aqui na comunidade portanto presumo que mesmo consultou o básico sobre SVG antes de perguntar aqui.
Comment: Uma abordagem adequada seria explicar da seguinte forma: - Como criar os shapes com uso de coding(como funciona, como fazer uma curva e etc..) - Como manipular os elementos também com o uso de javascript, Como modificar os elementos em tempo de execução da forma mais performática, para permitir que ele crie uma solução viável e coerente, pois se o mesmo tiver que usar mil softwares externos pra fazer oque ele já encontrou pronto em canvas certamente não vai valerá a pena substituir.
Comment: @Felipe, obrigado pela ajuda a trazer atênção à pergunta! Posso juntar que entretanto fiz um melhoramento que deixei [num comentário lá na biblioteca](https://github.com/darkskyapp/skycons/issues/11#issuecomment-160906351). Ficou melhor, mas a dúvida que gerou a pergunta ainda existe, ou seja: qual a maneira correta de fazer isto em svg.
Comment: Sobre o transform do svg e utilidades css para o svg, seria uma opção?
Comment: @FelipeAssunção Qual o tipo de animação que você pretende fazer? Quais são os recursos que você necessita na animação?
Comment: A última vez que eu brinquei com canvas e svg, eu acabei usando uma biblioteca chamada Fabric.js, ela possui suporte a animação. Já viu os exemplos?
Comment: Basta olhar no corpo da pergunta que ele já conhece o introdutório inclusive chegou a uma solução mínima
Answer: Atualização: Animação com Javascript
Para uma abordagem mais simples, consulte Animação (abaixo)
A animação de objetos em um documento SVG com Javascript pode ser feitas de
várias formas, como:

alterando as propriedades do DOM (parecida com Animação, abaixo)
modificando as transformações dos vetores (ex: através das
propriedades transform ou matrix)
animação direta de propriedades internas (ex: alterar os vetores que formam o path)

O acesso a atributos do objeto pode ser feito diretamente, porém, para
acessar elementos do SVG, deve-se utilizar um namespace:
const svgNS = 'http://www.w3.org/2000/svg';

// Referência ao objeto SVG (sem o namespace)
svgRef = document.getElementById('svgImg01');

// Cria um caminho (usa namespace)
pathRef = document.createElementNS(svgNS, "path");

// Atributos são acessados sem o namespace
pathRef.setAttribute('id','cam');
pathRef.setAttribute('style', "fill:#000000");
pathRef.setAttribute('d', 'M0 0 Z');

// Adiciona o caminho criado ao documento SVG
svgRef.appendChild(pathRef);

Looping da Animação
A forma mais simples para atualizar os objetos durante a animação, é utilizar as
 funções setInterval ou setTimeout.
A desvantagem, é que essas funções não tem muita precisão (de tempo) para atualizar a animação e podem ocorrer falhas ("pulos") durante a execução.
Um exemplo de como criar a estrutura básica do looping de animação com setInterval:
var handleInterval = -1;

function renderizar()
{
    // Código da animação
}

// inicia o timer
function iniciaAnimacao()
{
    handleInterval = setInterval('renderizar();', 300);
}

// para o timer
function pausaAnimacao()
{
    clearInterval(handleInterval);
    handleInterval = -1;
}

Uma outra forma (com precisão e desempenho melhores) para atualizar a animação é
utilizar um looping auxiliar e a função requestAnimationFrame:
var handleFrame = -1;

// tempo que o último frame foi renderizado
var ultimoFrame = 0;

// tempo até a renderização do próximo frame
const numFrames = 30.0;

// Looping auxiliar
function loopingAnimacaoFrameComTempo(tempo)
{
    if ((tempo - ultimoFrame) > numFrames) {
        renderizar();
        ultimoFrame = tempo;
    };
    handleFrame = requestAnimationFrame(loopingAnimacaoFrameComTempo);
    return;
}

// inicia o looping
function iniciaAnimacao()
{
    ultimoFrame = performance.now() - numFrames + 1;
    handleFrame = requestAnimationFrame(loopingAnimacaoFrameComTempo);
}

// interrompe o looping
function pausaAnimacao()
{
    cancelAnimationFrame(handleFrame);
    hanldeFrame = -1;
}

Como a função requestAnimationFrame aguarda a próxima operação de repaint do
dispositivo, é possível obter velocidades maiores e, ao mesmo tempo, manter uma
atualização "suave" dos frames.
A constante numFrames controla a velocidade da animação. Quanto menor o valor,
mais rápida será a animação.

Objetos
Neste exemplo, a animação deforma (aleatóriamente) os vetores de um polígono.
Criar ou alterar as propriedades de outros objetos (ex: círculos, retângulos), além do path, segue a mesma lógica e pode ser utilizada para qualquer tipo de animação (gráficos comerciais, banners, histogramas, jogos, etc.).
Os vetores são criados pela função abaixo e retornam em uma string, que será atribuída a
propriedade d do caminho criado:
function cria_path_inicial(x, y, r, tess)
{
    var ponto_x = Math.cos(0.0)*r + x;
    var ponto_y = Math.sin(0.0)*r + y;
    var ret = 'M' + ponto_x + ' ' + ponto_y + ' ';

    for (var angulo=0.0; angulo<2.0*Math.PI; angulo+=tess) {
        ponto_x = Math.cos(angulo)*r + x;
        ponto_y = Math.sin(angulo)*r + y;
        ret += 'L' + ponto_x + ' ' + ponto_y + ' ';
    }
    return ret + 'Z';
}

e a função que deforma o polígono dentro de um cage:
// Pontos importantes nos comentários

function renderizar()
{
    var i = 0;
    var px = 0.0;
    var py = 0.0;

    // Obtém a lista de vetores do caminho
    var segmentos = pathRef.pathSegList;

    // Percorre a lista
    for (i=1; i<segmentos.numberOfItems; i++) {

        // Obtém uma referência ao vértice 'i' e as coordenadas do vértice
        var vertice = segmentos.getItem(i);
        px = vertice.x;
        py = vertice.y;

        dx = Math.random()*2;
        dy = Math.random()*2;
        if (Math.random() < 0.5) {
            px += (px+dx < 400) ? dx : -dx;
            py += (py+dy < 400) ? dy : -dy;
        } else {
            px -= (px-dx > 0) ? dx : -dx;
            py -= (py-dy > 0) ? dy : -dy;
        }

        // Atualiza os vértices
        vertice.x = px;
        vertice.y = py;
    }
    return;
}

A complexidade na implementação depende, principalmente: do objetivo da animação,
os algoritmos que serão utilizados, a quantidade de objetos, sincronização dos movimentos, etc.
O formato SVG pertime a declaração de código Javascript dentro do documento, portanto,
 também há possibilidade usar essa área para codificar a animação.
O resultado abaixo foi implementado com controles para iniciar e pausar a animação, resetar o polígono
e alternar o looping entre setInterval e requestAnimationFrame:

Observação: O exemplo no jsfiddle foi testado com os navegadores FireFox 43.0.4 64bit, Opera 31.0, Safari 9.0.3 e Internet Explorer 11, porém, não funciona no Google Chrome.

Veja rodando no jsfiddle

Animação
Animar o objeto SVG consistem em alterar as suas propriedades em função de um intervalo de tempo.
É possível alterar essas propriedades (sem uso de Javascript), por exemplo, utilizando:

SMIL - Wikipedia
CSS

Através do CSS, é possível criar uma animação alterando uma ou mais propriedades em um intervalo de tempo utilizando, por exemplo, os comandos:

@keyframes para definir como e quais propriedades serão alteradas.
animation para definir, por exemplo, o tempo da animação ou quantas vezes ela será executada

Ao analisar a imagem no link da pergunta, a primeira estratégia utilizada para copiar a animação, foi combinar uma operação de escala com rotação, conforme o código abaixo:
#container {
  position: relative;
  float: left;
  width: 90mm;
  height: 90mm;
  left:20px;
  top:100px;
  background: rgb(240, 240, 255);
}

@keyframes animacao-escala-rotaciona {
  0%   { width:45mm; height: 45mm; top: 50%; left: 50%; }
  50%  { width:55mm; height: 55mm; top: 45%; left: 45%; }
  100% { width:45mm; height: 45mm; top: 50%; left: 50%; transform: rotate(360deg); }
}

#svg2 {
  position:absolute;
  top: 50%;
  left: 50%;
  width: 45mm;
  height: 45mm;
  margin: -23mm 0 0 -23mm;
  animation:
    animacao-escala-rotaciona 4s infinite running linear;
}

No comando keyframes, os passos (steps) da animação são definidos em porcentagens do tempo total da animação.
Dentro do bloco de código após cada porcentagem, estão as propriedades que serão alteradas em cada passo.
No objeto svg2, o atributo animation define o tempo da animação, a quantidade de repetições (infinite)
o status (parada ou rodando) e o tipo de interpolação de tempo.

Veja rodando no jsfiddle

Uma outra possibilidade é combinar as duas transformações diretamente no atributo transform, com o código:
@keyframes animacao-escala {
  0%   { transform: scale(1.0) rotate(0deg); }
  50%  { transform: scale(1.8) rotate(180deg); }
  100% { transform: scale(1.0) rotate(360deg); }
}

Veja rodando no jsfiddle

Animação de Caminhos (paths)

Para este tipo de animação, basta alterar os caminhos conforme o tempo da animação no atributo d da tag path.
A animação do atributo d deve ser feita com SMIL, pois o CSS não permite a animação desse atributo.
No código abaixo, o atributo values (na tag animate) armazena os caminhos de cada passo da animação, e o atributo d (na tag path), o caminho inicial:
<path
   d="m 288.8656,608.00072 a 44.166031 ...
   id="novanuvem2"
   >
   <animate
    id="path"
    xlink:href="#novanuvem2"
    attributeName="d"
    repeatCount="indefinite"
    values="
        m 288.8656,608.00072 a 44.166 ...
        m 325.36386,601.50838 a 42.18 ...
        m 352.99225,577.56713 a 42.18 ...
        m 365.39429,541.71227 a 42.18 ...
        m 358.90196,505.21401 a 44.16 ...
        m 334.96071,477.58562 a 44.16 ...
        m 299.10585,465.18357 a 44.16 ...
        m 262.60758,471.6759 a 42.188 ...
        m 234.97918,495.61715 a 42.18 ...
        m 222.57713,531.47202 a 42.18 ...
        m 229.06946,567.97029 a 44.16 ...
        m 253.01071,595.59869 a 44.16 ...
        m 288.8656,608.00072 a 44.166 ...
    dur="5s"/>
  </path>

Um ponto importante é que o atributo xlink:href="#novanuvem2" na tag animate deve corresponder ao id da tag path.

Veja rodando no jsfiddle

Conclusão
Há formas diferentes e, talvez, mais eficientes para implementar esse tipo de animação, mas o objetivo desta resposta é oferecer um exemplo prático de como criar animações com gráficos vetoriais.
Ao animar objetos no SVG, seja através das tags CSS, SMIL ou através de Javascript, a animação pode apresentar comportamentos diferentes ou exigir uma sintaxe específica conforme o navegador, por isso a dica é consultar e testar a aplicação em diversos navegadores:

Mozilla
Apple - Safari
MS - Internet Explorer

A vantagem da animação SVG é que a qualidade da imagem não depende da resolução do dispositivo onde ela será renderizada (ex: monitores, celulares, etc.), devido a imagem ser formada por vetores e não mapa de bits.

Abaixo, seguem outros links que ajudaram na elaboração da resposta:
Basic SVG path tweening with SMIL
Keyframe Animation Syntax
How SVG Line Animation Works
A Guide to SVG Animations - SMIL
W3 - Animation
SVG Path Morphing
Comment: Seria interessante ter um motivo para `-1` nesta resposta (caso seja por causa de um erro na resposta assim ela pode ser corrigida e aprendemos todos com isso).
Comment: @Sergio infelizmente este tipo de bom senso não faz parte da nossa comunidade. Gomiero, muito bacana a sua abordagem contudo achei que a mecânica que você usou para descrever o processo ficou muito atrelado ao uso de softwares gráficos e o SVG possibilita a criação de formas compostas com handcode only, consegue descrever um pouco sobre o processo de drawing?
Comment: Acho que o -1 deve ter sido por ter criado uma resposta muito longa, tendo explicado até os conceitos de animação etc, o que é absolutamente desnecessário pelo conceito do site... Acho que não só o -1, mas a falta de +1's tbm deve ser por isso... eu do AR retiraria o capítulo "Teoria" inteiro... aposto que a recepção melhoraria muito. :-) +1
Comment: Eu quero muito acreditar que quem deu -1 realmente leu e entendeu toda a resposta. Custa nada esclarecer ao AR o que ele pode melhorar na pergunta.
Comment: @gustavox Muito obrigado pela dica!! :-)
Comment: @FelipeAssunção e Sergio: Obrigado!! Eu não coloquei, porque na  pergunta, a animação é bem simples. Mas vou atualizar a resposta assim que encontrar algo sobre o assunto
Comment: @Sergio Acredito que possa ser a frase da Wikipedia no início da resposta. Eu gosto muito de animações, principalmente 3D e a idéia foi redigir o texto usando um tom bem humorado :)
Answer: Usando apenas SVG talvez algo assim seja uma boa abordagem.
https://jsfiddle.net/wgzk3qze/
É claro que a animação que eu fiz não esta perfeita, foi só para exemplificar.
Eu criei 8 casos na animação mas acho que se consegue reduzir o código para 4.
[PS] este ja funciona em Chrome também: https://jsfiddle.net/khnsoynh/
<svg x="0px" y="0px" width="283.026px" height="214.477px" viewBox="0 0 283.026 214.477" enable-background="new 0 0 283.026 214.477">
  <path fill="#FFFFFF" stroke="#000000" stroke-width="10" stroke-miterlimit="10">

  <animate attributeName="d" dur="20000ms" repeatCount="indefinite"  values="M236.5,140.163
    c27.5,37.281-59.5,78.029-93.945,36.414C124.321,220.712,24.5,183.946,43,143.631c-44.5-0.433-18-105.773,38-85.832
    C59,4.045,221.593,3.622,203,55.197C262.5,35.257,286,135.394,236.5,140.163z;

    M205.254,179.176
    c-17,29.568-148.404,29.972-151.214-15.828C9.319,186.476,0,64.738,40.913,71.946c-18.9-41.207,93.852-61.207,107.1-38.207
    c36.752-38,159,20,98.851,67C297.423,120.643,238.23,204.821,205.254,179.176z;

    M90.72,175.919
    c-55.178,19.285-115.488-41.725-53.895-65.88c-65.323-12.787-10.907-82.788,48.762-69.814
    c0.641-31.206,156.551-12.623,127.037,26.648c79.56-15.428,80.186,98.593,3.851,85.554
    C245.988,194.152,97.778,210.631,90.72,175.919z;

    M47.013,165.738
    c-52.501-16.871-37.225-129,11-116c0-43.084,110-49.738,134-9c29.231-28.426,105.832,56.274,51,74c64.265,35.76-32.06,120.03-68,60
    C153.013,220.738,46.013,202.738,47.013,165.738z;

    M47.43,73.458
    c-27.5-37.281,59.5-78.029,93.945-36.414C159.609-7.091,259.43,29.675,240.93,69.99c44.5,0.433,18,105.773-38,85.832
    c22,53.754-140.593,54.177-122,2.602C21.43,178.364-2.07,78.227,47.43,73.458z;

    M105.42,28.169
    C115.013,12,212.013,15.571,214.013,54.738c42.794-18.885,77.734,79.958,37.435,96c28.872,29.477-84.834,76.648-107.615,26
    c-27.82,51-143.833-6-108.82-63C-17.929,88.663,60.013,12,105.42,28.169z;

    M190.986,40.122
    c55.688-19.871,116.554,42.993,54.393,67.882c65.926,13.175,11.007,85.303-49.212,71.935
    c-0.647,32.154-157.996,13.006-128.21-27.458c-80.294,15.897-80.926-101.588-3.887-88.153
    C34.285,21.335,183.863,4.355,190.986,40.122z;

    M236.013,80.738
    c46.55,18.449,40.876,101.678-13,83c-12,35.231-130,41.669-139,13c-30,28-91-69.5-40-85c-40-41,51-85,81.693-61.14
    C141.513,3.738,277.013,52.738,236.013,80.738z;

    M236.5,140.163
    c27.5,37.281-59.5,78.029-93.945,36.414C124.321,220.712,24.5,183.946,43,143.631c-44.5-0.433-18-105.773,38-85.832
    C59,4.045,221.593,3.622,203,55.197C262.5,35.257,286,135.394,236.5,140.163z" />

  </path>
</svg>

Comment: Dei run e não funcionou...
Comment: Ups, só testei no Firefox e no Safari!
Comment: De facto no chrome não funciona!
vou ver porque!
Comment: Ok, ha um bug no Chrome que afecta o parâmetro 'keyTimes' mas podemos suprir o comando e neste caso não afecta a animação https://jsfiddle.net/khnsoynh/
Comment: @helderk por mais que o seu exemplo funcione, não utilize apenas o link para demonstrar o resultado. Elabore melhor sua resposta e explique a solução diretamente em sua resposta. Se o link sair do ar ou for removido, sua resposta será invalidada.
Comment: @CelsomTrindade Pois ta certo.
Answer: Eu vou dar um pouco mais de base teórica por experiência própria, talvez isso te ajude, vamos lá.
Pelo que entendi, você não quer exatamente converter uma animação que está sendo renderizada em um <canvas> para svg, você quer criar a animação via JavaScript, dando saída para SVG certo?
Indo direto ao ponto, existem duas libs bem conhecidas para esse propósito, detalhe é que ambas são do mesmo autor.
raphaël.js
snap svg
Porque vale a pena usar Snap.svg/Raphaël.js?
Ambas fazem basicamente a mesma coisa, você escreve javascript, e elas vão dar saída em SVG.
Raphaëljs, funciona a partir do IE6 e Snap.svg a partir do IE9, ou seja, você vai ter uma cobertura de marketshare bem alto mesmo usando Snap.
Entre as duas, recomendo Snap porque é mais moderna, aborda mais recursos novos, é simples de usar, tem suporte a animação, está documentada e tem exemplos de como usa-la. Você também pode carregar um svg externo ou fazer o parsing de um svg já carregado na página, pra dentro do Snap e usa-lo para manipular o svg, o que te da a vantagem de importar vetores do illustrator por exemplo, em vez de desenha-los via javascript.
Bom espero que isso possa te ajudar.


For a Paypal IPN what's the difference between auth_amount and mc_gross?

Question: I'm having a hard time finding this out from the documentation.  I have some code I've inherited which needs to get he payment amount from a Paypal IPN transaction.  It's expecting the variable "auth_amount" from a Paypal IPN but is not getting passed this field.  It looks to me from the Paypal docs as though I should be using the field "mc_gross" which is labelled as "Full amount of the customer's payment, before transaction fee is subtracted.".
The Paypal IPN docs describe the "auth_amount" field as "Authorization amount", which doesn't mean much to me.
I'm going to change it to use mc_gross, but I just want to check first that I'm not missing something silly?
Thanks!
Answer: Check this out:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables

mc_gross
  Full amount of the customer's
  payment, before transaction fee is
  subtracted. Equivalent to
  payment_gross for USD payments. If
  this amount is negative, it signifies
  a refund or reversal, and either of
  those payment statuses can be for the
  full or partial amount of the original
  transaction.
Comment: Hi, yes, I saw that, I'm just trying to understand what auth_amount is and why this code may use it.  Do you know what auth_amount does?
Comment: Auth ammount is how much the user authorised to send you before fees and stuff.


Why does member function return nil

Question: I have a list:
*DSTATES* = ( ( list1 ) ( list2 ) ( list3 ) ... ( listn )  )

And a list of state names, x = ( list )
*DSTATES* has ( (zero) (three two one) (two) (three zero) )
x has (two).
Here's my code:
(map '() #'(lambda (x)
           (princ "Looking at transition ") (princ x)
           (princ #\newline)
           (if (and (eq '() (member x *DSTATES*)) (not (eq '() x)))
               (progn
                 (princ x) (princ " is not a member of *DSTATES*")
                 (princ #\newline)
                 (setq *DSTATES* (append *DSTATES* (list x)))))
           (princ "Intermediate *DSTATES* ") (princ *DSTATES*)
           (princ #\newline) (princ #\newline))
       trans)

When I do ( eq '() ( member x *DSTATES* ) ) it always--as far as I can tell--returns true. Because of this *DSTATES* gets larger and larger and my loop, which has a stop condition on the size of *DSTATES* never terminates.
How can I fix this?
Comment: problem 4: `*states*` is a list of lists. `member` will not find anything, since it does not look at the sublists.
Comment: `member` checks if an item is in a list. `member` does not check if an item is in a sublist.
Comment: Style problem 2: `(eq '() foo)` is `(null foo)`. If it is a boolean use `(not foo)`.
Comment: Style problem 1: never append to the end of a list.
Comment: Ok thanks for those tips. What's wrong with appending to the end of a list?
Comment: Style problem 3: instead of `if` and `progn` use `when`.
Comment: lists are linked cons cells. adding to the front is fast. Adding to the end needs to traverse the whole list.
Comment: Right ok, thanks for that. For this problem, performance isn't a huge issue, but i'm glad you pointed that out
Comment: never do that. It's just wrong. Don't write bad code.
Comment: alright then, noted. So when I apply (member) to a list of lists what does it see if it doesn't see the sublists?
Comment: Ok, I need `member` to see `(two)` as a list item and not a sublist. Is there a way to do that?
Comment: I would iterate over the list and see if the item is a member of one of the sublists...
Comment: Thanks for the help! I was able to solve it using `#'tree-equal` in the `:test` section of `member`
Answer: Simply do (member x *DSTATES* :test #'tree-equal)
That will make member check membership.
Hope that helps guys
how to test whether one list is a member of another

Why does member function return nil


script Python que lê um Json e converte em um javascript

Question: Olá gostaria de uma ajuda,
Tenho um json que posso pegar ela da web ou baixar em meu linux... e preciso montar um codigo padronizado a partir desse json.
Preciso montar um javascript  sempre padrão com as modificações que vem do meu json.
Preciso mudar dois valores no meu javascript.
Hoje atualmente funciona certinho, mais eu que monto manual, queria montar isso de forma automatica usando python ou javascript.
My Json :

{
    "home": [
        {
            "base_url": "home",
            "redirect_url": "/",
            "type": "www.testemestradoolpt.com.br"
        }
    ],
    "portal": [
        {
            "base_url": "portal",
            "redirect_url": "/",
            "type": "www.testemestradoolpt.com.br"
        }
    ],
    "digital": [
        {
            "base_url": "digital",
            "redirect_url": "/",
            "type": "www.testemestradoolpt.com.br"
        }

    ]
}

Meu JavaScript:

'use strict';

const querystring = require('querystring');

 exports.handler = (event, context, callback) => {
     const request = event.Records[0].cf.request;
     const headers = request.headers;
     const uri = request.uri;

     var origin = request.origin[0].custom.domainName;
     console.log(`Request #PATH# is "${uri}"`);
     console.log(`Request #INCOMING REQUEST ORIGIN# set to "${origin}"`);

     const regex = /^\/(digital|home|portal|)[^\/]*/i;  **<<<< ADICIONAR AQUI**
     if (regex.test(request.uri))
     {
             /* Set custom origin fields*/
             request.origin = {
                 custom: {
                     domainName: 'www.testemestradoolpt.com.br' **<< ADICIONAR AQUI**
                 }
             };
             request.headers['host'] = [{ key: 'host', value: '*'}];
             /**origin = request.origin.custom.domainName;  enable it for testing*/
    }
    /** for testing purposes don't use unless you need to, big performance hit
    console.log(`###### - > Request HOST "${request.headers.host[0].value}"`);
    console.log(`###### - > Final Request Origin Server "${origin}"`);
    */
    callback(null, request);
};

Se vocês repararem eu so preciso adicionar meu base_url que vem dos meus json no campo de expressao regular do javascript e apenas uma vez o type que e a url no outro campo, a url sempre vai ser a mesma.
Eu fiz um script em python que me traz a base url, mais estou precisando de um script em python que monta para min o javascript com as variaveis do json como o java script acima que mandei, e estou tendo muita dificuldade em fazer isso, segue o que consegui fazer em python:

import json

with open('dataload.json') as json_file:
    data = json.load(json_file)
    for p in data ['home']:
         print(p['base_url'])
Answer: Você pode fazer algo como:
regexp = []
url = ''
for key in json:
    for value in json.get(key, []):
        url = value.get('type')
        regexp.append(value.get('base_url'))

regexp = str('|').join(regexp)

js_script = """
'use strict';

const querystring = require('querystring');

 exports.handler = (event, context, callback) => {
     const request = event.Records[0].cf.request;
     const headers = request.headers;
     const uri = request.uri;

     var origin = request.origin[0].custom.domainName;
     console.log(`Request #PATH# is "${uri}"`);
     console.log(`Request #INCOMING REQUEST ORIGIN# set to "${origin}"`);

     const regex = /^\/(""" +  regexp + """|)[^\/]*/i;  **<<<< ADICIONAR AQUI**
     if (regex.test(request.uri))
     {
             /* Set custom origin fields*/
             request.origin = {
                 custom: {
                     domainName: '""" +  url + """' **<< ADICIONAR AQUI**
                 }
             };
             request.headers['host'] = [{ key: 'host', value: '*'}];
             /**origin = request.origin.custom.domainName;  enable it for testing*/
    }
    /** for testing purposes don't use unless you need to, big performance hit
    console.log(`###### - > Request HOST "${request.headers.host[0].value}"`);
    console.log(`###### - > Final Request Origin Server "${origin}"`);
    */
    callback(null, request);
};
"""

# salvar o arquivo
# ou responder a requisição http com esse script.

Você pode criar uma rota em seu servidor que gera e retorna este arquivo pra o cliente.
no cliente (arquivo html) você pode fazer algo como:

Não sei qual framework que você está usando, mas não se esqueça de definir o content-type nos header da resposta como text/javascript.
Comment: Uma duvida no campo url"" eu coloco a url do meu json?

fui rodar e surgiu o seguinte erro.

root@LAPTOP-3IP5GPAG:~/cdn/python# python python2.py
Traceback (most recent call last):
  File "python2.py", line 3, in
    for key in json:
NameError: name 'json' is not defined
Comment: na linha 3 ele itera a variavel `json` que você tem que trocar/ou defini-la com o seu json.
Comment: Problem solved. Thanks man!
Comment: mateus pode me ajudar... parece que o topico nao consigo postar mais duvidas... vou editar a pergunta.
Comment: Eu fiz essa nova pergunta aqui: https://pt.stackoverflow.com/questions/419111/problemas-para-fazer-junção-de-informações-no-meu-script-python


What is the importance of $1 \neq 0$ in Spivak's Calculus?

Question:
(P6) If $a$ is any number, then $a⋅1=1⋅a=a$

Cannot understand the importance of this. Do we know what 0 is but don't yet know what 1 is?
And what does it mean to prove $1 \neq 0$?
Comment: We need more context. Is he constructing the real numbers or talking about any arbitrary ring?
Comment: Constructing reals I suppose. Here's some more context: https://math.stackexchange.com/questions/164811/explanation-for-why-1-neq-0-is-explicitly-mentioned-in-chapter-1-of-spivaks-c The link may contain the answer, but if so then I don't understand it.
Comment: If the properties being listed are intended to be all that is assumed about the real numbers, then, as Spivak says, the assumption $0\neq1$ is all that prevents us from believing that the only real number is 0 (and that therefore $1=0$).  That belief would completely mess up calculus (and most of the rest of mathematics).
Comment: I've also found in the notes "...and that there are distinguished numbers called 0 and 1." here http://math.uga.edu/~pete/math2400_lecture_1.pdf I guess it's important to note that multiplicative (1) is not the same as additive identity (0), because we don't yet know what 1 and 0 means precisely?
Comment: Andreas Blass, thank you.
Comment: That link contains the answer. He defines the real numbers from those axioms and those axioms can not be used to show that  $0≠1$, so he must include that as an additional axiom.
Comment: Okay, I think I get it now.
Comment: It is for Uniqueness
Answer: The axioms can be used to show that if $z$ is an element with the property that $z+x=x+z=x$ for every $x$, then $z=0$. Indeed,
$$
z+0=0
$$
from the stated property of $z$ (with $x=0$) and also
$$
z+0=z
$$
from the property of $0$ stated as an axiom. Hence $z=0$.
The proof that if $ux=xu=x$ for all $x$ then $x=1$ is just the same (substitute $u$ for $z$, $1$ for $0$ and multiplication for addition).
On the other hand, the set $\{?\}$ ($?$ means any object you like) with the operations
$$
{?}+{?}={?},\qquad {?}{?}={?}
$$
satisfies all axioms regarding addition and multiplication (and also order, actually) stated for the real numbers. Here $0={?}=1$, because the unique element satisfies the requirements for $0$ and $1$ stated by the axioms.
This means that we cannot prove $0\ne1$ only with the stated axioms and so we need to add $0\ne1$ as a further axiom, if we want the axioms to reflect what we expect from the real numbers.
Comment: Isn't 1+1=2? :)
Comment: @Max If $0=1$, then $1+1=0$.
Comment: Thanks. Really hard to know what I'm "supposed to know" and what I'm not supposed to know. He later shows how $1 > 0$ because $1=1^2$ and $1^2 > 0$, I guess we're truly not supposed to know much about the symbols "1" and "0" at this point. One is additive identity and the the other is multiplicative identity, and maybe they're the same thing, we don't really yet know. Using other symbols rather than "1" and "0" would help disassociate from preconceived notions about the two identities.


Use a form to run queries on a date range

Question: I have an MS-Access DB that pulls information in from an Excel file with 6 worksheets, so I get 6 tables. I created 7 queries, all of which make tables from the excel data, 6 of those 7 do a count of an item ie:
SELECT DISTINCT DISPLAYNAME, COUNT(DISPLAYNAME)
FROM [TXFR REC]
GROUP BY DISPLAYNAME

The 7th query pulls those 6 tables together into a sort of report table by using left joins onto one of the tables, where the connection to all the others is a DISPLAYNAME.
I have created a Form with 4 buttons and two date boxes, a start date and an end date. What I want to do is the following:

Choose Start Date
Choose End Date
Press Button that runs the 7 queries in the order I specified by invoking the date range from steps 1 and 2 ** THIS IS WHERE I AM STUCK: I do not know how to force this date range on the queries **
Run the report
Export the report
Close the form

The date boxes are set to General Date and the method used for them is GetDates so you just click in the box and the calendar pops up and you choose your date.
I did see this post here but am not following to well:
Date Range Form
Here is the text from a test query as suggested by a user and in the format suggested by the answering person:
SELECT [NO ADMITTING DX (HEALTH ISSUE)].PHYSICIANDISPLAYNAME, Count([NO ADMITTING DX (HEALTH ISSUE)].PHYSICIANDISPLAYNAME) AS CountOfPHYSICIANDISPLAYNAME INTO NO_ADMIT_DX_COUNT
FROM [NO ADMITTING DX (HEALTH ISSUE)]
WHERE ((([NO ADMITTING DX (HEALTH ISSUE)].PHYSICIANDISPLAYNAME) Is Not Null) And (([NO ADMITTING DX (HEALTH ISSUE)].AdmitDtm) Between Forms!PRINT_REPORT![START DATE] And FORMS!PRINT_REPORT![END DATE]))
GROUP BY [NO ADMITTING DX (HEALTH ISSUE)].PHYSICIANDISPLAYNAME;

** This query now works properly **
Thank you for all the help.
Answer: For your query, use something like this.
   SELECT  DISPLAYNAME, COUNT(DISPLAYNAME)
 FROM [TXFR REC]
  WHERE [TXFR REC].yourDate BETWEEN [Forms]![yourFormName]![yourStartDate]
      AND [Forms]![yourFormName]![yourEndDateField]
GROUP BY DISPLAYNAME

All of your queries that you want to rely on a date range should have these parameters. The advantage to doing it this way is that you can give your two date fields on your form a datePicker. It would still work the same if you did something like this:
    SELECT  DISPLAYNAME, COUNT(DISPLAYNAME)
 FROM [TXFR REC]
  WHERE [TXFR REC].yourDate BETWEEN [Please Enter a Start Date]
      AND [Please Enter an Ending Date]
GROUP BY DISPLAYNAME

It's all preference though. Just throw a button on there and go to Misc in the wizard and choose run query if you want.
Answer: Edit your queries to rely on the value of the form in the where clause:
[Forms]![form's name]![form's control]
Here's a Screenshot example
This will make your queries only work with the form, however.  You might consider copying your queries and renaming and editing the copies to reflect its limitation.
Comment: Above, [form value] needs to be the name of the control in your form, and you also need to have the form open with values populated in the date fields or you will get no results. If you want to run the queries with the form closed, another option would be to bind the date fields to a table and query based on the table field values.
Comment: Hi and thank you for the feed back. I want a button on the Form (Modal Dialogue) to run the queries, this will be a UI for people to just click the mouse a couple of times and get the info. I tried a test query and so far I get a black return table...still thinking it through.
Comment: @MCP_infiltrator can you add your test query to your question?  A screen shot of the query designer or the text of your SQL statement should suffice.
Comment: @coge.soft sure thing
I am actually going to do the query now and try to work through this so I'll show you what I have right now.


jquery ui slider - changing the position of the handle

Question: I'm using a jquery ui slider with a play/pause button to control a d3.js animation. When i press the play button, i'd like the slider handle to move along, any way to do that?
Likewise, is there any way to position the slider at a specific step within the slider? I still want the max and min to remain the same but for example, if i want the handle to start at the last step when the page loads instead of the first one.
Answer: Use setInterval and stopInterval see there
Lets say you have play button that should invoke under mentioned method and switch to pause mode.
Some example where slider moves each sec and represent hours:
play
var hoursInterval = setInterval(function(){
        var timeOfDay = (localStorage['hour']==23)?0:parseInt(localStorage['hour'])+1;
        $("#playHour").slider("value",timeOfDay);
    },1000);

pause
....
clearInterval(hourInterval);

Suppose it will help you


No bash, qual a diferença entre uma string nula e uma string vazia?

Question: Gostaria de saber se existe diferença em como o bash representa as variáveis com valores nulos
var=

e com strings vazias
var=""

Quais cuidados devo ter ao manipular variáveis como essas?
Answer: Considere o seguinte:
var1=

var2=""

A variável var1 não tem valor algum, tem seu valor nulo (null). Um valor nulo é exatamente um "NADA"! Diferente do valor da variável var2 que tem uma string em branco.
Imagine que estaremos usando alguma linguagem de objetos (só para ficar mais didático). Usando o exemplo com Python:
$ python
Python 2.7.12 (default, Jun 29 2016, 14:05:02)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> var1 = None
>>> var2 = ""
>>> type(var1)
<type 'NoneType'>
>>> type(var2)
<type 'str'>

ps: None em python é a mesma coisa que null em outras linguagens.
A situação da var1 demonstra que a variável não há inicialização de um valor. Logo, um "nada" não poderá receber algum retorno, caso tente... irá receber o famoso erro NullPointerException porque o "nada" não pode receber atributo(s): não recebe valores e aponta para nada.
>>> len(var1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'NoneType' has no len()

A var2 é uma variável do tipo string vazia. Algo "vazio" tem seu valor de zero porque deste jeito a variável está inicializado. Ou seja, mesmo sendo um "caractere em branco" ele tem seu lugar reservado na memória. Então, quando utilizado o len() (length) será retornado 0:
>>> len(var2)
0

Answer: Por favor, considere o shell script em sh:
#! /bin/sh

aNullString=
anEmptyString=""

if [ -z ${aNullString} ] ; then
    echo The string aNullString is empty
else
    echo The string aNullString is not empty
fi

if [ -z ${anEmptyString} ] ; then
    echo The string anEmptyString is empty
else
    echo The string anEmptyString is not empty
fi

if [ ${aNullString} = ${anEmptyString}] ; then
    echo The strings aNullString and anEmptyString are equal
else
    echo The strings aNullString and anEmptyString differ
fi

Ele sugere que a= e b='' são a mesma cadeia de caracteres, pois seu resultado é:
The string aNullString is empty
The string anEmptyString is empty
The strings aNullString and anEmptyString are equal


Find the triangle(s) formed by nine arbitrary concyclic points on a circle

Question: I have read a lot about the nine point circle. Finding the nine point circle of a triangle is straightforward. But what about going the other way?
Let $w$ be a circle. Given nine arbitrary concyclic points on $w$, how can one find the triangle (if it exists) for which $w$ is the nine-point circle?

In other words, let's say there exists a triangle, $t$, where

$P$, $Q$, and $R$ are the midpoints of each side of $t$
$P'$, $Q'$, and $R'$ are the foot of each altitude of $t$
$P''$, $Q''$, and $R''$ are the midpoints of the line segments from each vertex of $t$ to the orthocenter
$P$, $Q$, $R$, $P'$, $Q'$, $R'$, $P''$, $Q''$, and $R''$ all lie on circle, $c$

Given $P$, $Q$, $R$, $P'$, $Q'$, $R'$, $P''$, $Q''$, $R''$, and $c$, find $t$

Note: there may exist multiple triangles which fit the criteria for $t$, or there may exist no triangles which fit the criteria for $t$. Thus, there are two halves to the problem:
a) Determine of a triangle $t$ exists whose significant points are $P$, $Q$, $R$, $P'$, $Q'$, $R'$, $P''$, $Q''$, and $R''$
b) If $t$ exists, find the vertices of $t$
Comment: Are you sure that every set of nine concyclic points are the nine-point circle for some triangle? Suppose the points are all very close together one one side of a large circle?
Comment: @retrovius You imply that if nine arbitrary points are given on a circle, then the originating triangle can be determined (upto rotation maybe) right?
Answer: I've significantly re-worked this answer. For a previous version, see the Edit History.

"The" nine points of a triangle fall into three types:

the three midpoints of its sides ($P$, $Q$, $R$ in the figure),
the three points ($P'$, $Q'$, $R'$) half-way between its orthocenter and its vertices (we'll call these "ortho-midpoints"), and
the three feet ($P''$, $Q''$, $R''$) of its altitudes.

These points naturally determine three concyclic right triangles:

By Thales' Theorem, each hypotenuse is necessarily a diameter of the nine-point circle. Each diameter has a triangle midpoint and an ortho-midpoint as its endpoints. The left-over points are the altitude feet, which determine the original triangle's orthic triangle. These elements happen to be related in an interesting way:

Fun Fact. The midpoint/ortho-midpoint diameters must be the perpendicular bisectors of the sides of the orthic triangle.

The figure shows the situation for diameter $\overline{PP'}$ and orthic triangle side $\overline{Q''R''}$:

For proof, we note that, since $\angle BQ''C$ and $\angle BR''C$ are right angles, Thales tells us that $Q''$ and $R''$ live on a circle with diameter $\overline{BC}$ (and, therefore, with center $P$). Similarly, with $G$ the orthocenter of $\triangle ABC$, we have right angles $\angle AQ''G$ and $\angle AR''G$, so that $Q''$ and $R''$ live on a circle with center $P'$. Thus, $\overline{Q''R''}$ is a chord common to the two circles, so that it must be perpendicular to, and bisected by, the line $\overline{PP'}$ connecting the centers. $\square$
The Fun Fact provides the "only if" portion of this characterization of viable nine-point sets:

Theorem. A set of nine distinct concyclic points is "the" nine-point set of some triangle if and only if it can partitioned into three diametric pairs $\{P,P'\}$, $\{Q,Q'\}$, $\{R,R'\}$ and a triad $\{P'', Q'', R''\}$ such that $$\overline{PP'}\perp\overline{Q''R''} \qquad
\overline{QQ'}\perp\overline{R''P''} \qquad
\overline{RR'}\perp\overline{P''Q''}$$

For the "if" part, we provide a construction a quartet of solution triangles. To begin, one can show (as @mathlove did in this answer)

Lemma. The incenter $G$ and excenters $A$, $B$, $C$ of $\triangle P''Q''R''$ form an orthocentric system such that $\triangle ABC$, $\triangle GBC$, $\triangle AGC$, and $\triangle ABG$ have altitude feet $P''$, $Q''$, $R''$. No other triangles have these altitude feet.

The four triangles determined by the orthocentric system share a common nine-point set, namely: the three altitude feet ($P''$, $Q''$, $R''$), as well as the three midpoints of $\overline{AB}$, $\overline{BC}$, $\overline{CA}$ (the midpoints of $\triangle ABC$), and the three midpoints of $\overline{GA}$, $\overline{GB}$, $\overline{GC}$ (the ortho-midpoints of $\triangle ABC$). The roles of some points change for $\triangle GBC$, $\triangle AGB$, $\triangle ABG$, but the point-set itself remains the same.
By the Fun Fact, the midpoints and ortho-midpoints determine diameters perpendicular to the sides of $\triangle P''Q''R''$. Such diameters are unique, so they must coincide the the Theorem's assumed pairs $\{P,P'\}$, etc, so that the midpoints and ortho-midpoints themselves coincide with the points $P$, $P'$, $Q$, $Q'$, $R$, $R'$. Thus, the given nine points are "the" nine points of $\triangle ABC$. $\square$

So, given nine points, the Theorem tells us when the set is viable, and the Lemma tells us how to construct an orthocentric system that yields exactly four solution triangles.
Note that nine points can contain four diametric pairs, raising the possibility of additional solutions. What happens then?
In the case of four diametric pairs, there the altitude-feet triad must contain one of them (so that the other three remain in tact), making the orthic triangle a right triangle (by Thales, yet again). Consequently, we have two midpoint/ortho-midpoint diameters perpendicular to the legs, which makes them perpendicular to each other, while the third midpoint/ortho-midpoint diameter is perpendicular to the hypotenuse diameter. In other words: Those four diameters comprise two mutually-perpendicular pairs.

I'll leave it as an exercise to the reader to show that there is only one choice of altitude-foot triad, unless the diameters make angles of $30^\circ$ and $60^\circ$; in that case, there are two symmetric choice of triad, leading to two orthocentric systems, for a total of eight solution triangles.
Comment: @retrovius: Diametric points come in pairs. With 9 distinct pts, there can be at most four diametric pairs. As indicated in the answer, the nature of viable 9-pt sets requires at least 3 such pairs. So, if you have 9 pts at random, and there are 4 or more pts whose diametric opposites aren't among those pts, then those pts are not a 9-pt set of any triangle. If there are only 3 un-paired pts, or else just one, the set *might* be viable. As mentioned, the easiest way to tell *may* be to pick ostensible midpts from the pairs, construct the triangle, and see if the remaining pts fit the triangle.
Comment: I am reading this and trying to understand XD I really appreciate this solution, I'll get back to you with questions. If you could add drawings/diagrams to go along with your explanation that would be wonderful, but I know it's a lot to ask.
Comment: @retrovius: Accepting my answer is appreciated, but if you (understandably) still find it unsatisfying, please un-accept so that others aren't discouraged from posting alternative approaches. ... I'm actually still mulling the problem (but have gotten a little distracted). I've run into a few separate cases and am seeking the appropriate perspective by which to unify them, but I'm not quite there yet.
Comment: I appreciate that, but your solution actually does make sense! I just had to visualize it first. I'll get back if I can implement an algorithm. Let me know if you have other ideas.
Comment: When you say "nine points determine at least 4 diameters", do you mean at least 4 distinct simultaneous diameters?


How does the ear pick which note to hear when hearing guitar vibrato

Question: When adding vibrato to a fretted note on an electric guitar, if I do so by bending the note up a semitone, I perceive as the pitch of the original note being modulated. When applying vibrato to a bend however I sort of bend up to the note from the semitone below but this I hear it as the sound of the higher pitch being modulated, despite it technically being the same as the pitch I'm not hearing in the original case.
I thought it might be my brain latching onto the start point of the vibrato as you typically bend up to pitch then release but it seems to be the same if I just start from the semi tone down.
Is this just an ambiguous sound that forces my brain just pick the most likely interpretation? If so why does it always pick the same option?
Comment: If your vibrato is actually as wide as a semitone, then that's a *very* wide vibrato. Perhaps consider pulling it back a bit to more like a quarter tone or less.
Comment: @topomorto - given several slightly different frequencies to be happy with, I reckon our ears will accept the ones that are most in tune with the rest of what we listen to. Why would it latch on to something dissonant? Maybe that's one of the reasons I find it hard listening to coliatura opera singers...
Comment: Is it actually true in general that the ear 'picks a note' to hear?
Comment: @topomorto IIRC, it depends on the width and rate of the vibrato and different brains will have different responses. Some vibratos will be heard as a single note by 99% of listeners, while others will be heard as a wide pitch variation between two notes (almost like a trill if it's fast enough) by 99% of listeners. There is research on what makes a pitch a pitch and how our brains distinguish between pitch variation and vibrato. I don't have it to hand at this time.
Comment: In my research I found that while some vibrato is a bit wider than a semitone (up to 120 cents) and is still perceived as vibrato if played with a fast enough rate (around 7 Hz), the most common vibrato width seems to be around 70 cents, which is a bit wider than a quarter tone.
Comment: Purely anecdotally, imho perception of vibrato is one of those things in music that is very subjective. What one person thinks really enhances a note, the next person (i.e. me) thinks ruins it.
Comment: @Tim my ears certainly latch on to any hint of dissonance! It's very annoying. They also tend to hear notes with strong, slow vibrato as being unstable in pitch and drifting up and down (which they sometimes are if the vibrato is being used to cover up for poor technique).
Answer: I found an excerpt from a chapter written by Johan Sundberg in  The Psychology of Music, a compilation of articles, presumably all related to psychoacoustics.
Here are some quotes and explanations:

Although F0 [the fundamental frequency of the note] varies regularly in such tones, the pitch we perceive is perfectly constant as long as the rate and extent of vibrato are kept within certain limits.

This means if a vibrato is too wide or too slow or too fast, it will not be perceived as vibrato of one note, but instead a fast glissando or glide back and forth. I doubt that human-generated vibrato is likely to ever be too fast, but electronic vibrato can easily be sped up to the point that it is actually frequency modulation that causes a dramatic change in timbre, as used in synthesizers.
Later:

Our conclusions are that the pitch of a vibrato tone is practically identical to the pitch of a vibrato-free tone with an F0 equal to the geometric mean of the F0 of the tone with vibrato.

That suggests that upwards vibrato from a fretted note should sound a bit sharp, and downwards vibrato from a bent note should sound a bit flat.
In your particular situation, you can't entirely trust your perception of pitch, because you are overly informed about how you're creating the sounds and therefore are susceptible to confirmation bias. By that I mean, you expect to hear a certain pitch and that can create the auditory illusion of hearing exactly the pitch you expect to hear.
That said, unless you're playing in an ensemble with other instruments that are playing the same nominal pitches as you, naive listeners are unlikely to notice the difference.
Answer: Could be a few things. The note you hear is often the one you want to hear - in tune with the accompanying chord and relevant to the melody. If the vibrato stays a little longer on the higher/lower note, that's coming out as a more important pitch.
Somehow, we tend to hear a fluctuating note as the highest part. For that reason, we often play the note we want a fret lower than it should be, so that giving it a semitone vibrato, it gives us the right note to hear. We may even start that with the string bent to pitch - a cunning, but not easy move.
There's probably a limit to the amount a note can be stretched upwards before we become aware that something's out of tune, but I'm not party to it.
Comment: "*For that reason, we often play the note we want a fret lower than it should be, so that giving it a semitone vibrato, it gives us the right note to hear*" Can you think of any examples of this? I don't know if I've ever heard vibrato what wide. "*There's probably a limit to the amount a note can be stretched upwards before we become aware that something's out of tune, but I'm not party to it*" Yes, this is true, but vibrato is different because it's periodic and not a static alteration in frequency.
Comment: @ToddWilcox - the vib. doesn't have to be that wide, it just needs the 'proper' note to be played on a bent string, a fret lower than normal, as then it can be bent to the 'right' note and a sort of 'backwards vib.' applied, if that makes sense. If the note played is on pitch using a bent string a fret below, the 'let down' can be as little or as large as you need, up to, obviously, a semitone max. I used to use the technique a lot, but don't play so much guitar at the moment.  Dependant on style, a tone vib. is as much as I'd go, usually that's between, say, a P4 and P5; or b7 and octave.
Comment: I don't understand what you mean about vibrato "having to be wide". You've asserted that guitarists will play the note they want a fret lower than they otherwise would if they want to apply a wide vibrato to it because we allegedly prefer the highest note when vibrato is making the pitch ambiguous. I certainly don't know everything but I've never heard of any of that before, neither the higher note preference nor the guitar technique. I would like to know more about both so I was wondering if you could point me towards some sources for further reading.
Comment: @ToddWilcox - no, it doesn't *have* to be a wide vib. Imagine wanting a top string E, 12th fret. Press, play, vib. Fine. But another way would be to press *fret 11* and bend so you play an E. That can have vib. applied by releasing slightly, or more, then bending back to original. So now, the pitch at its highest, is the note you want to play, rather than the note you want to play bending upwards to produce vib. No reading material, sorry. Just started using it when teaching different vibs years ago. Give it a try, it makes sense when it's happening, although maybe it sounds weird.
Comment: I've done tons of bent vibrato. Because whether you bend a note or not, if you're sticking to it, you often want vibrato. But let's leave that aside. What about the question of whether the highest frequency heard by the ear during a wide vibrato is preferred by the brain when determining what pitch is being played? I'm very interested in that and I think it cuts right to the heart of what this question is about. How does the brain choose a pitch when it is technically being presented with several nearby frequencies in rapid succession?
Comment: @ToddWilcox - that's a corollary question to this. But just as we tend to perceive the highest note of a chord as part of the melody line, it must be the same phenomenon.
Comment: To me it seems the perception assertion is exactly what this question is about and without any reason to think this isn't merely speculation on your part, I have to downvote.


Interpreting log multiple linear regression, backtransformations?

Question: I'm investigating adherence to a special diet (that is scored from 0-18)  in relation to C-reactive protein level and am in the process of building multiple linear regression models:
To achieve a normal distribution, I log transformed CRP. Now I'm having issues interpreting my results:
Log(C-reactive protein) = intercept + diet score + age + gender (This is just my basic model and I will be adding variables later  ...)
My R output:
Call:
lm(formula = log_CRP ~ total_score + age + gender_T0,
    data = final_regression_table)

Residuals:
    Min      1Q  Median      3Q     Max
-8.6813 -0.2796  0.6229  1.4016  3.3035

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept)   -0.40926    1.33728  -0.306    0.760
total_score   -0.01755    0.03166  -0.554    0.579
age           -0.01537    0.01816  -0.847    0.397
gender_T0male -0.08077    0.14462  -0.559    0.577

Residual standard error: 2.415 on 1133 degrees of freedom
Multiple R-squared:  0.001141,  Adjusted R-squared:  -0.001504
F-statistic: 0.4314 on 3 and 1133 DF,  p-value: 0.7305

                      5 %       95 %
(Intercept)   -2.61068556 1.79216737
total_score   -0.06967919 0.03457092
age           -0.04526635 0.01451645
gender_T0male -0.31885146 0.15730319

Do I exponentiate the betas individually?
The geometric mean is exp (-2.61) = 0.073?
So can I say that a one unit increase in diet score is expected to decrease CRP by exp(-0.40926) =  diet score * 0.9326 (keeping age and gender constant)?
Would the standard error also be exponentiated?
would the confidence intervals be exponentiated? so they would range from 0.93 to 1.035??
& this would mean that I cannot reject null hypothesis as CI cross 0?
Answer: Short answer - yes.
The logic here is that if we say ln(y)=a+b*x+u (this is simple linear regression but applies just the same to multiple linear regression) and defining $y_1$ and $y_2$ as follows:
$ln(\hat{y}_1)=a+b*x$ and $ln(\hat{y}_2)=a+b*(x+1)$ for some fixed x,
then the relative change in y is
$\hat{y}_2/\hat{y}_1=exp(a+b*x)/exp(a+b*(x+1)=exp(b)$
In your case, as you said, a unit increase in total diet score means that the level of protein is 0.98 times as high, or each unit increase in diet score reduces the level of protein by 2%.
The interesting thing you'll notice about the transformed confindance intervals is that usually, the coefficient is the midpoint of the confidence interval. For total diet score, the untransformed 95% confidence interval is:
$CI=[-0.01755-1.645*0.03166, -0.01755+1.645*0.03166]=[-0.070,0.035]$
and obviously, the coefficient -0.01755 is its midpoint.
But the transformed interval is:
$CI=[exp(-0.070),exp(0.035)]=[0.933,1.035]$
and the transformed coefficient 0.983 is not the midpoint. This also means you can't just transform the standard errors because they aren't symmetric. This is really important because the reason why the log transformation achieves normal distribution is because the original distribution is essentially:
$y=exp(a+b*x+u)=e^a*e^{b*x}*e^u$
And it's u that is normally distributed, so $e^u$ clearly isn't.
You indeed can't reject the null. You can see this from the p-value of 0.579 for the untransformed coefficient. You can also see it in the transformed CI which contains the value 1.
Hope this helps at all!


How to set up a text format that replaces the tokens?

Question: In the custom Drupal 8 block, there are no tokens.
<code>/admin/structure/block/block-content
</code>
How to set up a text format that replaces the tokens ?
I need to use in a custom block, the title of the current page, the creation date of the current page, ...
Comment: I expect it's the same way you use them with anything else; set up a text format that replaces tokens, then use that text format for the block body
Comment: @Clive Thank you. So how to set up a text format that replaces the tokens?
Comment: https://www.drupal.org/project/token_filter is still in beta but I'd imagine works well enough to use
Answer: Token Filter is a very simple module to make token values available as an input filter.
This doesn't mean that all tokens will work in every location. For example, if you use a [node:field_foo] token in the text of a block, the token system will not know which node you are referring to and will not replace the token.
It is up to you when you are implementing this module to be aware of the context for token usage and use them appropriately
https://www.drupal.org/project/token_filter


Possible to use drush to list overrides for all features?

Question: I believe that drush features-diff will list the overrides for a specific feature and that drush features-list will list all features. Is it possible to list all of the overrides for all features, perhaps by piping the results of drush fl to drush fd?
If so, how would one pick up the second field from drush fl to pipe to drush fd? Or, is there a better way to do this?
Comment: Running drush fd with no argument will return a list of overridden features-- I take it that this is not what you want, and that instead you want a list of all the actual changes to the code?
Comment: `drush fda -y` is the best answer for this one now, no question in my mind
Answer: In the current version of Drush, you can show a list of all features and their override state with (both short and long versions of commands shown, with and without the "-y" flag to skip confirmation questions):
$ drush features-list
$ drush fl

If you want to show only the overridden features:
$ drush features-list | grep -E "Overridden|Needs"
$ drush fl | grep -E "Overridden|Needs"

To show everything that has been overridden for all features:
$ drush features-diff-all
$ drush fda -y

To update all features to their currently overridden state:
$ drush features-update-all
$ drush fua -y

To revert all features to their default state:
$ drush features-revert-all
$ drush fra -y

Comment: can't edit cause it is less than 6 characters but `drush fl | grep grep -E` should be `drush fl | grep -E`
Comment: Thanks @powpow12.  I fixed the typo.
Answer: Just to share or whatever -- I use it all the time, and I would've loved to come across this tip when I was a noob , so...
I run:
drush fl | grep -E "Overridden|Needs"

...And, I added an alias to my drushrc.php to make it even quicker to call upon:
$options['shell-aliases']['flovr'] = '!drush fl | grep -E "Overridden|Needs"';

That's all, hope it helps someone!  (Also, "first time / long time," so if I've done wrong here, please be gentle :) )
Answer: I think what you are missing is xargs (available on Mac and Linux, at least).  Also, the magic numbers in your cut command are not reliable; use sed instead.  It is hard to tell, but I think that drush is outputting tabs as well as spaces, hence the [:space:] character class in the following:
$ drush fd | grep -E 'Overridden[[:space:]]+$' \
| sed -E 's/[[:space:]]*Enabled[[:space:]]*Overridden[[:space:]]*//' \
| sed -E 's/.*[[:space:]]//' \
| xargs drush fd

Answer: I'm sure it's possible by piping the results of drush fd or drush fl to grep, which could be used to extract the feature name, then piping that to drush fd, but that is no simple task.
If you're using git, another option is, on a clean working directory, run drush fua and then git diff. You can then run git reset --hard HEAD to get back to where you were. A workaround, but possibly simpler.
Comment: If it is possible with drush, then I should be getting close.

drush fd | cut -c28-51 | tail -n +2

gives a list of features that have been overridden without any of the other fd output columns and without the first row title.

However, I can't find a way to pipe that result to drush fd in a way that would give me the detailed results for all overridden features.

Is it possible?
Answer: If you'd like to show the code difference for all enabled features not in their default state, use fda command:
drush features-diff-all --force

--force Bypass the confirmations. This is useful if you want to output all of the diffs to a log file.

Other option is to use Features Diff module for that.

This is a simple modules used to view the diffs of a single or all features modules.

To list all Overriden feature modules by parsing the output of feature-list, the syntax can be:
drush fl --status=enabled | grep -o "\S\+\s\+Enabled.\+" | grep "Overridden"

To have both Overridden and Needs review, use: grep -e "Overridden" -e "Needs review" instead.
To get the list of modules, filter by: cut -d' ' -f1.
For longer name of modules, increase COLUMNS variable as names can be cut off.
So to pipe all features into feature-diff (fd), feature-revert (fr), feature-update (fu) or features cleanup (fcf), e.g.
COLUMNS=100 drush fl --status=enabled | grep -o "\S\+\s\+Enabled.\+" | grep -e "Overridden" -e "Needs review" | tee | cut -d' ' -f1 | xargs -t drush fcf

For running it in parallel (to speed it up), add -P4 -L4 into xargs.
Comment: Should `drush features-diff-all --force` be `drush features-diff-all -y`?
Comment: You may try `-y`, however there is a special `--force` option for it (see: `drush help features-diff-all`). I think the difference is that `--force` is suppressing the annoying confirmation message, where `-y` is still displaying it. So `--force` is useful when you're logging the differences to the log file.


solr. faceted search understanding

Question: I cannot understand result of faceted search.
I indexed two files:
1:
<add>
<doc>
  <field name="id">SOLR1000</field>
  <field name="name">Solr, the Enterprise Search Server</field>
  <field name="manu">Apache Software Foundation</field>
  <field name="cat">software</field>
  <field name="cat">search</field>
  <field name="cat">XXX</field>
  <field name="cat">XXX</field>
  <field name="features">Advanced Full-Text Search Capabilities using Lucene</field>
  <field name="features">Optimized for High Volume Web Traffic</field>
  <field name="features">Standards Based Open Interfaces - XML and HTTP</field>
  <field name="features">Comprehensive HTML Administration Interfaces</field>
  <field name="features">Scalability - Efficient Replication to other Solr Search Servers</field>
  <field name="features">Flexible and Adaptable with XML configuration and Schema</field>
  <field name="features">Good unicode support: héllo (hello with an accent over the e)</field>
  <field name="price">0</field>
  <field name="popularity">10</field>
  <field name="inStock">true</field>
  <field name="incubationdate_dt">2006-01-17T00:00:00.000Z</field>
</doc>
</add>

2:
<add><doc>
  <field name="id">3007WFP</field>
  <field name="name">Dell Widescreen UltraSharp 3007WFP</field>
  <field name="manu">Dell, Inc.</field>

  <field name="manu_id_s">dell</field>
  <field name="cat">electronics</field>
  <field name="cat">monitor</field>
  <field name="features">30" TFT active matrix LCD, 2560 x 1600, .25mm dot pitch, 700:1 contrast</field>
  <field name="includes">USB cable</field>
  <field name="weight">401.6</field>
  <field name="price">2199</field>
  <field name="popularity">6</field>
  <field name="inStock">true</field>

  <field name="store">43.17614,-90.57341</field>
</doc></add>

my simple facet request:
http://localhost:8983/solr/collection1/select/?indent=on&q=*:*&fl=name&facet=true&facet.field=cat

interesting part of response:
<lst name="facet_counts">
<lst name="facet_queries"/>
<lst name="facet_fields">
<lst name="cat">
<int name="XXX">1</int>
<int name="electronics">1</int>
<int name="monitor">1</int>
<int name="search">1</int>
<int name="software">1</int>
</lst>
</lst>
<lst name="facet_dates"/>
<lst name="facet_ranges"/>
</lst>
</response>

I don't understand what does it mean. If you could clearly explain it - I will very helpful.
Notably unclear
 <int name="XXX">1</int>

How Can I change  to
<int name="XXX">2</int>

Answer: Only one of your indexed items match cat=XXX. The fact that you have added it twice on one of them doesn't make a difference.
In your request to Solr you chose to facet on the field cat, so the response will include a lst element faceting on the cat field.
Every int element within that list contains acount of how many items match the different categories. So all the categories XXX, electronics, monitor, search and software match one item each.
If you would for example add <field name="cat">XXX</field> to the second item, you would get <int name="XXX">2</int> in the response.
Comment: Just to clarify, the counts that facets provide are the number of documents that contain the particular facet field/value combination (not the number of times the field/value combination occurs in the index.)

solr. faceted search understanding


The certificate request was submitted to the online authority, but was not issued. The request was denied

Question: I've a Hyper-V lab with few VMs. I'm trying to renew expired server certificate for one of my virtual machines which is running Windows Server 2019 (version 1809). I'm trying to renew the certificate from IIS:

Certificate authority is residing on domain controller which is running Windows Server 2016 (version 1607). When I go through the certificate renewal wizard via IIS manager it gives below error:

The certificate request was submitted to the online authority, but was
not issued. The request was denied.

What all I've tried so far:

Rebooted domain controller
Then rebooted the problematic machine
Then ran gpupdate command on the problematic machine
Answer: You cannot renew expired certificates, which is most likely the reason why the request was denied. You need to check the CA logs if you want to see the reason.


Find Domain of Log Function

Question: Need help determining the Domain of $$\log_2\left(2x+3\right)=\log_2\left(3x+4\right)-\log_2\left(3x+2\right)$$
Do not know if I should simplify first to get the domain, or to get the domain from the set logs that are in place?
Comment: Did you mean to have a log within the log (left-hand side), or is that a typo?
Comment: That was someones edit, I just meant one log on the left hand side.
Comment: I corrected it; is the question ok like this?
Comment: That is the original equation that I meant to input. I fixed it now so that the log function (3x+2) is subtracting.
Answer: This is an equation, and you can solve it. First of all we need to understand the single domains. That is easy. I will use the writing $\lg$ for the log base $2$.
$$\lg(2x+3)$$
This function exists iff $2x+3 >0$ hence $\boxed{x > -\frac{3}{2}}$.
$$\lg(3x+4)$$
This function exists if $3x+4 >0$ hence $\boxed{x > -\frac{4}{3}}$
$$\lg(3x+2)$$
This function exists if $3x+2 >0$ hence $\boxed{x >-\frac{2}{3}}$
Finally you can write th equation
$$\lg(2x+3) = \lg\left[(3x+4)/(3x+2)\right]$$
Where I used the well known property of the sum of log.
So now you can exponentiate in base $2$:
$$2x+3 = \frac{3x+4}{3x+2}$$
$$(2x+3)(3x+2) = 3x+4$$
$$6x^2 + 13x + 6 = 3x + 4$$
$$6x^2 + 10x + 2 = 0$$
Now you can solve it as a normal second degree equation
$$x = \frac{-10\pm\sqrt{100 - 48}}{12}$$
And check for the solutions, that don't have to be in contrast with the previous assumptions (necessarily).
Answer: I see an equation, not (just) a function?
In any case: $\log_a x$ (for a positive base $a$, different from $1$) is only defined for $x>0$. So for any logarithm appearing in your equation, the argument of the logarithm has to be strictly positive.
E.g. for $\log_2(3x+2)$ you need $3x+2>0 \Leftrightarrow x > -\tfrac{2}{3}$.
For all logarithms to be defined, you'll want the intersection of the 'domains' (sets where the different logarithms are defined), before simplifying (see below).

Notice that
$$\log x + \log x$$
is defined only for $x>0$ while (use $\log a + \log b = \log (ab)$)
$$\log \left( x^2 \right)$$
is defined for all $x\ne0$.
Comment: So the domain for the whole equation would be equal to x>-4/3, x>-2/3, x>-3/2?
Comment: I would reserve 'domain' for the context of functions; but your equation is well-defined for $x$-values satisfying $x>-4/3$ **and** $x>-2/3$ **and** $x>-3/2$; but you can simplify this to $x>-2/3$ (why?).
Comment: How could you say that $\log x^2$ is defined for all $x$??

$$\log(x^2) = 2\log(x)$$

!!
Comment: Not for all (please read what it says); for all non-zero $x$. The equality you write is only valid for $x>0$, more generally you have: $\log(x^2) = 2\log|x|$; or do you claim that $\log(x^2)$ is not defined for $x<0$...?
Comment: Downvote? I hope it's not because of my claim that $\log(x^2)$ is defined for all $x \ne 0$...
Comment: @StackTD For what concerns the down vote: I did not down voted you so I don't know who was.
Comment: So the domain could be simplified to x>-2/3 why?
Comment: @FourierTransform: alright thanks; I thought it could've come with your comment. Note though that properties such as $2\log x = \log x^2$ don't show / prove that $\log x^2$ would not exist for $x<0$, the equality just doesn't hold for some $x$-values (where one side exists, but the other doesn't).
Comment: @Revinous: If $x$ has to be larger than 3 values, then $x$ simply has to be larger than the largest of those 3 (and automatically satisfies the other conditions) - you see?
Comment: @StackTD Ok, thanks. This is only possible because of like bases? Right?
Comment: @Revinous No, watch out. You can only use most properties for log's in the same base, but the conditions on the argument (the domains) are independent of those bases.

Find Domain of Log Function


Comment only once per node

Question: I'm trying to get my users to post only once on each Product node... I'm kind of new to hooks and I'm not sure what else should I use for this.
What is the drupal way to do this?
Answer: You can use the Comment limit module.

Limits how many comments a user may post on a node.
  Adjustable on a per node type basis.
This module can be handy for instance when comments are used as "Reviews" and "Ratings" for products and a user may only review and rate a product once.

Comment only once per node