transpose(u) * Matrix * u

Question: I've seen this a couple of times during a machine learning lecture, for example in context of LDA, when looking at the Fisher Criterion. It can be expressed in two ways:
$$J(w) = \frac{(m_1 - m_2)^2}{s_1^2 + s_2^2}$$
And, formulated in the input space:
$$ J(w) = \frac{w^TS_Bw}{w^TS_Ww}$$
Where $S_B$ is the between-class covariance matrix and $S_W$ is the within-class covariance matrix. I understand that we can project a point $p$ into our new space like this: $w^Tp$, and I guess something similar happens here. But what exactly is the intuition of this calculation: $w^TS_Bw$? It looks like it yields large values when $w$ is perpendicular to the first eigenvector of our covariance matrix. But why? Im struggling to fully understand how to reconstruct this equation.
Thanks!
Comment: Some more context might help.
Comment: MathJax works in the title too, don't you know?
Answer: Let $\mu_1$ and $\mu_2$ be the means of the classes in the original space and let $m_1=w^Tm_1$ and $m_2=w^Tm_2$ be the means of the projected space.
$$S_b=N_1(\mu_1 - \mu)(\mu_1-\mu)^T+N_2(\mu_2-\mu)(\mu_2-\mu)^T$$
where the mean is  $\mu=\frac{N_1\mu_1+N_2\mu_2}{N_1+N_2}$
Hence $\mu_1-\mu=\frac1{N_1+N_2}(\mu_1-\mu_2)$ and $\mu_2-\mu=\frac{1}{N_1+N_2}(\mu_2-\mu_1)$
Hence $$S_b=(\mu_1-\mu_2)(\mu_1-\mu_2)^T.$$
$$w^TS_bw=(w^T\mu_1-w^T\mu_2)^2=(m_1-m_2)^2$$
Also, since $$S_w=\sum_{j=1}^2\sum_{i=1}^{N_j}(x_{ij}-\mu_j)(x_{ij}-\mu_j)^T$$
 Similarly,
$$w^TS_ww=\sum_{j=1}^2\sum_{i=1}^{N_j}(w^Tx_{ij}-m_j)^2=s_1^2+s_2^2$$

transpose(u) * Matrix * u


How can I convert a newline to a  tag?

Question: Given the following text in a textarea:
Line 1 stuff.. Line 1 stuff.. Line 1 stuff.. Line 1 stuff.. Line 1 stuff..

Line 2 stuff.. Line 2 stuff.. Line 2 stuff.. Line 2 stuff.. Line 2 stuff..

I want to convert the new lines to
 tags, not use the simple_format
 tags...
So I tried:
 str = str.gsub("\r\n", '
')

Problem is this is making two
 tags:

line 1

Line 2

How can make just one
 tag?
Comment: possible duplicate of [Rails 3: How to display properly text from "textarea"?](http://stackoverflow.com/questions/5852377/rails-3-how-to-display-properly-text-from-textarea)
Comment: [``](http://brainstormsandraves.com/articles/semantics/structure/#br) used this way isn't [semantic](http://webstyleguide.com/wsg3/5-site-structure/2-semantic-markup.html); use something more appropriate, such as a paragraph or [list](http://www.w3.org/TR/html401/struct/lists.html) element.
Comment: possible duplicate of [In Rails - is there a rails method to convert newlines to ?](http://stackoverflow.com/questions/611609/), [Ruby on Rails: How can i convert/replace every newline to ''?](http://stackoverflow.com/questions/8405175/)
Answer: Best way to do this is to use simple_format(str):

simple_format() is a helper function which will convert new lines
and carriage returns to
 and
...
 tags.

reference: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
Answer: str = str.gsub(/[\r\n]+/, "
")

This will turn any number of consecutive \r and/or \n characters into a single
.
Answer: This would mean that you have two occurrences of "\r\n". So you could sanitize the input or expect this situation in your regex.
Have a look at this: Ruby gsub / regex modifiers?
Answer: You have two line breaks in the input text. If you want there to be one
, just do:
str = str.gsub("\r\n\r\n", '
');

How can I convert a newline to a  tag?


Is there such a thing as a Harmonic key besides for Harmonic Aeolian?

Question: My understanding of the various modes is that, relative to the base note's natural major key:

Ionian is the same as natural major;
Dorian flats the third and seventh;
Phrygian flats the second, third, sixth, and seventh;
Lydian sharps the fourth;
Mixolydian flats the seventh;
Aeolian flats the third, sixth, and seventh (natural minor);
Locrian flats all but the prime and fourth.

I also understand that there's a concept of a Harmonic minor, in which the minor seventh is sharped (or, in other words, only the third and sixth are flatted). I further understand that there's a concept of a Harmonic major, in which the sixth - and only the sixth - is flatted.
Can these be applied to other modes, besides Aeolian and Ionian, respectively?
Regarding Harmonic minor: Since this obviously would only apply to keys in which the seventh is already flatted, this means that, in addition to Aeolian, only a Harmonic Dorian (flat third), Phrygian (second, third, and sixth), and Locrian (flat second, third, fifth, and sixth) would be possible. I don't count Harmonic Mixolydian here, since that's just the same as Ionian.
However, when you consider that the purpose of a Harmonic minor is to enable the dominant chord to be a major chord, rather than minor, then this picture changes a bit, since a major dominant requires that the fifth, seventh, and second all be not flatted. Therefore: the Phrygian mode requires sharping its second as well, making it into normal Harmonic minor. If Harmonic Locrian requires its fifth being sharpened, then it will devolve into normal Harmonic minor as well, and if not, then its fifth is already major. So either way, no new modes there.
That leaves Harmonic Dorian. This would entail flatting the third and nothing else. Is this actually a mode used? If not, is there a reason why not?
Regarding Harmonic major: Following the same logic as above, only modes with a sixth not flatted can have it flatted; excluding Ionian, this leaves Dorian, Lydian, and Mixolydian. Dorian wouldn't work, since flatting the sixth just gives a normal Aeolian scale. Lydian could technically work, but having a sharp fourth and flat sixth not only feels weird but also sounds horrendous. And then there's Mixolydian, which would have a flat sixth and seventh.
Narrowing it down further based on a normal Harmonic major yielding a minor fourth chord, Lydian would be impossible without flatting the sharped fourth, but a theoretical Harmonic Mixolydian would work just fine. As with the Harmonic Dorian above, is this a mode actually used, and if not, why?
Comment: What you are referring to as "Harmonic Dorian" (ie D E F G A B C# D) is actually just the melodic minor scale, so yes, it is used — very frequently as a matter of fact!
Comment: I understand the math behind *why* these modes are the way they are, but I find it fascinating that the theoretical Harmonic Dorian and Harmonic Mixolydian, when overlaid on each other, actually yield a normal Aeolian scale. So I guess another way to put it would be that Harmonic Dorian starts out Aeolian and ends Ionian, while Harmonic Mixolydian does the opposite.
Comment: Just like the melodic minor (ascending) starts off minor and ends with major.
Answer: Your approach to this investigation is really interesting, but it ultimately doesn't yield any new scales. The "harmonic Dorian" you posit is ultimately just an ascending melodic minor scale. However, there are several new scales generated if you approach mode in terms of the intervals between successive notes.
Your description of the seven church modes is accurate, but, in some ways, it's more useful to define mode in terms of rotations. Ionian is a whole step (W) followed by another W, then a half step (H), followed by W–W–W and then the final step is H. So, we could define Ionian as the interval succession WWHWWWH. Now, let's rotate this list of intervals one click to the left. In other words we'll make the second interval into the first, the third interval into the second, etc. and move what used to be the first interval so that it's at the end. Like this WHWWWHW. If you check, you'll see that this is the interval sequence of Dorian. Do it again and you get HWWWHWW, which is Phrygian. All of the church modes are created this way; the last rotation is HWWHWWW, which is Locrian. After that you just start over with Ionian again, that's why there are seven church modes (actually, in the Mediæval period, Locrian didn't exist, that's a modern invention, but whatever.
Ok, now let's changed Aeolian (Natural Minor) into harmonic minor. Aeolian is WHWWHWW, but when we raise the seventh note, that changes both of the last two intervals. Think of the Aeolian scale that starts on A: instead of moving HWW at the end, E–F–G–A, we have E–F–G#–A. The final interval is now a half step, and, more importantly, we created an entirely new step size between F and G# that is a half step larger than a whole step. The technical name for that is "augmented second," which I'll abbreviate as A. The harmonic minor succession of intervals, therefore, is WHWWHAH.
You're right about the original reason for using harmonic minor—it creates a leading tone that allows the dominant chords to resolve more strongly to tonic chords—but another way of looking at it is a scale with a unique interval in it. And, just like we did with the diatonic intervals above, we can rotate the intervals to generate new modes, which are usually called the "harmonic minor" modes. For instance, rotate it once and you have the second mode of the harmonic minor: HWWHAHW. Starting on B that would be : B–C–D–E–F–G#–A–B. Perhaps the most famous of these is the fifth mode of the harmonic minor (sometimes called Phrygian dominant) with the interval series HAHWHWW. For example, E–F–G#–A–B–C–D–E. These scales are fairly common in Industrial and Metal music. In other words, another way to answer your question is to create a series of modes that preserve the augmented second of harmonic minor instead of preserving the "raised seventh scale degree" of harmonic minor. Ultimately, it's far more fruitful in this form.
If you're curious, one can also create seven modes of the ascending melodic minor by the same method. In this universe, you don't usually use a different version of the scale for descending. The interval succession for normal melodic minor is WHWWWWH, and this can be rotated to get a somewhat less common set of seven modes.
Answer: First, some background:
Actually, your approach is my favorite analysis technique for scales. I find it much more convenient than the concept of modes, i.e. shifting (rotating) the tonal center of a particular scale to a different degree. Because I feel altering one note of a scale yields a scale that is somewhat similar to it but rotating it takes you to completely new territory. "Families" of scales are more readily understood in terms of alterations.
For heptatonic scales (scales that contain seven notes), we can do a much more complete analysis:
You have six degrees (other than the root): the second, the third, the fourth, the fifth, the sixth, and the seventh.
At first, let's stick with perfect fourth and perfect fifth. If we keep those constant, the second, the third, the sixth, and the seventh can be either minor or major. It gives us 16 scales (4 degrees to the power of 2 options):
<code>These four have a Phrygian flavor, they work well on Neapolitan chords,
that's why two of them ara named after that chord:

m2 m3 p4 p5 m6 m7 => Phrygian
m2 m3 p4 p5 m6 M7 => Neapolitan minor
m2 m3 p4 p5 M6 m7 => Dorian b2 / Phrygian #6
m2 m3 p4 p5 M6 M7 => Neapolitan major

These four have an eastern flavor because they sound like the popular
Middle Eastern Hijaz family of maqams:

m2 M3 p4 p5 m6 m7 => Phrygian dominant
m2 M3 p4 p5 m6 M7 => Double harmonic
m2 M3 p4 p5 M6 m7 => Mixolydian b2
m2 M3 p4 p5 M6 M7 => Ionian b2

These four form the minor scale family. Western music likes to alternate
between them almost freely:

M2 m3 p4 p5 m6 m7 => Natural minor / Aeolian
M2 m3 p4 p5 m6 M7 => Harmonic minor
M2 m3 p4 p5 M6 m7 => Dorian
M2 m3 p4 p5 M6 M7 => Melodic minor

And finally, these four form the major scale family:

M2 M3 p4 p5 m6 m7 => Mixolydian b6
M2 M3 p4 p5 m6 M7 => Harmonic major
M2 M3 p4 p5 M6 m7 => Mixolydian
M2 M3 p4 p5 M6 M7 => Major (Ionian)
</code>
You obtain 16 more scales by sharpening the fourth. They're not all very usable but the Lydian (Ionian #4), the Dorian #4 and the Hungarian Gypsy (Aeolian #4) are nice and popular.
Flattening the fifth yields 16 more. They're harmonically quite unstable but some of them are melodically usable and somewhat popular: Locrian (Phyrigian b5) and Aeolian b5 for instance.
Although less usable, you have some more options like flattening the fourth (and optionally the fifth) of Phrygian flavored scales (example: super Locrian = Locrian b4), or augmenting the fifths of scales that end with a M6 and M7 for some quasi-whole tone scale flavor.
Back to the question:
As you can see, a few of these scales have the word "harmonic" in their names. The common point is that they all have a minor sixth and a major seventh in their structure. Neapolitan minor is not named that way but it certainly has some of the others' character.
One can also observe that augmented second gives such a character to a scale even if it's not between the sixth and the seventh. The Phrygian dominant (5th mode of harmonic minor), Mixolydian b2, Ionian b2, and the aptly named Double harmonic all have a similar character. So do the Dorian #4 (4th mode of harmonic minor) and Hungarian Gypsy scales.


How to execute test from inside a class in pytest?

Question: I am trying to run a test method which is inside a class in Python using pytest framework.
Not sure what is going wrong, but the test is not getting picked. I made sure the package name, module name, class name and function name starts with "test".
There is no content inside init.py, I am not sure if I need to include anything inside this file to make sure the test(s) are picked which are under the class.
The interpreter I am using is shown in the screenshot. Also, I have added a screenshot showing the code so it becomes easier to understand the directory structure.
I visited several blogs and this, but none of them helped me resolve this.
Could you please help?
Answer: To test a function in a class with pytest, we can use this command:
$ pytest -v /path/to/test_file.py::ClassName::test_function_name

remember use "::"
Comment: this is what i needed. go get some more reputation
Answer: By default, pytest expects test classes to be named in CamelCase: TestDemo, not test_demo. The rest of your names follow the correct schema for the defaults, so if you change the class name to TestDemo, pytest should be able to find it.
pytest docs on test discovery: https://docs.pytest.org/en/stable/example/pythoncollection.html
Comment: @Prabodh: `CamelCase` class names also happens to be the naming convention recommended in [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) — so you should be doing things that way, regardless.


Gerar numero sequencial de 8 digitos

Question: Preciso gerar um numero sequencial de 8 digitos seguindo o banco..
Tenho a coluna código na tabela orcamento, possui o valor de ex: 1800000001 onde 18 é o ano e o restante é um numero sequencial, preciso que eu verifique no sistema qual o ultimo orcamento cadastrado e crie um numero sequencial seguinte, no exemplo é 1800000001, quero que gere o codigo 1800000002 e assim sucessivamente, contanto que quando o ultimo numero atingir dois digitos ele substitua um 0, quando 3, dois zeros, ex: 1800000099, esse numero após o ano tem que conter 8 casas.
Comment: Qual o problema?
Comment: O problema é que não sei como gera o numero dessa forma..
Answer: Para gerar um padrão em PHP seria:
$ultimoNro = '1800000001';
$ultimoNro = substr($ultimoNro, 2);
$proximoNro = $ultimoNro + 1;
$proximoNro = date('y').str_pad($proximoNro, 8, '0', STR_PAD_LEFT);
echo $proximoNro;

Answer: Faz um SELECT para saber qual o último código inserido:
$sql="SELECT codigo FROM sua_tabela ORDER BY codigo DESC LIMIT 1";

$ultimo_resultado='1800000001';
$ultimo_resultado=intval($ultimo_resultado)+1;
//1800000002

O primeiro número, você pode verificar no sistema se existe algum registro, caso não exista vc define manualmente mesmo usando um if, subsequentemente serão definidos automaticamente.
$ano=date('y');//pega o ano corrente no formato 19, como no seu código
if(!resultados){//verifica se não existem resultados do sql
    $primeiro_codigo=$ano.00000001;//cria o primeiro, no caso 18
}else{//se tiver resultados
    $ano_atual=substr($ultimo_codigo,0,2);//pega o ano atual do ultimo código
    if($ano_atual != $ano){//compara com o ano corrente
        $primeiro_codigo=$ano.00000001;//se for diferente cria o código novo, quando passar para 2019
    }
 }

Comment: Editei a resposta
Comment: Ótimo meu amigo, isso que precisava, muito obrigado!
Comment: Eu quem agradeço por poder ajudar.
Comment: Sim, pensei desta mesma forma, mas e quando virar o ano, que não vai encontrar nenhum codigo com o ano 19? Como criarei esse codigo de x digitos?

Gerar numero sequencial de 8 digitos


Programa nao para o laço, mesmo digitando a tecla para interromper!

Question: #include <stdio.h>
#include <string.h>

typedef struct {
    int codigo;
    char departamento;
    char nome[30];
    float salario;
}DadosFuncionario;

int main () {
    FILE *fp;
    DadosFuncionario funcionario;
    char nome_arquivo[]= "saida.txt";
    char sair;

    fp = fopen(nome_arquivo, "w");

    do {
        printf("Codigo do Funcionario:\n");
        scanf("%d", &funcionario.codigo);

        printf("Departamento:\n");
        scanf(" %c", &funcionario.departamento);

        printf("Nome:\n");
        scanf(" %[^\n]s", funcionario.nome);

        printf("Salario:\n");
        scanf("%f", &funcionario.salario);

        fwrite(&funcionario, sizeof(DadosFuncionario),1,fp);

        printf("Deseja sair (s/S):");
        scanf("%c", &sair);

        }while(sair!= 's' && sair!='S');

        fclose(fp);
    return 0;
}

Comment: Creio que você está tendo problema com caractere ENTER da entrada anterior que não é consumido e permanece  no buffer do teclado. Você pode descartar este '\n' com: while((sair = getchar()) != '\n' && sair != EOF)
   /* descarta o caractere lido */ ;. Existem outras maneiras de fazer.
Comment: De uma maneira mais simples coloque um espaço antes do %c: scanf(" %c", &sair); que o caractere de nova linha será consumido.
Answer: Em vez de ser && no while, deverá ser ||
#include <stdio.h>
#include <string.h>

typedef struct {
    int codigo;
    char departamento;
    char nome[30];
    float salario;
}DadosFuncionario;

int main () {
    FILE *fp;
    DadosFuncionario funcionario;
    char nome_arquivo[]= "saida.txt";
    char sair;

    fp = fopen(nome_arquivo, "w");

    do {
        printf("Codigo do Funcionario:\n");
        scanf("%d", &funcionario.codigo);

        printf("Departamento:\n");
        scanf(" %c", &funcionario.departamento);

        printf("Nome:\n");
        scanf(" %[^\n]s", funcionario.nome);

        printf("Salario:\n");
        scanf("%f", &funcionario.salario);

        fwrite(&funcionario, sizeof(DadosFuncionario),1,fp);

        printf("Deseja sair (s/S):");
        scanf("%c", &sair);

        }while(sair!= 's' || sair!='S');

        fclose(fp);
    return 0;
}

Comment: Neste caso basta digitar ou 's' ou 'S' que continuará executando o loop. Tem que ser && mesmo.
Answer: Coloque um espaço antes do %c
printf("Deseja sair (s/S):");
scanf(" %c", &sair);


self-adjoint operator with positive spectrum is positive

Question: I have found many threads about the inverse statement but none for this: (Part of exercise 6.24 in Brezis)
Let $T$ be linear, self-adjoint operator on a Hilbert space and assume that the spectrum of $T$ fulfills $\sigma(T) \subset [0,\infty)$. Prove that the operator is positive, i.e. $(Tu,u)\geq 0$.
So from know on I will set $\lambda < 0$ be a real number outside the spectrum, i.e. $T-\lambda I$ will be one-to-one and onto. I have tried the following:

Starting with $(Tu,u)$, we set $v$ such that $Tv-\lambda v = u$ (exists by assumption), and we have to prove that $(T^2v-\lambda Tv, Tv-\lambda v) \geq 0$. Now we can isolate a few interesting terms but I can't show positivity
To me it looks like the proof should go like this: We have some property which is known to be positive and somewhere inside this term we have a factor of $-\lambda(Tu, u)$ and if we assume $(Tu,u)$ (and thus $-\lambda(Tu, u)$) to be negative, we will get a contradiction for $0>\lambda \to 0$. I started with $0\geq (Tu-\lambda u, Tu- \lambda) = \|Tu\|^2 - 2\lambda (Tu, u) + \lambda^2 \|u\|^2$ but this did not get me anywhere.
Answer: In the context of Brezis' book, this is already proven in the text. In Proposition 6.9 he proves that, with
$$
m=\inf\{\langle Tv,v\rangle: \|v\|=1\},\ \  M=\sup\{\langle Tv,v\rangle:\ \|v\|=1\},
$$
one has $\sigma(T)\subset [m,M]$, and $m,M\in \sigma(T)$. In your case $\sigma(T)\subset[0,\infty)$, so $m\geq0$.
Comment: I am not assuming that: I take $\lambda$ to be in the resolvent set, which is defined as the set of real numbers such that $T-\lambda I$ is bijective (i.e. one-to-one and onto). But yes, I completely overlooked that I can use that $m \in\sigma(T)$, thanks!
Comment: You are right. I have removed that sentence.


Why "De Morgan's laws", Why not De Morgan's theorems?

Question: While we can prove both De Morgan's terms, they are called "law/rule" in many textbooks, references and also Wikipedia(+)! why law?

Aren't those terms theorem, in fact?
Comment: DeMorgan was the great-great-...-great grandfather of Dredd. And as we all know, Dredd is THE LAW.
Comment: Some older theorems where rather seen as absolute truths, specially those in the heart of logic. De Morgan's Laws are an example.
Answer: The truth is that many results have non-standard names, like the ones you mention, the division algorithm, and Bertrand's postulate (which was not proved by Betrand). Then there are conjectures that will probably carry their names forevermore even after being proven (like Riemann's hypothesis); conjectures that were called "theorem" (like Fermat's last theorem, last because it was one of the few unproven results by Fermat that Euler wasn't able to prove, and withstood centuries of work). The strict theorem/lemma/corollary division is just fiction, there are people who prefer to call everything "proposition," there are plenty of lemmata which turned out much more important than the (now almost forgotten) results they led to. Mathemathics is a human endeavor, with plenty of quirks and vagaries.
Answer: The answer here is really helpful: Difference between a theorem and a law.  I believe you are right though!
From that link: "Theorems are results proven from axioms, more specifically those of mathematical logic and the systems in question. Laws usually refer to axioms themselves, but can also refer to well-established and common formulas such as the law of sines and the law of cosines, which really are theorems." -user4594


Dependent product variation type

Question: I have a question.
My site sells tours.
For each tour(product) a user can choose a flight  and some hotel rooms.
Example tour1:
user can choose: flight1 and flight2.
user can choose: double rooms and/or single rooms.
If the user choose flight1 then ->  double rooms costs 50, single rooms costs 100(a).
If the user choose flight2 then -> double rooms costs 150, single rooms costs 200 (b).
I have 3 dependent variation types(flight, doubleRoom, singleRoom). What I want is:
if the user choose flight1 I only show double rooms = 50, single rooms  =100 (rooms(a));
if the user choose flight2 I only show double rooms = 150, single rooms=200 (rooms(b)).
Flights and rooms have  a taxonomy terms called 'solution':solution1, solution2 ecc..
I think that a way should be use rules, with event 'After adding a product to the cart' but I can't write the condition('if flight  choose solution1') and the action(set visible=true where rooms solution= solution1).
Can someone help me please??
Thanks in advice
Answer: I am looking for this for Drupal 8, however it appears that the module Commerce Product Add-on provides a solution for Drupal 7 (I have not tested it).

Commerce Product Add-On allows users to attach products as options to
  the add to cart form of another product. This is particularly useful
  for things like event sponsorship, optional accessories, and other
  up-sells.

Dependent product variation type


Using Elasticsearch java config client in Spring Batch

Question: I am trying to write a custom writer of elasticsearch which would index data in a spring batch implementation.
I could find the below code as Java config for the elasticsearch.
Anyone who has used this, Can please share where to call this configuration?
@Configuration
   @EnableElasticsearchRepositories(basePackages = "org/springframework/data/elasticsearch/repositories")
        static class Config {

        @Value("${esearch.port}") int port;
        @Value("${esearch.host}") String hostname;

        @Bean
        public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(client());
         }

        @Bean
        public Client client(){
            TransportClient client= new TransportClient();
            TransportAddress address = new InetSocketTransportAddress(hostname, port);
            client.addTransportAddress(address);
            return client;
        }
   }

Answer: The code that you listed above is basically your implementation details of a - Transport Client element pointing to an instance of Elasticsearch Server i.e. this defines your persistent layer by using Spring Data.
This code will be used by your elasticsearch repositories i.e. repositories that you define by extending - ElasticsearchRepository from Spring Data.
You need to edit @EnableElasticsearchRepositories  in code listed by you to actually point to package where you are keeping your repository definitions - no other call would be needed.
When you are going to write/index data to elasticsearch, you work with ElasticsearchRepository interface and you need to define your own repositories and these repositories work with instances as per listing in your code.
Hope it helps !!


Android - Scandit - java.lang.UnsatisfiedLinkError

Question: Scandit SDK started crashing when initializing.  It was working fine, but it just started erroring out.  I have tried googling around for a solution, and I've tried every suggestion. But nothing seems to fix it. It doesn't seem to be a proguard issue and the build path seems correct.
<code>E/AndroidRuntime(25471): java.lang.UnsatisfiedLinkError: Couldn't load scanditsdk-android-3.5.3 from loader dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.android.example-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.android.example-1, /vendor/lib, /system/lib]]]: findLibrary returned null
E/AndroidRuntime(25471):    at java.lang.Runtime.loadLibrary(Runtime.java:358)
E/AndroidRuntime(25471):    at java.lang.System.loadLibrary(System.java:526)
E/AndroidRuntime(25471):    at com.mirasense.scanditsdk.ScanditSDKBarcodePicker.initializeRecognitionEngine(ScanditSDKBarcodePicker.java:1364)
E/AndroidRuntime(25471):    at com.mirasense.scanditsdk.ScanditSDKBarcodePicker.<init>(ScanditSDKBarcodePicker.java:333)
E/AndroidRuntime(25471):    at com.mirasense.scanditsdk.ScanditSDKBarcodePicker.<init>(ScanditSDKBarcodePicker.java:255)
E/AndroidRuntime(25471):    at com.venueplus.android.VPScannerActivity.onCreate(VPScannerActivity.java:99)
E/AndroidRuntime(25471):    at android.app.Activity.performCreate(Activity.java:5231)
E/AndroidRuntime(25471):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(25471):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
E/AndroidRuntime(25471):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(25471):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(25471):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(25471):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(25471):    at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(25471):    at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(25471):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(25471):    at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(25471):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(25471):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(25471):    at dalvik.system.NativeStart.main(Native Method)
</code>
Help is much appreciated
Answer: After talking with a Scandit engineer, it turns the problem was that I didn't have a directory named "armeabi-v7a" in addition to "armeabi".  So the libscandit-sdk-android-3.5.3.so file must be present in both subfolders.
Hope this helps someone
Comment: TY, you save me dozen hours.


Computational complexity comparison between MINLP and MILP

Question: Can someone please explain the computational complexity of MINLP and MILP, though both are NP-Hard. What is the advantage of having an MILP formulation over MINLP formulation for a same optimization problem?
I have an MINLP problem of 32 binary integer variables with some nonlinear constraints. I perform exact linearization for some of the constraints and employ piecewise linear approximation for the constraint exact linearization is not possible. But the MINLP formulation now have additional 32 binary integer variables (because of SOS type 2 variables).
Can you please explain which one I should prefer in terms of computational complexity.
Answer: IP problems are generally solved by using a relaxation to the (N)LP formulation. Branch and bound algorithms and cutting plane algorithms utilize a relaxation of some sort.
Non-Linear Programming is much harder than LP, especially when the feasible region is non-convex, as it can be hard to determine which points are actually optimal. So if you have a choice, a MILP is probably a better choice. The constraints will be easier to deal with, and the LP relaxation will give you an LP optimum.


kthreaddi process is causing a high CPU usage

Question: I'm using REDHAT 7.6 as an OS on my server and top command shows high CPU usage from kthreaddi process without obvious reason, now my solution is down, and also my Fusion middleware (I'm using ORACLE as database )
any solutions
Answer: I experienced this problem a few days ago, the quickest solution I could get was the following:
Use the following command:
ls -l /proc/<PID_of_process>/exe

This command shows the position where the process is running.
Create this folder.
Remove all the permissions for all users:
chmod o-rwx /tmp/<name_of_folder>

Then kill the process:
kill -9 <PID_of_process>

Comment: In my case, it had a parent process that name was numeric.

First i found the directory with your first command. Then killed the parent process and finally killed the kthreadd processes.

Thanks dear Carlos
Answer: Kindly run below one liner bash shell script inside crontab every minute and it will kill the virus in a scripted way.
kill -9 $((ps -aux | grep -i 'kdevtmpfsi\|kinsing\|kthreaddi') 2>/dev/null |grep -v grep |awk '{print $2}')


Validation for not a valid Integer value

Question: If a string comes then these validation is not enough.
import play.data.validation.Constraints.Max;
import play.data.validation.Constraints.Min;
import play.data.validation.Constraints.Required;

@Required
@Min(1)
@Max(500)
private Integer capacity;

how i am checking
Set<ConstraintViolation<Object>> violations = (Set) play.data.validation.Validation.getValidator().validate(object, Default.class);
        for (ConstraintViolation<Object> violation : violations) {
            System.out.println(violation.getPropertyPath().iterator().next().getName());
            System.out.println(violation.getMessageTemplate());
        }

soppose user sends "govind" in place of Integer value then its give the execution exception
is there any way to do check via @annotaions?
or any another suggested way?
i am getting error

play.api.Application$$anon$1: Execution exception[[RuntimeException:
  com.fasterx ml.jackson.databind.exc.InvalidFormatException: Can not
  construct instance of in t from String value 'govind': not a valid Integer
  value
Comment: think you have option to use pattern(java.lang.String regex) method to find out whether its string or fully integer. Please look this url for more info:https://www.playframework.com/documentation/2.0/api/java/play/data/validation/Constraints.html
Answer: For positive integers try
@Pattern(value = "[0-9]+", message = "The value must only contain digits.")

Comment: Does the Max work? What happens if user sends 30000? How do you invoke the validations?
Comment: after adding `pattern`  Max and Min also stop working
Comment: And without it? Technically, validation annotations work by throwing exceptions at some point - the question is only which exception is thrown and how it is handled.
Comment: Ah, sorry, my bad. The parameter is called "value", not "regexp": https://www.playframework.com/documentation/2.0/api/java/play/data/validation/Constraints.Pattern.html   Changed the code.


Quadrature Error for Trapezoidal Rule

Question:
Question:
If the trapezoidal rule is used to approximate the integral of the function $f$ over the interval $[a,b]$ with 201 evenly spaced dissection points, estimate the quadrature error for
$$\int_0^1log(1+x^2)dx$$

For this style of question would I use the formula
$$error \le \sum_{i=1}^{N} \frac{-1}{12}\left(\frac{b-a}{N}\right)^3 f''(c_i)$$
to find the error?
Where N is the number of equal length intervals, [a,b] is the full inteval, $c_i$ is the midpoint of each interval and $f$ is $log(1+x^2)$.
If this is the case, how do I find $c_i$?
Answer: Instead of adding up the estimates for the local errors, we can use the standard expression for the global error, which in general is
$$-\frac{(b-a)^3}{12N^2}f''(c),$$
where $c$ is a number between $a$ and $b$. In our case,  $a=0$ and  $b=1$. The number $N$ of subintervals is $200$.
Now we need an estimate for $f''(c)$. The second derivative is, I think, $\dfrac{2(1-x^2)}{(1+x^2)^2}$. As $x$ increases, the numerator is decreasing, and the denominator is increasing. Thus $f''(x)$ is steadily decreasing. It is equal to $2$ at $x=0$,  so $0\le f''(x)\lt 2$.
Remark: Or else use the local errors, and add them up. Since the second derivative is everywhere positive and $\lt 2$, the local error is always negative and $\lt \dfrac{1}{12}\cdot\dfrac{1}{(200)^3}\cdot 2$ in absolute value, so in absolute value the total error is $\le 200\cdot \dfrac{1}{12}\cdot\dfrac{1}{(200)^3}\cdot 2$.
Typically, the error estimates produced by this kind of calculation are unduly pessimistic. One can ordinarily get more useful information by comparing $T_{100}$ with $T_{200}$. The number $T_{100}$ is typically computed on the way to computing $T_{200}$, so it involves no additional cost.
Comment: Thank you, the local and global errors were confusing me a bit but I think I get it now!
Comment: You can use the "local" errors version. The $N$ individual errors are bounded as given by your formmula, so their sum is $\le N$ times the maximum local error. For that maximum, maximimize the second derivative as I did.

Quadrature Error for Trapezoidal Rule


image of integer in $(Z/p^nZ)^\times$

Question: This is a homework problem, I don't think I understand what the problem is saying.
Let $ p $ be an odd prime and $ n \ge 1 $ an integer. Prove that if $ a $ is an integer such that $ a-1 $ is divisible by $ p $ but it is not divisible by$  p^2 $ then the image of $ a $ in the multiplicative group of $ Z/p^nZ $ is $ p^{n-1} $.
Say $p=7$, $a=8$, then  $ 8 $ is an integer such that $ 8-1=7 $ is divisible by $ 7 $ but it is not divisible by$  7^2=49 $, then according to the problem, the image of $8$ in $(Z/7^2Z)^\times$ is $7$.... but $7 $ is not even in $(Z/7^2Z)^\times$.
Please help me understand what the problem is saying.
The problem in its official form (by the professor) is attached below
Comment: There indeed is something wrong with the problem. Are you sure you've copied it correctly? Perhaps it was meant to ask about the order of $a$?
Comment: @Wojowu I have attached an image of the original problem, please take a look.
Comment: It very much seems to me like the problem is misphrased, I would recommend you ask your professor about this in person or via email.
Comment: @Wojowu Thanks,I will do that. I was worry that I might be missing something obvious, so that I post it here first
Comment: Don't worry. Missing something obvious is something one should always consider, but it was not the case this time :)
Answer: I believe the problem should read "the ... order of the .... image of $a$ is $p^{n-1}$".
It that case, then one possible method is by induction.(but that's not the point of this post)
Please don't post solution (in case you want to) until next week, as this is a homework problem.

image of integer in $(Z/p^nZ)^\times$


Was Bach the first to use thumbs on a keyboard?

Question: This question reminded me of a claim that I've heard before, namely, that J. S. Bach was the first keyboardist to utilize the thumbs in his playing technique. I'm not sure where I've heard this, but believe I've seen it in several places, always unsourced. The claim sounds incredible, given the age of keyboard instruments (some organs even date to BC), that no one had ever thought to try using their thumbs before. But perhaps I am biased by the perspective of modern technique.

What is the source for this alleged fact? Is it reliable or is it just rumor and hearsay?
Do we have any knowledge of thumbs being used in keyboard technique prior to Bach?
For that matter, how did people even play a keyboard without thumbs? I can't imagine how that would work. (possibly out of scope for this question)

Original sources, or modern scholarly research, are preferred, where possible.
Comment: It would be hard to say if he was the first (such a long time ago) but I have read that most pre-Bach keyboardists played scales by crossing the middle finger over the ring finger or pinky and that thumbs were once considered an unwieldy blunt digit and the use thereof was avoided.
Comment: Sounds a bit like the guitar. Purists would never use a thumb for fretting, but someone came up with the idea, which actually worked (assuming one has a long thumb!) subsequently lots of players use it.
Comment: @Tim That might depend on genre. I'm not sure if anyone playing rock guitar could be described as a "purist", since rock technique is almost universally personalized. Also, some of the biggest names in the history of rock guitar have fretted with their thumbs (Jimi Hendrix!!, Jimmy Page, Stevie Ray Vaughan), so any discussion of rock technique, pure or otherwise, would *have* to at least mention, if not outright recommend, thumb fretting.
Answer:
Rumour or hearsay, I think, abetted by C.P.E. Bach.
Yes. Evidently Santamaria's Arte de tañer fantasia from the 16th century gives examples of quick scale passages using the thumb, and also warns about using the thumb on black keys except when paired with an octave. I'm getting this secondhand (Historical Harpsichord Technique: Developing La douceur du toucher, Yonit Lea Kosovske, 2011, pgs. 121 and 126), as, while IMSLP has the original Arte de tañer, I'd have to try translating the writing and deciphering movable type examples - not easy. (My second language isn't Spanish.)
Except for the simplest music, it probably wouldn't work. I think you'd be hard-pressed to play, say, Bull or Sweelinck without the use of the thumb (especially chordal passages).

Claims of this nature are properly subject to a certain skepticism, I think - Alessandro Scarlatti (of the previous generation to Bach's) specified the thumb quite liberally for his first Toccata. (IMSLP has the Shedlock edition, which is fairly assiduous about following the manuscript.)
Comment: "My late father told me about having heard great men in his youth who did not use the thumb except when it was necessary for large stretches. Since he lived at a time in which there gradually took place a quite remarkable change in musical taste, he was obliged to think out a much more complete use the fingers, and especially to use the thumb (which apart from other uses is quite indispensable especially in the difficult keys) in such a manner as Nature, as it were, wishes to see it used. Thus it was raised suddenly from its former idleness to the position of the principal finger.29"
Answer: (Sorry, this was to be a comment continuing on the previous thread, but I wanted to include pictures)

This picture was used in a video class I've seen, by Prof. Craig Wright from Yale where he corroborated the perspective that primite (late medieval/early renaissance context) keyboard playing was done without using the thumbs. He also referred to what he called the "3 over 3" method used afterwards until Bach's time, which seems to be the same thing as the finger crossing mentioned by Rockin above.
Another interesting source relating to this subject is Couperin's "Art of Playing the Keyboard" (L'Art the Toucher le Clavecin). This 1716 work was a reference during the Baroque and was commended by Bach himself (Christopher Hogwood, The Keyboard in Baroque Europe). Couperin stressed the use of the index, middle and ring fingers, using the thumb only occasionally in very specific situations. Here's a scale fingering from this book:

Another source that corroborates this view is the "amateur" harpsichordist (he recorded the integral Scarlatti sonatas in his custom built harpsichord!) John Sankey. His site has a wealth of information and references about ancient keyboard playing, specially the harpsichord.
Apparently this "3 finger" approach was state of the art until C.P.E.Bach's "True Art of Playing the Harpsichord", where, thumb crossing is given some relevance. Quoting from Sankey's site, «Five fingers can only play five notes in a row. To extend this range, there are two main techniques: the turning under of the thumb and the crossing over of the fingers.(C.P.E.Bach, 1753).»
I wonder if it is a coincidence that C.P.E. was among the first to write for pianoforte. I don't have any experience with the harpsichord, but I've been told it has a ligther touch than the piano, probably requiring a different technique to optimize speed and fluency. Could it be the relatively stronger touch of the new pianoforte that prompted the adoption of new techniques? Anyone can coment on this idea?
Comment: Since I play using my thumbs and also often could be seen with my hands in almost the exact same position as in the first image, I don't understand what about that first image supports the idea that the player in that image was not using their thumbs.
Comment: You're right, it's no proof, it was used by Prof. Craig only for illustrative purposes of the thesis he was presenting. What's more, we don't even know if the model actually played the instrument, and there are many comtemporary paintings with similar subjects that show hands in a much more (for our standards) natural position. Having said that, in this picture to me it really seems that the thumb is positioned in a rather akward way, like if wanted really out of the way. Totally subjective interpretation, of course, I guess one tends do see what one wants do see...
Comment: If you compare the size of the hands and fingers with the dimensions of the keyboard, there is a rather obvious lack of realism in the picture - not to mention the fact that the "black" keys appear to be on the same level as the "white" ones. There are enough of surviving early keyboards to know what their typical real dimensions were.
Answer: Having played both piano and harpsichord, let me throw another idea out there on top of all the excellent academic sources people have quoted:
In harpsichord it does not matter how hard or soft you hit the key (since it plucks rather than hits the string).  Good technique is, thus, centered around control of the "touch", and typically the goal is to keep the finger as close to the key as possible.  (This is referenced, for example, in Couperin's L'Art De Toucher Le Clavecin on pg. 11)
The thumb, being shorter than the other fingers, presents a specific challenge to this goal.  Playing a key with the thumb, particularly an accidental, risks tilting the rest of your hand and sacrificing the closeness and control of the other fingers to the strings.  Notes played with the thumb also tend to be play with the finger slightly tilted, which also sacrifices some control.
While plenty of Baroque composers wrote octaves, parallel sixths, and other figures that clearly can only be played using the thumb, the thumb was otherwise de-emphasized.  This is clear from the scale fingering referenced above.  Playing Baroque music modernly I think of it this way: I never play an accidental with the thumb unless I absolutely cannot avoid it.  For non-accidental notes, I try to use another finger if it's not too onerous.  In practice that helps me keep close enough to the key as is reasonable for most pieces.
So no, Bach was not the first composer to use the thumb.  As the harpsichord transitioned to the fortepiano (certainly during CPE Bach's lifetime), avoiding the thumb became less important in good technique and CPE might have boasted about his father being in the vanguard of Classical technique.
Answer: CPE Bach certainly made that assertion about his father, but remember that they both had very limited access to anything except "contemporary music", compared with what is available to anyone today.
If you look at any collection of 16th century keyboard music written 50-100 years before JSB), it is full of octave stretches, especially for the left hand. There is no way it could have been played without using thumbs. The typical fingering for an octave of a scale was certainly given as 2 3 4 2 3 4 2 3, but early keyboard music was not restricted to single-note scales. Virtually any page of the Fitzwilliam Virginal Book http://imslp.org/wiki/Special:ImagefromIndex/178082 (one of the larger collections of keyboard music made in about 1600) has examples of 4-note chords spanning an octave and played with one hand.
In fact, some 16th century keyboard music is a significantly more technically challenging than much of JS Bach. For example look at the piece on pages 34-39 in volume 2 of the same collection http://imslp.org/wiki/Special:ImagefromIndex/05178. Even the Goldberg Variations don't have fast scale passages in double-thirds and double-sixths played with one hand!
Comment: Although, looking at it further, I suspect it was more puffery for C.P.E.'s dad than a lack of knowledge of earlier music. Bach was known to have Froberger in his library, and there's another composer whose music would be hard to negotiate without ample recourse to the thumbs (also one who would be familiar to younger musicians of the time - the Hexachord Fantasia was used as training material as late as Beethoven).
Answer:
Do we have any knowledge of thumbs being used in keyboard technique prior to Bach?

About 150 years before Bach, several books like "Declaracion de Instrumentos" (Bermudo, 1555)  and Arte de tañer (Santamaría, 1565) allow the use of the thumb.  From the later book:

In English: "Thumbs are not allowed for black keys, except when playing octaves, with any hand, or when there is no other alternative".
Bermudo goes farther, and prescribes as normal the fingering 1-2-3-4 4-3-2-1 for scale passages. A few more details (in Spanish) here.


Twitter API Protected User Rate Limit

Question: I get mixed results when I try this so I thought I'd ask if anyone else knows of any documentation, etc that explains what happens - the problem is when you access a protected users feed on Twitter, does that count towards your API rate limit?
Thanks,
Answer: Based on Twitter's documentation page for user_timeline , it is counted towards your rate limit. Regardless of whether the user is protected or public.

Rate Limited
true
Comment: As of 2017-02-25, the link is broken.

Twitter API Protected User Rate Limit


Could there be exact solutions to the Lane-Emden equation for real n≥0 other than 0, 1, or 5?

Question: This Astronomy SE answer says

With a constant $k$ and the polytrop index $n$. This is a result of the solutions of the Lane-Emden equation
$$\frac{1}{\xi^2} \frac{\mathrm{d}}{\mathrm{d}\xi} \left(\xi^2\frac{\mathrm{d}\theta}{\mathrm{d}\xi}\right) + \theta^n = 0$$
which is a dimensionless form of the Poisson equation for a radially-symmetric self-gravitating polytropic fluid, thus where density follows a function of the form $\varrho = \varrho_c \theta^n$ with a central density $\varrho_c$.
This equation can be solved exactly for polytrop index 0 (isobaric polytrope), 1 (isothermal polytrope) and 5 (limited use as it results in infinite stellar radius)...

Question: Wikipedia notes that exact solutions (not depending on converging series) are known only for $n=(0, 1, 5)$. Could there be as-yet undiscovered exact solutions for other real $n \ge 0$? Or has it been shown that there are no others possible?
Potentially related:

I have a special solution for the Lane-Emden equation. Can I use it to find the general solution?
Answer: "Analytical solving is possible" means that the solution can be expressed with a finite number of standard functions (elementary and special functions). But this doesn't mean that analytical solving is impossible for ever. If new convenient special functions were defined and standardized, the solving would become possible thanks to those functions.
This is the same as the Bessel ODEs for example. They were not anatically solvable and become solvable when some new special functions named "Bessel functions" where defined and standardized.
Citation : "A special function has to acquire a background of property, descriptions,
formulas and derivations as extended as possible. So, it will be preferable to simply refer to a particular part of the background, instead of searching and redoing a development by ourselves. Before becoming a referenced special function, its name has to be spread in the literature in order to become familiar. More importantly, the function should be useful in a branch of mathematics or physics." (Citation from p.3 in https://fr.scribd.com/doc/34977341/Sophomore-s-Dream-Function ).
Generally, a function has a long way to go before acquiring the honorific status of special
function. Probably a long way too for the expected special fonctions related to the Lane-Emden equation.
Comment: In fact this is not an answer to your question. This a comment, but too long to be edited in the comments section. That is why it was edited in the answers section.
Comment: Thanks for your answer, this is informative and illuminating. I'll still hold off for a boolean answer though ("yes there could be, it's not been proven otherwise" vs "no, it's been shown that there can not be" or "this is why there can not be")
Comment: Yep I understand; I still find it valuable and helpful nonetheless.


Flexbox does not display text in columns

Question: I want three articles to be displayed on the homepage of the desktop version, each article in its own column. As I'm using flexbox this should be done easily, as I read in some tutorials.
But nothing changes, the articles are still one under another. I tried with this tutorial: https://davidwalsh.name/flexbox-column
HTML
<!DOCTYPE html>

    <title>Munchies</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/style3.css">

Home

Around the globe

Where to eat?

Recipes

About me

    <input type="checkbox" id="nav-trigger" class="nav-trigger" />

Featured:

Brussels

Belgian Food

                    Traditional Belgian food is not for the faint hearted, with dishes such as bloedworst (black pudding made from pig's blood, served with apple sauce), breugel kop (chunks of beef and tongue set in gelatine) and paar de filet/steack de cheval (horse
                    steak). But there are more elegant spins on the local fare available: try La Maison du Cygne, which fuses Belgian and French cuisine and also offers glorious views of Brussels' gabled, gilded Grand Place.

Featured:

Real guacamole

Ingredients:

4 mild chillies, finely chopped

bunch coriander, chopped

2 tomatoes, finely chopped

salt, to taste

1 onion, finely chopped

½ lime, juice only

3 ripe avocados

Directions:

                    In a pestle and mortar, pound the chillies, coriander, tomatoes, salt and onion to a fine paste.

                    Add a little water and lime juice to make a looser mixture. Mash in the avocados. Serve.

Featured:

Belgium

Waffles

                    Belgian waffles (gauffres) are internationally known, but in Belgium there are two different types: the Brussels waffle and the Liège waffle. The Brussels waffle is rectangular, golden brown on the outside, dusted with powdered/icing sugar and then
                    sometimes covered with syrup, slices of fruit, chocolate spread and whipped cream - all of which is deemed a mite inauthentic by waffle connoisseurs! The denser textured Liege waffle is square and has burnt sugar on the outside. They are sold
                    by street vendors and gourmet restaurants alike, all over Belgium.

            MUNCHIES

CSS
        /CSS reset/
        html, body, div, span, applet, object, iframe,
        h1, h2, h3, h4, h5, h6, p, blockquote, pre,
        a, abbr, acronym, address, big, cite, code,
        del, dfn, em, img, ins, kbd, q, s, samp,
        small, strike, strong, sub, sup, tt, var,
        b, u, i, center,
        dl, dt, dd, ol, ul, li,
        fieldset, form, label, legend,
        table, caption, tbody, tfoot, thead, tr, th, td,
        article, aside, canvas, details, embed,
        figure, figcaption, footer, header, hgroup,
        menu, nav, output, ruby, section, summary,
        time, mark, audio, video {
            margin: 0;
            padding: 0;
            border: 0;
            font-size: 100%;
            font: inherit;
            vertical-align: baseline;
        }
    /* Site wrapper, using flexbox*/

    .wrapper {
          display: -webkit-box;
        display: -moz-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-flex-flow: row wrap;
        flex-flow: row wrap;
        text-align: center;
        flex: 1 100%;
        min-height: 100%;
        min-width: 100%;
        background-color: rgb(237, 237, 237);
        position: relative;
        top: 0;
        bottom: 100%;
        left: 0;
        z-index: 1;
        padding: 0em;
        background-size: 200%;
    }

    .main {
        padding: 1em;
        flex: 1 100%;
        text-align: justify;
        background: rgb(237, 237, 237);
        order: 3;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 18px;
        line-height: 1.3;
    }

    .aside-1 {
        padding-top: 1em;
        padding-left: 5em;
        padding-right: 5em;
        padding-bottom: 1em;
        margin-top: 0em;
        flex: 1 100%;
        background: rgb(224, 224, 224);
        order: 2;
    }

    .aside-2 {
        padding: 10px;
        margin-top: 0em;
        flex: 1 100%;
        background: rgb(55, 60, 57);
        order: 1;
        font-family: Impact, sans-serif;
        font-size: 50px;
        color: white;
    }
    /*Navigation menu*/

    .navigation {
        width: 100%;
        height: 100%;
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 0;
        list-style: none;
        background: rgb(35, 36, 35);
    }
    /*List items width in navigation menu*/

    .nav-item {
        width: 200px;
        border-top: 1px solid rgb(73, 70, 70);
        border-bottom: 1px solid rgb(73, 70, 70);
    }
    /*Appearance for navigation menu links*/

    .nav-item a {
        display: block;
        padding: 1em;
        background: rgb(35, 36, 35);
        color: white;
        font-size: 1.2em;
        text-decoration: none;
        transition: background 0.5s;
    }
    /*Changing the color of the link when hovering over with the cursor*/

    .nav-item a:hover {
        background: black;
    }
    /*Navigation trigger*/

    .nav-trigger {
        /*hide the checkbox input*/
        position: absolute;
        clip: rect(0, 0, 0, 0);
    }

    label[for="nav-trigger"] {
        /*critical positioning styles */
        position: fixed;
        left: 15px;
        top: 15px;
        z-index: 2;
        /*styles */
        height: 30px;
        width: 30px;
        cursor: pointer;
        background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' x='0px' y='0px' width='30px' height='30px' viewBox='0 0 30 30' enable-background='new 0 0 30 30' xml:space='preserve'><rect width='30' height='6'/><rect y='24' width='30' height='6'/><rect y='12' width='30' height='6'/></svg>");
        background-size: contain;
    }

    .nav-trigger+label, .wrapper {
        transition: left 0.3s;
    }

    .nav-trigger:checked+label {
        left: 215px;
    }

    .nav-trigger:checked~.wrapper {
        left: 200px;
    }

    .responsive-image {
        max-width: 100%;
    }

    html, body {
        height: 100%;
    }

    body {
        /*Without this, the body has excess horizontal scroll when the menu is open*/
        overflow-x: hidden;
        margin-left: 0px;
        margin-right: 0px;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 14px;
    }

    /*Styles for table of content*/

    .content {
        list-style-type: none;
        text-align: center;
        font-size: 18px;
        max-width: 15em;
        margin: auto;
    }

    .content li a {
        display: block;
        padding: 0.7em;
        background: rgb(35, 36, 35);
        /*SPREMENI BARVO TEKSTA, ISTO KOT OZADJE*/
        color: white;
        font-size: 1em;
        text-decoration: none;
        transition: background 0.5s;
        /*SPREMENI BARVO BORDERJA, ISTO KOT OZADJE*/
        border-top: 1px solid white;
        border-bottom: 1px solid white;
                border-radius: 10px;
    }

    .content a:hover {
        background: black;
    }

    .profile-pic {
        border-radius: 50%;
        max-width: 30%;
        max-height: 30%;
        float: left;
        margin: 1em 1em 1em 1em;
    }

    #social img {
        display: inline-block;
        max-height: 50px;
        max-width: 50px;
        margin: 1em 1em 1em 1em;
        float: left;
    }

    .anchor:before {
        content: "";
        display: block;
        height: 50px;
        /* fixed header height*/
        margin: -50px 0 0;
        /* negative fixed header height */
    }

    .index-img {
        max-width: 70%;
        border-radius: 25px;
        display: block;
        margin: auto;
        padding: 10px;
    }

        .recipe {
      list-style: none;
    }
    /*Tablets responsive*/

    @media all and (min-width: 700px) {
        /* Navigation Menu - Background */
        .navigation {
            /* critical sizing and position styles */
            height: 6em;
            z-index: 2;
            overflow: hidden;
            /* non-critical appearance styles */
            background: rgb(55, 60, 57);
        }
        /* Navigation Menu - List items */
        .nav-item {
            /* non-critical appearance styles */
            width: 20%;
            height: 6em;
            border-top: none;
            border-bottom: none;
            float: left;
        }
        .nav-item a {
            /* non-critical appearance styles */
            width: auto;
            height: 6em;
            background: rgb(55, 60, 57);
            font-size: 1em;
            transition: color 0.2s, background 0.5s;
            text-align: center;
            padding-top: 2.3em;
            border-left: 1px solid rgb(73, 70, 70);
            border-right: 1px solid rgb(73, 70, 70);
        }
        /* Nav Trigger */
        .nav-trigger {
            display: none;
        }
        label[for="nav-trigger"] {
            /* critical positioning styles */
            display: none;
        }
        .nav-trigger+label, .wrapper {
            transition: none;
        }
        .nav-trigger:checked+label {
            left: 0;
        }
        .nav-trigger:checked~.wrapper {
            left: 0px;
        }
        .main {
            padding: 10px;
            flex: 1 100%;
        }

        .recipe {

        }
        .aside-1 {
            padding: 10px;
            flex: 1 100%;
            font-size: 18px;
            /*position: fixed;*/
            height: 100%;
        }
        .aside-2 {
            background: red;
            margin-top: 1.5em;
            flex: 0 0 100%;
        }
        body {
            margin-top: 0em;
        }
        .responsive-image {
            margin: auto;
            padding: 20px;
            display: block;
            width: 40%;
        }
        /*Styles for table of content*/
        .content {
            list-style-type: none;
            text-align: center;
            font-size: 18px;
        }
        .content li a {
            display: block;
            padding: 0.7em;
            background: rgb(55, 60, 57);
            /*SPREMENI BARVO TEKSTA, ISTO KOT OZADJE*/
            color: white;
            font-size: 1em;
            text-decoration: none;
            transition: background 0.5s;
            /*SPREMENI BARVO BORDERJA, ISTO KOT OZADJE*/
            border-top: 1px solid rgb(237, 237, 237);
            border-bottom: 1px solid rgb(237, 237, 237);
        }
        .index-img {
            max-width: 50%;
        }
    }
    /*Desktop responsive*/

    @media all and (min-width: 900px) {
        /* Navigation Menu - Background */
        .navigation {
            /* critical sizing and position styles */
            height: 3em;
            z-index: 2;
            overflow: hidden;
            /* non-critical appearance styles */
            background: rgb(55, 60, 57);
        }
        /* Navigation Menu - List items */
        .nav-item {
            /* non-critical appearance styles */
            width: auto;
            height: 3em;
            border-top: none;
            border-bottom: none;
            float: left;
        }
        .nav-item a {
            /* non-critical appearance styles */
            width: auto;
            height: 3em;
            background: rgb(55, 60, 57);
            font-size: 1em;
            transition: color 0.2s, background 0.5s;
            padding: 1em;
        }
        /* Nav Trigger */
        .nav-trigger {
            display: none;
        }
        label[for="nav-trigger"] {
            /* critical positioning styles */
            display: none;
        }
        .nav-trigger+label, .wrapper {
            transition: none;
        }
        .nav-trigger:checked+label {
            left: 0;
        }
        .nav-trigger:checked~.wrapper {
            left: 0px;
        }
        .main {
            padding: 10px;
            flex: 1 60%;
        }

        .aside-1 {
            padding: 10px;
            font-size: 18px;
            flex: 0 0 200px;
            height: auto;
        }
        .aside-2 {
            background: white;
            margin-top: 0;
            color: black;
            flex: 0 0 100%;
        }
        body {
            margin-top: 3em;
        }

        /*.responsive-image {
            margin: auto;
            padding: 20px;
            display: block;
            width: 40%;
        }*/
        /*Styles for table of content*/
        .content {
            list-style-type: none;
            text-align: center;
            font-size: 18px;
            max-width: 10em;
            /*margin-top: 6em;*
            /*position: fixed;
            left: 4em;*/
                        padding: 1em;
        }
        .content li a {
            display: block;
            padding: 0.7em;
            background: rgb(55, 60, 57);
            color: white;
            font-size: 1em;
            text-decoration: none;
            transition: background 0.5s;
            border-top: 1px solid rgb(237, 237, 237);
            border-bottom: 1px solid rgb(237, 237, 237);
        }
        .index-img {
            max-width: 31%;
            display: block;
            margin: auto;
        }
        .recipe {

        }
                .content-wrapper{
                        position: fixed;
                }

                .main-content{
                    order: 2;
                }

                .main-content > article {
                    width: 30%;
                    padding: 10px;
                    order: 2;
                }
    }

https://jsbin.com/kakiqanaho/edit?output
 Thanks for the help!
Comment: Add `display: flex` to `.main-content`. The scope of flex layout is the parent-child relationship. Elements that aren't the parent or a child of this parent won't accept flex properties.
Comment: Hi, i can just a send this link [link](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) Here I have found a lot on good info.
Comment: Yes, I started with flex because I ran into this page. But thanks!
Answer: Add display: flex to main-content in @media all and (min-width: 900px)
See demo below:

/*CSS reset*/

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* Site wrapper, using flexbox*/

.wrapper {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  text-align: center;
  flex: 1 100%;
  min-height: 100%;
  min-width: 100%;
  background-color: rgb(237, 237, 237);
  position: relative;
  top: 0;
  bottom: 100%;
  left: 0;
  z-index: 1;
  padding: 0em;
  background-size: 200%;
}
.main {
  padding: 1em;
  flex: 1 100%;
  text-align: justify;
  background: rgb(237, 237, 237);
  order: 3;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 18px;
  line-height: 1.3;
}
.aside-1 {
  padding-top: 1em;
  padding-left: 5em;
  padding-right: 5em;
  padding-bottom: 1em;
  margin-top: 0em;
  flex: 1 100%;
  background: rgb(224, 224, 224);
  order: 2;
}
.aside-2 {
  padding: 10px;
  margin-top: 0em;
  flex: 1 100%;
  background: rgb(55, 60, 57);
  order: 1;
  font-family: Impact, sans-serif;
  font-size: 50px;
  color: white;
}
/*Navigation menu*/

.navigation {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 0;
  list-style: none;
  background: rgb(35, 36, 35);
}
/*List items width in navigation menu*/

.nav-item {
  width: 200px;
  border-top: 1px solid rgb(73, 70, 70);
  border-bottom: 1px solid rgb(73, 70, 70);
}
/*Appearance for navigation menu links*/

.nav-item a {
  display: block;
  padding: 1em;
  background: rgb(35, 36, 35);
  color: white;
  font-size: 1.2em;
  text-decoration: none;
  transition: background 0.5s;
}
/*Changing the color of the link when hovering over with the cursor*/

.nav-item a:hover {
  background: black;
}
/*Navigation trigger*/

.nav-trigger {
  /*hide the checkbox input*/
  position: absolute;
  clip: rect(0, 0, 0, 0);
}
label[for="nav-trigger"] {
  /*critical positioning styles */
  position: fixed;
  left: 15px;
  top: 15px;
  z-index: 2;
  /*styles */
  height: 30px;
  width: 30px;
  cursor: pointer;
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' x='0px' y='0px' width='30px' height='30px' viewBox='0 0 30 30' enable-background='new 0 0 30 30' xml:space='preserve'><rect width='30' height='6'/><rect y='24' width='30' height='6'/><rect y='12' width='30' height='6'/></svg>");
  background-size: contain;
}
.nav-trigger+label,
.wrapper {
  transition: left 0.3s;
}
.nav-trigger:checked+label {
  left: 215px;
}
.nav-trigger:checked~.wrapper {
  left: 200px;
}
.responsive-image {
  max-width: 100%;
}
html,
body {
  height: 100%;
}
body {
  /*Without this, the body has excess horizontal scroll when the menu is open*/
  overflow-x: hidden;
  margin-left: 0px;
  margin-right: 0px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
}
/*Styles for table of content*/

.content {
  list-style-type: none;
  text-align: center;
  font-size: 18px;
  max-width: 15em;
  margin: auto;
}
.content li a {
  display: block;
  padding: 0.7em;
  background: rgb(35, 36, 35);
  /*SPREMENI BARVO TEKSTA, ISTO KOT OZADJE*/
  color: white;
  font-size: 1em;
  text-decoration: none;
  transition: background 0.5s;
  /*SPREMENI BARVO BORDERJA, ISTO KOT OZADJE*/
  border-top: 1px solid white;
  border-bottom: 1px solid white;
  border-radius: 10px;
}
.content a:hover {
  background: black;
}
.profile-pic {
  border-radius: 50%;
  max-width: 30%;
  max-height: 30%;
  float: left;
  margin: 1em 1em 1em 1em;
}
#social img {
  display: inline-block;
  max-height: 50px;
  max-width: 50px;
  margin: 1em 1em 1em 1em;
  float: left;
}
.anchor:before {
  content: "";
  display: block;
  height: 50px;
  /* fixed header height*/
  margin: -50px 0 0;
  /* negative fixed header height */
}
.index-img {
  max-width: 70%;
  border-radius: 25px;
  display: block;
  margin: auto;
  padding: 10px;
}
.recipe {
  list-style: none;
}
/*Tablets responsive*/

@media all and (min-width: 700px) {
  /* Navigation Menu - Background */
  .navigation {
    /* critical sizing and position styles */
    height: 6em;
    z-index: 2;
    overflow: hidden;
    /* non-critical appearance styles */
    background: rgb(55, 60, 57);
  }
  /* Navigation Menu - List items */
  .nav-item {
    /* non-critical appearance styles */
    width: 20%;
    height: 6em;
    border-top: none;
    border-bottom: none;
    float: left;
  }
  .nav-item a {
    /* non-critical appearance styles */
    width: auto;
    height: 6em;
    background: rgb(55, 60, 57);
    font-size: 1em;
    transition: color 0.2s, background 0.5s;
    text-align: center;
    padding-top: 2.3em;
    border-left: 1px solid rgb(73, 70, 70);
    border-right: 1px solid rgb(73, 70, 70);
  }
  /* Nav Trigger */
  .nav-trigger {
    display: none;
  }
  label[for="nav-trigger"] {
    /* critical positioning styles */
    display: none;
  }
  .nav-trigger+label,
  .wrapper {
    transition: none;
  }
  .nav-trigger:checked+label {
    left: 0;
  }
  .nav-trigger:checked~.wrapper {
    left: 0px;
  }
  .main {
    padding: 10px;
    flex: 1 100%;
  }
  .recipe {} .aside-1 {
    padding: 10px;
    flex: 1 100%;
    font-size: 18px;
    /*position: fixed;*/
    height: 100%;
  }
  .aside-2 {
    background: red;
    margin-top: 1.5em;
    flex: 0 0 100%;
  }
  body {
    margin-top: 0em;
  }
  .responsive-image {
    margin: auto;
    padding: 20px;
    display: block;
    width: 40%;
  }
  /*Styles for table of content*/
  .content {
    list-style-type: none;
    text-align: center;
    font-size: 18px;
  }
  .content li a {
    display: block;
    padding: 0.7em;
    background: rgb(55, 60, 57);
    /*SPREMENI BARVO TEKSTA, ISTO KOT OZADJE*/
    color: white;
    font-size: 1em;
    text-decoration: none;
    transition: background 0.5s;
    /*SPREMENI BARVO BORDERJA, ISTO KOT OZADJE*/
    border-top: 1px solid rgb(237, 237, 237);
    border-bottom: 1px solid rgb(237, 237, 237);
  }
  .index-img {
    max-width: 50%;
  }
}
/*Desktop responsive*/

@media all and (min-width: 900px) {
  /* Navigation Menu - Background */
  .navigation {
    /* critical sizing and position styles */
    height: 3em;
    z-index: 2;
    overflow: hidden;
    /* non-critical appearance styles */
    background: rgb(55, 60, 57);
  }
  /* Navigation Menu - List items */
  .nav-item {
    /* non-critical appearance styles */
    width: auto;
    height: 3em;
    border-top: none;
    border-bottom: none;
    float: left;
  }
  .nav-item a {
    /* non-critical appearance styles */
    width: auto;
    height: 3em;
    background: rgb(55, 60, 57);
    font-size: 1em;
    transition: color 0.2s, background 0.5s;
    padding: 1em;
  }
  /* Nav Trigger */
  .nav-trigger {
    display: none;
  }
  label[for="nav-trigger"] {
    /* critical positioning styles */
    display: none;
  }
  .nav-trigger+label,
  .wrapper {
    transition: none;
  }
  .nav-trigger:checked+label {
    left: 0;
  }
  .nav-trigger:checked~.wrapper {
    left: 0px;
  }
  .main {
    padding: 10px;
    flex: 1 60%;
  }
  .aside-1 {
    padding: 10px;
    font-size: 18px;
    flex: 0 0 200px;
    height: auto;
  }
  .aside-2 {
    background: white;
    margin-top: 0;
    color: black;
    flex: 0 0 100%;
  }
  body {
    margin-top: 3em;
  }
  /*.responsive-image {
                margin: auto;
                padding: 20px;
                display: block;
                width: 40%;
            }*/
  /*Styles for table of content*/
  .content {
    list-style-type: none;
    text-align: center;
    font-size: 18px;
    max-width: 10em;
    /*margin-top: 6em;*
                /*position: fixed;
                left: 4em;*/
    padding: 1em;
  }
  .content li a {
    display: block;
    padding: 0.7em;
    background: rgb(55, 60, 57);
    color: white;
    font-size: 1em;
    text-decoration: none;
    transition: background 0.5s;
    border-top: 1px solid rgb(237, 237, 237);
    border-bottom: 1px solid rgb(237, 237, 237);
  }
  .index-img {
    max-width: 31%;
    display: block;
    margin: auto;
  }
  .recipe {} .content-wrapper {
    position: fixed;
  }
  .main-content {
    order: 2;
    display: flex;
   }
  .main-content > article {
    width: 30%;
    padding: 10px;
    order: 2;
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Home

Around the globe

Where to eat?

Recipes

About me

  <input type="checkbox" id="nav-trigger" class="nav-trigger" />

Featured:

Brussels

Belgian Food

          Traditional Belgian food is not for the faint hearted, with dishes such as bloedworst (black pudding made from pig's blood, served with apple sauce), breugel kop (chunks of beef and tongue set in gelatine) and paar de filet/steack de cheval (horse
          steak). But there are more elegant spins on the local fare available: try La Maison du Cygne, which fuses Belgian and French cuisine and also offers glorious views of Brussels' gabled, gilded Grand Place.

Featured:

Real guacamole

Ingredients:

4 mild chillies, finely chopped

bunch coriander, chopped

2 tomatoes, finely chopped

salt, to taste

1 onion, finely chopped

½ lime, juice only

3 ripe avocados

Directions:

          In a pestle and mortar, pound the chillies, coriander, tomatoes, salt and onion to a fine paste.

          Add a little water and lime juice to make a looser mixture. Mash in the avocados. Serve.

Featured:

Belgium

Waffles

          Belgian waffles (gauffres) are internationally known, but in Belgium there are two different types: the Brussels waffle and the Liège waffle. The Brussels waffle is rectangular, golden brown on the outside, dusted with powdered/icing sugar and then
          sometimes covered with syrup, slices of fruit, chocolate spread and whipped cream - all of which is deemed a mite inauthentic by waffle connoisseurs! The denser textured Liege waffle is square and has burnt sugar on the outside. They are
          sold by street vendors and gourmet restaurants alike, all over Belgium.

      MUNCHIES

Comment: Thanks for the help :)


JS conteúdo por tempo

Question: Quero fazer um código JS para exibir determinado conteúdo relacionado com os dias, conforme no exemplo abaixo.
dia 1 = html a
dia 2 = html b
dia 3 = html c
Tipo, quando for no dia 1, vai aparecer um conteúdo do html a e quando finalizar as 24 horas vai para o dia 2 e exibe o html b e assim por diante.
Quero apenas saber a base de como executar isso, alguém consegue me dar um help?
Comment: Quantos dias diferentes há? um por semana, um por mês, ou um numero fixo que vai rodando?
Comment: E outra pergunta, se a página recarregar o utilizador vê o mesmo conteúdo desse dia ou pode ser outro conteúdo?
Answer: Somente com JS nao e um jeito bom de fazer isso, o ideal seria um backend que traz renderiza somente o conteudo do dia.
Mas pra voce entender uma maneira simplista poderia ser assim

$(document).ready(function(){
  var date = new Date()
  var today = date.getDate()
  //isso e so preguica de copiar e colar 30 divs, mas da pra entender a ideia geral
  lazyLoad()

  //mesmo nome de classe ali de baixo na linha 15
  var $todayContent = $('.content-day-'+today)
  $todayContent.show()
})

function lazyLoad(){
    var $main = $('#main')
    for(var i=0; i<31; i++){
      var day = i+1
      $main.append('
'+
        '
Sou o Conteudo do dia '+day+'
'+
      '
')
    }
  }
.content {
  display: none;
}

Ai voce precisa ajeitar pra suas necessidades, tipo um setInerval pra mudar automaticamente para o dia as 00:00h e por ai vai, depende das suas necessidades.
Comment: Valeu mano, era isso mesmo, abs.

JS conteúdo por tempo


Plotting discrete user-defined function in R

Question: set.seed(123)
x <- rnorm(10000,0,2);
s2 <- function(n) (1/(length(x[1:n])-1)*sum((x[1:n]-mean(x[1:n]))^2))^(1/2)
m <- function(n) 1/n*sum(x[1:n])

I want to plot s2 and m, i. e. (n,s2(n)) and (n,m(n)) for 1<=n<=N, where N is some fixed value, i. e. N=1000, and the n's are integers. I want them to be in the same coordinante system. How can I do that?
Answer: You can use sapplyas follows
set.seed(123)
x <- rnorm(10000,0,2);
s2 <- function(n)
  (1/(length(x[1:n])-1)*sum((x[1:n]-mean(x[1:n]))^2))^(1/2)
m <- function(n) 1/n*sum(x[1:n])

xx <- 1:10000
f_s <- sapply(xx, s2)
f_m <- sapply(xx, m)

plot(xx, f_s, ylim=c(-3,3))
points(xx, f_m, col=2)

Comment: Amazing! It works!
Comment: Thanks! Does it plot them in the same coordinate system? I doesn't seem to do it for me.
Comment: I updated the two last lines of code.


String type in c++builder (RAD XE2) handle 2047 character only?

Question: I have a project with Indy (using RAD XE2) and I get a return string from IdHTTP like:
String result = IdHTTP->Get(url);
the problem is reuslt is limited at 2047 character lenght.
How can i handle full return string?
Thank you.
Edit: This issue occurs when in debug mode only (using Step into).
Comment: Strings in 32-bit C++Bulder applications are not limited to 2047 bytes; they can hold up to 2GB. It's something you're doing wrong, but as you've posted zero code it's hard to say what that might be.
Comment: That's not an issue with the `String` or `WideString` type, but will either be an issue with Indy or the web service you're attempting to consume!
Comment: Thank LaKraven and Ken White.
Answer: There's no inherent limit to the length of a string. More likely is that your debugging activities are interrupting the network activities, interfering with your program's ability to read everything off the socket before the debugger pauses it.
Stop trying to single-step through asynchronous I/O, and you'll probably see better results.
Also note that the debugger's watch window won't necessarily show you the entire contents of a variable, so if you're only seeing 2047 characters in the debugger, that doesn't necessarily reflect the actual length of the string. Call Length instead.


Como resolver ou rejeitar uma Promise (nativa) em JavaScript fora do seu escopo?

Question: A maioria das implementações que vejo de Promises (promessas) em frameworks JavaScript trata o uso de Promises de maneira que é possível acessar as funções responsáveis pela rejeição e resolução em qualquer escopo.
Por exemplo, Angular:
var defer = $q();

setTimeout(function () {
    defer.resolve({status: true});
}, 5000);

defer.promise.then(function (data) {
    console.log(data.status);
});

Algo similar é possível fazer no jQuery.
Porém, ao usar a Promise nativa do JavaScript, eu não consigo visualizar como poderia fazer tal operação, a não ser que a chamada se desse dentro do callback passado como argumento.
Para fazer no Javascript, eu teria que fazer assim, teoricamente:
 var p = new Promise(function (reject, resolve) {
        setTimeout(() => p({status: true}, 5000);
  });

  p.then((data) => console.log(data.status));

O meu questionamento é se existe alguma forma de fazer a mesma operação, usando o Promise nativo do JavaScript, da mesma forma que fiz no primeiro exemplo. Pois, dependendo da estrutura do projeto, poderia ser horrível ter que ficar refém de encapsular algo dentro de um callback para ter a funcionalidade da Promise. E pelo que andei pesquisando na internet, parece que a Promise do Javascript foi feita pra ser usada assim mesmo. :\
Existe alguma maneira simples de se burlar essa limitação da implementação de promessas do JavaScript?
Observação: Tentei usar a chamada Promise.resolve(promise), mas não obtive o efeito desejado.
Comment: @WaIlaceMaxters, você deseja alguma informação adicional na resposta? :-)
Answer: Você poderia fazer este tipo de gambiarra:

const controls = {};
const promise = new Promise((resolve, reject) => {
  controls.resolve = resolve;
  controls.reject = reject;
});

promise.then((val) => {
  console.log('Fui resolvida. Valor de resolução:', val);
});

setTimeout(() => {
  controls.resolve(1);
}, 1000);

Esse tipo de código é possível já que a função executora (primeiro argumento passado para o construtor Promise) é executada de forma síncrona, o que permite "retirar" as funções resolve e reject de dentro do callback.
No entanto, o código acima pode ser considerado um anti-pattern (tanto é que o escondi por padrão) e, portanto, seu uso deve ser desencorajado. Por design, as Promises foram arquitetadas para serem resolvidas somente através das funções (resolve e reject) passada para o executor. Desse modo, não é bem uma "limitação", mas sim uma escolha.
O construtor da Promise comporta-se dessa maneira por um motivo chamado throw safety. Isso significa que, se uma exceção for lançada de dentro do executor, o próprio construtor Promise capturará o erro e rejeitará imediatamente a Promise, sendo o valor de rejeição do próprio erro lançado. Isso é importante pois mantém um código previsível. [Referência]
Portanto, quando há a necessidade de se resolver uma "promessa" de fora de seu executor, vale mais a pena utilizar um deffered, que te permite fazer isso. A Promise do JavaScript não foi feita com esse use-case em mente. O jQuery, por exemplo, implementa o jQuery.Deferred. Vale observar que promises e deferreds, embora possuam funções parecidas, não são a mesma coisa.

Vale notar que o método ("estático") Promise.resolve não é usado para resolver uma Promise, mas sim criar uma nova promessa, que será imediatamente resolvida com o valor passado como primeiro argumento de Promise.resolve. Existe também o método Promise.reject, que se comporta de mesma maneira para criar uma promessa imediatamente rejeitada.
Não é o caso, mas se existisse um método Promise.prototype.resolve, esse sim seria usado para resolver instâncias já existentes de Promise.
Comment: Por que o negativo? Aliás, convido a pessoa que negativou postar uma outra resposta. :-)


OnCLick: read the field name and print it out in TOAST

Question: I'm trying to read an element from the list shown below (using onClick), with the data being read from a JSON file, the data itself only holds strings. However, I'm having trouble actually registering the array elements to the onClick procedure.
I have absolutely no experience with JSON and am trying to familiarise myself with reading a JSON file and storing it in an Array (which I've done), but I then want to click the individual fields and make it do something.
below is what I have so far:
<code>    public void onBindViewHolder(Adapter.ViewHolder holder, int position) {

    final ItemFruit itemFruit = fruitList.get(position);

    holder.tvFruit.setText(itemFruit.getFruit());
    holder.tvPrice.setText(itemFruit.getPrice());
    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //when item is clicked, TOAST displays the field name

        }
    });

}
</code>
Image of array:
array of fruit
Any help whatsoever would be greatly appreciated.
Thanks in advance
Comment: Possible duplicate of [How to display Toast in Android?](https://stackoverflow.com/questions/3500197/how-to-display-toast-in-android)
Answer: put this inside onclick
<code> Toast.makeText(adapterContext, itemFruit.getFruit(),
   Toast.LENGTH_LONG).show();
</code>
Here adapterContext you have to maintain at adapter level.
Create global variable
<code>   Context adapterContext
</code>
on onCreateViewHolder initialize it
<code> adapterContext = parent.getContext();
</code>
and then use it.
Comment: Thank you so much for the response. When adding that, I get the error "cannot resolve symbol adapter context". Is there something else I'm doing wrong?
Comment: No, As i told you before you have to maintain context at adapter level.
Comment: Just trying that now, thank you for your continued help
Comment: Perfect, that worked. On second glance, I had created a private context c but I had not initialised it. Thank you ever so much for showing me my mistake! Have a great day!
Comment: @JamesSon Why didn't you accept this as the answer then?


Multiple Intent receivers?

Question: Documentation states that if an Intent can be processed by multiple applications the user will be prompted with a dialog asking him to choose the application to complete the action. Is there any way to make user select multiple applications that will complete the action one by one? For example, if I want to share a message I'll be using ACTION_SEND with a specified MIME type and I'll be prompted with a list of applications that can share the message. Can I make a user choose multiple apps to share message on Twitter, Facebook etc. at the same time? Thanks.
Comment: Not that I'm aware of - you'd most likely have to use the Facebook, Twitter etc APIs and write your own mechanism to do it.
Answer:
Is there any way to make user select multiple applications that will complete the action one by one?

Not native to Android.
That being said, there is nothing stopping you from using PackageManager and queryIntentActivities() to create your own chooser that allows multiple selection, then dispatches the event to each checked item one by one.
Comment: @Egor: https://github.com/commonsguy/cw-omnibus/tree/master/Introspection/Launchalot -- that sample project demonstrates using the aforementioned APIs to implement an app launcher. In your case, you would make it multiple-choice and substitute in your own `Intent` instead of the one I am using, plus update the UI to meet your needs.
Answer: The way OS handles it, seems no.
You talk about this, right?
Because you load text, and/or image, and then sharing it.
Lot of apps can handle it, but every app handles it with different way.
May the app who when get text and/or img, do nothing!
e.g G+, asks you what circles you want to share with.
facebook i dont know, i dont use it.
SMS/MMS: may see if there is a picture or something to choose between them.
Even dropbox sometimes thinks can handle some sharings, but eventually it cant!
Also, there is no option for multiple select in sharing.
If there was, what was going to happen?
eg selected g+ and twitter, open first the G+ New post Activity,
and when you finish, open the Twitter one?
Maybe using API's for those soc. networks, but user may have to give again its credencials.
Comment: Thank you for your answer, you got the question absolutely right.

Multiple Intent receivers?


Getting "Parameter undefined" in jQuery with AJAX, MySQL and PHP

Question: I'm building a shopping site in PHP with mysqli database and I have a "category" and a "brands" sections in that.
What I want is that the user can filter the products in the store by clicking on category & brands section without page refreshing with help of ajax jQuery.
For example on Category>Electronics and it will show him the Electronics products on site main page.
Maybe with the code, it will be clearer.
This is the part of the HTML:

Products

This is the PHP code in the "action.php" file:
    <?php
    if(isset($_POST["getSelectedCategory"])){
        $cid=$_POST["categoryID"];
        $sql="SELECT * FROM products WHERE productCat = '$cid' ";
        $run_query=mysqli_query($con, $sql);
        while($row=mysqli_fetch_arry($run_query)){
            $productID = $row["productID"];
            $productCat = $row["productCat"];
            $productBrand = $row["productBrand"];
            $productTitle = $row["productTitle"];
            $productPrice = $row["productPrice"];
            $productIMG = $row["productIMG"];

            echo "

$productTitle

$productPrice.00$
    <button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>

 ";

 }

}
?>

This is the jQuery code:
   $("body").delegate(".category","click",function (event) {
        event.preventDefault();
        var cid = $(this).attr("categoryID");

        /*Used this alert to see if the
         right category number is shown, Here it says undefined*/
        alert(cid);
       $.ajax({
            url: "action.php",
            method: "POST",
            data: {getSelectedCategory: 1, categoryID: cid},
            success: function (data){
                $("#getProduct").html(data);
            }

        })
    });

I can't seem to find the problem in my code.
Comment: Where are you storing `categoryID`? Do you not mean `$(this).attr('id');`?
Comment: I'm storing it in my database, in a table called "products".
Comment: Read the second part of my comment.
Comment: when you alert cid, it return correct parameters?
Comment: No. as you can see in   `$cid=$_POST["categoryID"];` it wants 'categoryID'.
Comment: @NicolòCozzani No. its gives "Undefined".
Answer: You js code is listening to .category class. And there is no such class in your php code template. That's how your echo should look like to work:
echo "

$productTitle

               $productBrand
                $productPrice.00$
             <button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>

 ";

Look - I've added $productBrand  to you panel-header.
Comment: It is still undefined.
Comment: You now how to use inspector, right? RightClick on the `` that I added, then look what is the value if categoryID attribute. If there is no value - then you have troubles with DB - some goods are without brands and categories.
Comment: I dont know how to use it. do you mean F12 in chrome?
Comment: yes, web inspector. F12 in chrome or right click and then 'inspect the element'
Comment: you have a mispelling in your while loop - mysqli_fetch_arry should be mysqli_fetch_array()
Comment: also, try just running the php script on its own. so at the top of the script set $_POST["getSelectedCategory"] = 'WHATEVER' and run it to debug and see what you are getting back.


Two-Component distribution modelling

Question: I am trying to plot a two-component mixture distribution $F_X(x):.7N(0,1)+.3N(3,1)$ with density
$$f_X(x) = {0.7 \over {\sqrt{2\pi}}} e^{−x^2/2} + {0.3 \over {\sqrt{2\pi}}}e^{−(x−3)^2/2} $$.
I have done the histogram for it but having trouble with plotting the true density,so far this is my code
x <- rep(na,2000)
mu1 <- 0
sd1 <- 1
mu2 <- 3
sd2 <- 1

for(i in 1:n){
    u <- runif(1,0,1)
    if (u < .7){
        x[i] <- rnorm( 1, mu1, sd1)
    }else
        x[i] <- rnorm( 1, mu2, sd2)
    }

hist(x,prob=T)

Comment: Rearranged the math a bit for you, making it a little clearer; hope you don't mind.
Answer: Try:
x <- seq(-3, 6, by=0.01)
fx <- 0.7*dnorm(x) + 0.3*dnorm(x,3)
plot(fx~x, type='l')

to get:

Two-Component distribution modelling


Game Development: Should I program my levels or interpret them from a file?

Question: The game will be written in C++
Programming:
enemies.puch_back(new DefaultEnemy(200, 300, 3, 5));
enemies.puch_back(new DefaultEnemy(500, 400, 4, 5));
enemies.puch_back(new DefaultEnemy(300, 420, 3, 15));
enemies.at(2).createAward(new Key(4), "pling.wav");

Or Interpret them from a file like this:
DefaultEnemy 200 300 3 5
DefaultEnemy 500 400 4 5
DefaultEnemy 300 420 3 15
CreateAward 2 "pling.wav" Key 4

Program it would be more easy and people can't (without speaking of hacking) edit your levels. But it maybe a bit rubbish to program it all? Are there other reasons to choose for programming or interpreting?
How about memory-management (if I should go for interpreting)?
How to delete the (game)objects when the level unloads?
Comment: In addition to what Konerak said - store them in a platform-independent file type; XML. A good library for reading it is TinyXML. Platform-independent because storing in binary will get you issues like byte-endianess.
Comment: @Poni: Thanks for TinyXML! I think I'm going to use that!
Comment: Noticed a small typo: push has an S in it, not a C :) Verder alles ok!
Answer: Always separate application from data.
Comment: Separation is good and will improve maintainability, but the best way to accomplish this might be by modular code following good encapsulation practices.  Unless there's a need for users to change the levels, why build your own parser, semantic checker, etc when the compiler does all of that for you?  Also, compiling the levels will make the game load much faster.
Answer: First variant is equivalent to hardcoding game resources. This is absolutely bad and is suitable only for debugging.
Every games store their resources in external files - xml, archived packages and parse and load them during runtime.
Therefore, modern game engines almost every time have their set of tools which is bundled with it.
Deleting game resources is also a vast question - it depends. Depends on your objects' lifetime management and on that fact if you need to unpack your data into temporal files.
Comment: Your statements are way too general and provide no evidence to back them up.
Comment: @Ben Don't you think that this kind of *"general"* question requires a non-general answer?
Comment: You say *absolutely bad* and *every game*, when in fact these statements are only true of _some_ games.  Perhaps the majority, perhaps not, but it definitely isn't as universal a rule as you try to make it.
Answer: Well I would save the level design in a file. Thats what scripting is for right. This then gives me a way to JUST change the levels..
Also It will keep your objects (the stuff used in the levels) seperate from the logic (the game logic). This will help debugging and have a clearer structure
Comment: Actually, writing the levels in a language the debugger knows will help debugging.  With a level interpreter, you'll just end up stepping though the interpreter implementation and it will be much harder to follow the high level logic.
Answer: Depends on if you can spare the resources for interpretation, and who else you intend to use your work. If you and you alone are creating it, then there's nothing wrong per se with hardcode.
If, however, you ever intend users or anyone else to modify it, ever, then interpret.
Comment: I disagree. Hardcoding means recompiling everything each time you want to change something as little as the position of an enemy. Even if you're developing alone it's a pain. Pretty much any non trivial game uses external data file instead of hardcoding them.
Comment: Depends on if you have other reasons to recompile each build, and how long it will take you to create a suitable file format. Interpreting stuff isn't free on the dev time either.
Comment: @nico: That is also true... But, always reinterpreting it when the level loads OR recompile it once when the level changes....
Comment: External file for level information can by a dynamic library containing code just as easily as a data file.  No need for recompiling *everything*, and with a decent makefile system, you may only recompile a single function.  With code, it's also a lot easier to add a hook for changing things at runtime.