How do I migrate the "Created" and "Modified" date fields?

Question: I created a migration script to test this out.
This is the code I used.
<code>id: article_csv_import
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: Import articles
label: 'Import articles'
source:
  plugin: csv
  path: 'modules/custom/sigtarp_migrate/data/articles.csv'
  header_row_count: 1
  ids:
    - id
process:
  nid: id
  title: title
  body/format:
    plugin: default_value
    default_value: full_html
  body/value: body
  changed:
    plugin: callback
    source: update
    callable: strtotime
    created: date
  created:
    plugin: callback
    source: update
    callable: strtotime
    created: DateCreated
  status: Status
  type:
    plugin: default_value
    default_value: article
destination:
  plugin: 'entity:node'
migration_dependencies:
  required: {  }
</code>
When I run the migration script, this is what happen when both the Changed and Created fields are entered.

This is the content of the CSV file used for the migration.

Why is the date off? How can I fix it?
Comment: May have todo with timezone, can you show what your csv looks like when opened on Notepad? Want to make sure your Excel isn't hidding things.
Comment: Here here what it look like in my csv
Comment: id,title,body ,DateCreated,update,Status
1,title 1,some body text 1 ,4/3/1994,4/3/1994,1
2,title 2,some body text 2 ,4/13/1996,4/13/1996,1
3,title 3,some body text 3,9/25/2003,9/25/2003,1
Comment: instead of the plugin: callback
Comment: from_format: 'm/d/Y'
Comment: So what is to_format: ''
Comment: did not work I becaue you the lead year
Answer: Turns out that for created & changed dates, they are stored differently than field_date's, you must convert these to Unix universal time.
<code>  changed:
    plugin: format_date
    source: update
    from_format: 'm/d/Y'
    to_format: 'U'
    from_timezone: 'UTC'
    to_timezone: 'UTC'
  created:
    plugin: format_date
    source: DateCreated
    from_format: 'm/d/Y'
    to_format: 'U'
    from_timezone: 'UTC'
    to_timezone: 'UTC'
</code>
Comment: Thanks you so much


Durrett exercise 3.2.5: how to apply dominated convergence?

Question:
Suppose $g,h:\Bbb R\to\Bbb R$ are continuous with $g(x)>0$ and $|h(x)|/g(x)\to 0$ as $|x|\to\infty$. If $F_n\implies F$ (indicating weak convergence) and $\int g(x)dF_n(x)\le C<\infty$ then
  $$\int h(x) dF_n(x)\to \int h(x) dF(x).$$

What is known is the embedding theorem: we can have $Y_n$ equal in distribution to $X_n\sim F_n$ and $Y$ equal in distribution to $X\sim F$ such that $Y_n\to Y$ a.s. Obviously this tells us to apply Dominated Convergence Thm. In particular, we must find another random variable $Z$ on the same probability space that dominates all $h(Y_n)$ and is integrable itself. However, I don't know how to find it, although I believe we must start from $g(Y_n)$ which dominate $h(Y_n)$ in a sense, but I have no idea how to formally write it out.
Answer: Using the embedding theorem, we are reduced to prove that if $C :=\sup_n\mathbb E\left[g\left(Y_n\right)\right]< +\infty$ and $Y_n\to Y$ almost surely, then $\mathbb E\left[h\left(Y_n\right)\right]\to \mathbb E\left[h\left(Y\right)\right]$. This can be done by dominated convergence. Fix a positive $R$ and define a continuous function $\phi_R$ which takes the value $1$ on $[-R,R]$ and $0$ outside $\mathbb R\setminus[-R-1,R+1]$, and $0\leqslant \phi\leqslant 1$. Now, we use the inequalities
$$\left|\mathbb E\left[h\left(Y_n\right)\right] -\mathbb E\left[h\left(Y\right)\right]\right|\leqslant \left|\mathbb E\left[h\left(Y_n\right)\phi_R\left( h\left(Y_n\right)\right) \right] -\mathbb E\left[h\left(Y\right)\phi_R\left(h\left(Y\right)\right )\right]\right|+ \left|\mathbb E\left[h\left(Y_n\right)\left(1-\phi_R\right)\left( h\left(Y_n\right)\right) \right] -\mathbb E\left[h\left(Y\right)\left(1-\phi_R\right)\left(h\left(Y\right)\right )\right]\right|\\ \leqslant \left|\mathbb E\left[h\left(Y_n\right)\phi_R\left( h\left(Y_n\right)\right) \right] -\mathbb E\left[h\left(Y\right)\phi_R\left(h\left(Y\right)\right )\right]\right|+ \left|\mathbb E\left[h\left(Y_n\right)\left(1-\phi_R\right)\left( h\left(Y_n\right)\right) \right] \right| +\left|\mathbb E\left[h\left(Y\right)\left(1-\phi_R\right)\left(h\left(Y\right)\right )\right]\right|.$$
Since for any real number $t$, $\left|h(t)\right|\cdot\left(1-\phi_R\right)(h(t))\leqslant \left|h(t)\right| \mathbf 1_{\mathbb R\setminus  [-R,R] }(h(t))\leqslant g(t)\sup_{|x|\geqslant R}\left|h(x)\right| /g(x)$ and $\mathbb E \left[g\left(Y\right) \right] \leqslant \liminf_{ n\to +\infty} \mathbb E \left[g\left(Y_n\right) \right]\leqslant C $, we derive that
$$\tag{*}  \left|\mathbb E\left[h\left(Y_n\right)\right] -\mathbb E\left[h\left(Y\right)\right]\right|\leqslant \left|\mathbb E\left[h\left(Y_n\right)\phi_R\left( h\left(Y_n\right)\right) \right] -\mathbb E\left[h\left(Y\right)\phi_R\left(h\left(Y\right)\right )\right]\right| +2C\sup_{|x|\geqslant R}\left|h(x)\right| /g(x).$$
From continuity of $h_R$, we infer that  $h\left(Y_n\right)\phi_R\left( h\left(Y_n\right)\right)\to h\left(Y\right)\phi_R\left( h\left(Y\right)\right)$ almost surely and $\left| h\left(Y_n\right)\phi_R\left( h\left(Y_n\right)\right)\right|\leqslant R$,  hence by (*),
$$\limsup_{n\to  +\infty} \left|\mathbb E\left[h\left(Y_n\right)\right] -\mathbb E\left[h\left(Y\right)\right]\right|\leqslant 2C\sup_{|x|\geqslant R}\left|h(x)\right| /g(x).$$
Comment: Thanks. This is brilliant.


Como remover um arquivo de um repositório Git sem deletá-lo localmente?

Question: Eu gostaria de remover um arquivo ou diretório que foi enviado ao repositório Git erroneamente, mas sem removê-lo dos meus arquivos locais. Qual comando git executa tal ação?
Answer: Passe o parâmetro --cached para o git rm:
git rm --cached arquivo.txt
Para diretórios, remova recursivamente com -r:
git rm --cached -r diretorio


HMVC e a Componentização do HTML

Question: Eu já li vários artigos sobre HMVC, tanto em PHP como em outras linguagens, e em todos eles a implementação do padrão girava em torno de se ter um "Controller-mestre" o qual requisitava o Response Body de um ou mais recursos, internos ou externos, via cURL ou Stream Contexts, a fim de montar o seu próprio, diretamente num objeto responsável pela Resposta, ou através de uma View Engine própria, criando variáveis de template com o(s) HTML obtido(s).
Porém, todos esses artigos se apegavam muito ao conceito técnico e por vezes não abrangiam todos os pontos pertinentes. Com isso a conclusão a que eu pude chegar foi a de que o conceito básico do HMVC é, a grosso modo, MVCs dentro de MVCs, os quais funcionam tanto hierárquica quanto isoladamente, sempre da mesma forma.
Mas como exatamente ocorreria a componentização do HTML desse "Controller-mestre" se, para que cada subsistema funcione da mesma forma em todos os sentidos seriam necessários eventuais scripts, folhas de estilo ou mesmo marcações adicionais?
Com um exemplo fica mais fácil de entender:
Considerando uma aplicação cuja GUI seria desenvolvida com o Bootstrap e composta por N componentes, todos também desenvolvidos com o mesmo framework (para que isoladamente funcionem igual a aplicação principal), com um HMVC figurativamente criado pelo pseudo-código abaixo:
// Make the Requests

$projects = new Request( 'management/projects', 'GET' );
$clients  = new Request( 'management/clients',  'GET' );

// Creates the Template Variables with Response Bodies HTML

$this -> view -> assign(

    array(

        'projects' => $projects -> send(),
        'clients'  =>  $clients -> send()
    )
);

A título de clarificação desse fragmento, Request::send() estaria retornando o HTML

Resultaria num HTML similar a:

    <meta charset="utf-8">

    <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

Sidebar Item

Sidebar Item

Sidebar Item

                        <meta charset="utf-8">

                        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

Component HTML

O que nesse exemplo simples é "apenas" incorreto, afinal, numa aplicação real poderíamos ter conflito de script, ou regras CSS que fazem uso do !important bagunçando com o HTML existente depois da seção designada para o componente (um rodapé, por exemplo) e etc.
Sendo assim, como que deveria ocorrer a componentização do HTML num HMVC?
A menor idéia que me ocorre seria a de o "Controller-mestre" analisar o HTML de retorno e pegar só aquilo que estivesse dentro do do , mas eu não vi nada nem remotamente similar a isso naquilo que eu pesquisei.
Comment: O Kohana tem um modelo HMVC. [*Esse link*](http://techportal.inviqa.com/2010/02/22/scaling-web-applications-with-hmvc/) tem algumas considerações sobrer HMVC.
Comment: Mas você viu que em momento algum ele toca no problema da dúvida que eu levantei? No artigo a construção do tal *Gazouillement* apenas demonstra a técnica de composição, mas não abrange como o HTML final ficaria. A *View* que ele constrói com os dados recebido não especifica esses *Response Bodies* já vêm limpos de quaisquer marcações desnecessárias para Aplicação principal ou se algo mais está sendo feito.
Comment: Por que HMVC e não SOA ?
Comment: Talvez porque eu não saiba muito mais do que apenas a definição de SOA. u.u'
Answer: Bruno Augusto, os componentes HTML podem ser organizados, na estrutura HMVC, em script's separados.
Ou seja, separe o template da sua aplicação dos scripts HTML referentes ao conteúdo.
Com base no exemplo que você citou, você teria algo como:
Um arquivo para o layout, que como no seu exemplo seria as questões equivalentes em todos os subsistemas.
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

Sidebar Item

Sidebar Item

Sidebar Item

            <?php
                /* Exemplo de renderização do conteúdo da página requisitada
                *  Irá variar de acordo com o framework ou componentes que você está utilizando na sua aplicação.
                */
                echo $this->content;
            ?>

Um arquivo apenas com o conteúdo da página projects:

Página Projects

Component HTML

Um arquivo apenas com o conteúdo da página clients:

Página Clients

Component HTML

Comment: Sua resposta termina onde eu estou com dificuldades. No seu exemplo o HTML de cada componente **não possui** as demais tags (``, `` e etc). Um componente escrito nesses moldes, só funcionaria **exatamente** igual quando parte da Aplicação principal, seguindo o exemplo dado, se violássemos a semântica e inseríssemos o CSS/JS do Bootstrap diretamente no `` ao invés de no ``. Além disso, casos específicos, como os que envolvem scripts que precisam ser carregados no ``poderiam não funcionar como esperado isoladamente pois o componente não teria sua tag própria.
Comment: Os componentes não devem possuir as tags (``, `` e etc), pois a ideia é que cada componente seja injetado, de acordo com a requisição, em um layout padrão da sua aplicação. Caso você queira adicionar outras bibliotecas dependendo do componente requisitado, você pode pensar em uma solução que faça o carregamento das bibliotecas no seu HTML de acordo com a requisição ou, em alguns casos, criar um layout que inclua as bibliotecas necessárias.
Comment: Mas isso eu sei, afinal é a mínima noção sobre modularização de HTML aprendida ao trabalhar com querystrings. A pergunta em si não é sobre a criação de um componente e sim sobre manter o HTML da aplicação principal válido, semântico, quando "plugar" os módulos à ela **sem impedir** que tais componentes funcionem isoladamente, que tanto quanto pude encontrar de informação, é a base do HMVC. Se eu remover as tags "supérfluas" dos componentes, parte da característica deles no meio HMVC se perde, pois eles não serão sozinhos o que são combinados com a Aplicação consumidora.

HMVC e a Componentização do HTML


Is a high number of support vectors a sign of overfitting?

Question: I've tuned a SVM with radial kernel that has training error about 10%,
but test error is about 38%, which surprise me.
I tried to understand what may cause this and noticed the number of support vectors is high, about 50% of the observation are support vectors. Is this the cause of the problem? Does high number of support vectors leads to a high
variance SVM?
Here is the summary of the SVM.
<code>Parameters:

   SVM-Type:  C-classification

 SVM-Kernel:  radial

       cost:  31.62

      gamma:  1e-04

Number of Support Vectors:  117

 ( 58 59 )

Number of Classes:  2

Levels:
 high low
</code>
Comment: Test error will always be larger than training error. Why are you surprised, precisely?
Comment: @user777 by the difference between training and test error, that is about 28%. I've applied the SVM to other dataset, the differences are usually about 5-10%.
Comment: But this is a different data set, correct? Perhaps the relationship between features and outcome is weaker in this data, or there are many low-quality input features, or you need a more specialized kernel function, or you need more data to learn the boundary in the feature space...
Comment: How many observations did you have in the training sample ?
Comment: @user777 that's true! I randomly split the observation set into training and test set with 50/50 split. I guess I didn't the expect the relationships between x and y are so different among them.
Comment: @fcoppens there are 196 in training set and 196 in test set, both are derived from random splitting the full dataset.
Comment: I think you have a problem of overfitting, there are some results on error bouds and the lnk with the number of support vectors but I am not an expert in that.  Nevertheless a very high fraction of support vectors is an indication of overfit.  Maybe you should re-phrase your question "Is a high number of support vectors a sign of overfitting ? "
Comment: @fcoppens I changed the title based on your suggestion. thanks.
Answer: YES, a large number of support vectors is often a sign of overfitting.
The problem appears to be that you have chosen optimal hyperparameters based on training set performance, rather than independent test set performance (or, alternatively, cross-validated estimates).
The problem
Never evaluate a set of hyperparameters based on training set performance, because you will inevitably end up with an immense overfit. Consider the RBF kernel:
$$K(\mathbf{u},\mathbf{v}) = \exp(-\gamma \|\mathbf{u}-\mathbf{v}\|^2).$$
Now, take the following limit case:
$$
\lim_{\gamma\rightarrow\infty} K(\mathbf{u},\mathbf{v}) =
\left\{ \begin{matrix}
0, & \text{if } \mathbf{u}\neq\mathbf{v},\\
1, & \text{otherwise.}
\end{matrix} \right.
$$
Which essentially means that, for $\gamma\rightarrow\infty$ the kernel matrix becomes the unit matrix. This allows the resulting model to always fit the training data perfectly, with each instance becoming a support vector, but learn absolutely nothing.
The solution
If you want to optimize hyperparameters, you must always estimate the generalization performance of a given set of hyperparameters based on unseen data. The most common approach is via cross-validation, e.g. $k$-fold or leave-one-out.
Note that, when you are tuning hyperparameters based on cross-validation, it is still effectively possible to overfit. You can reduce this to some extent by using several iterations and/or more folds, but the inherent issue remains.
Comment: Hi, thanks for your comments, I really like the example you give to demo the problem. I used the `turn` function in R to find the optimal parameter, and I believe it use 10-folder CV by default. The high test error rate is probably due to the splitting that gives different data characteristics between the two datasets because the sample size is small (about 400). Thanks for you answer to the question, I'd keep it in mind when apply SVM.


comparação usando caracteres em c

Question: Ok, o problema so esta na função q31 e na q311.
http://pastebin.com/8CJwKej4
Deixei o codigo completo no link acima.
então aqui esta funçao q311:
void q311(){
char forma;
int n,jota,b,i,j;
printf("Informe a figura e o tamanho: ");
scanf("%c",&forma);
scanf("%i",&n);
    if (forma=='q')
    {
        for ( i = 0; i < n; ++i)
        {
        printf("*");
            for ( b = 1; b < n; ++b)
            {
                if ((i==jota)|| (i==0))
                {
                    printf("*");
                }
                else if (b==jota)
                {
                    printf("*");
                }
                else
                    printf(" ");
            }
            printf("\n");
            }
        }
    else if (forma=='t')
    {
        for(int i=n-1;i>=0;i--)
        {
            for(int j=0;j<=i;j++)
            {
             if(i==n-1 || j==0 ||i==j)
                 printf("*");
              else
                printf(" ");
        }
          printf("\n");
         }
    }
    else
        printf("Forma Invalida\n");

}

O meu programa sempre da como saída "Forma Invalida" mesmo que voce digite "t" ou "q"... Queria saber por que isso esta acontecendo.
Comment: Eu executei a função postada como um programa e funcionou certinho. A comparação de caracteres que está fazendo está certa. Pode ser lixo, tente usar `fflush(stdin)` antes do `printf`.
Comment: qual printf? o primeiro?
Comment: voce acha que a string esta com valor de lixo?
Comment: Sim pode acontecer, afinal você tem um programa grande com várias funções. Tente usar o comando antes do primeiro `printf`. Tente executar a função isoladamente como eu fiz e depois conte-me o resultado.
Comment: Estranho! Realmente funciona ...
Comment: Mas nao tem como resolver para o programa grande?
Comment: O `fflush(stdin)` não resolveu?
Answer: O que ocorre é que stdin está com o caractere que você tinha digitado na função principal para escolher a função q311, um "enter". E um enter realmente não é um "t" ou um "q".
A forma mais simples de corrigir isso é fazendo com que o scanf ignore o "enter" acrescentando um espaço antes do tipo:
scanf(" %c",&forma);

Recomendo duas leituras:
Uma pergunta nossa.
Um material externo.
Comment: Muito obrigado, o fflush(stdin) não tinha funcionado.

comparação usando caracteres em c


How to initialize a variable value

Question: Let's assume a scenario. We have a list of musicians (coming from an API service call in JSON format)who can play different genres of music
Now I'm supposed to display these Genres along side the name of the musician.
There is a small requirement . We can only display 3 genres next to the name. If the musician can play more than 3 genres the names should be displayed somewhere else, maybe a pop up for more info. How can I keep a count of this no of genres for a particular musician, so that if the genres more then 3 then only I need to display the others in ye pop up.
Until now 1.div id musicians  for let x of musicians
..........
2. div  {x,musicianName}
3.div Genres
span ngIf x,genreMetal Metal
4.span ngIf x,genreClassical Classical
5.span ngIf x,genreIndie Indie
6.span ngIf x,genreMetal & x,genreClassical & x,genreIndie & x,genreRock ..(This is to depict that there are more genres to this musician
Until now hardcoding is what I was doing. I want to make this dynamic. My approach was to use nginit and make a count using interpolation as the values of these genres are coming as 1 and 0. But it's not happening as there must be something that I may be doing wrong.
Please help..
Comment: Show us what you have already tried, we aren't here to code for you !
Comment: We need details on what you have so far.
Comment: I suppose you should hold all musican's genres as array. In view template you would show only 3 and you would can show genres count.
Comment: Yes @grzesiek I'm trying to imply this. The problem is now these genres are coming from a json and it belongs to an individual musician. In the HTML code I don't have that much flexibility such as to create a new array where I can keep the list of genres and display them according to the condition. Here is the part where i'm Stuck
Answer: With the information you provided, and assuming the array of genres is called "genres", the number of genres would be "artist.genres.length".
Then to display only the first three, you may want to display "artist.genres.slice(0,2)" and then the rest would go in "artist.genres.slice(3, artist.genres.length - 1)"
Finally do one thing or another based on the condition "artist.genres.length > 3"
--------------- Edit based on original question edits --------------
If you are just trying to figure out whether there are three or more genres in that json, what if you do:
<code>countGenres(artist) {
   let c=0;
   for(let prop of artist) {
      if(prop.startsWith('genre')) c++;
   }
   return c;
}
</code>
That would basically count all the genres an artist has, based on the assumption that the properties for each genre starts with the word "genre".
Then ngIf on a span for that function to display either less than three or more than three.
Comment: The artist.genre is not a list of genres that a length function can be used.
Comment: so what is the data type of artist.genre? if it isn't an array... is it something you can do "split()" on? e.g. a comma separated list of genres?

In that case do:
artist.genre = artist.genre.split(',')

and voilà, now artist genre is indeed something with a .length attribute
Comment: Yes I indeed got your point. But let's don't categorise that the list of genres are under one particular key. Just imagine that the genres are coming in this way in the json. Isclassical:1, is rock:0, isindie:1 etc etc. so I was showing these genres by writing an if statement in the ui side.
Comment: Edited the answer with another approach

How to initialize a variable value


convert image to video on server-side by php

Question: My visitors upload pictures to server. My website gives a sequencial name for these uploads (e.g. 0001.jpg, 0002.jpg, 0003.jpg...) What I want to do is, on request from user, I want to create a movie (preferably not flash) on server-side and send this video to client. How can I do this?
Answer: You have to use ffmpeg for creatiion video on serverside. It is very flexible and really powerful tool for working with video, audio and images.
for example, to convert images image1.jpg, image2.jpg,.. into video use this command
<code>ffmpeg -f image2 -i image%d.jpg video.mpg
</code>
To execute this command from php use exec or system function.
PS. There are other command line utilites can be used to create video from images ogg-slideshow and dvd-slideshow. They very convenient if you want to add some
predefined transition effects or titles.


Find $y^{(n)}(0)$ for every $n$.

Question: Let $y(x)$ fulfill $y''-xy=0$. Furthermore: $y(0)=0,y'(0)=1$. Find $y^{(n)}(0)$ for every $n$. I tried different forms of recurrence relations but I couldn't do much with it without it becoming a complete mess. This is what I got:
$f^{(n+2)}=n\cdot y^{(n-1)}+x\cdot y^{(n)}$.
I would really appreciate your simplifying.
Answer: Hint: write the solution $y$ as a power series $y\colon x\mapsto \sum_{n=0}^\infty a_n x^n$, and see what the differential equation and the initial conditions impose on the $a_n$'s.
Then, use the relation between $a_n$ and $y^{(n)}(0)$.
Answer: Why mess? Because you should calculate $y^{(n)}(0)$, not in other point, it could be not too messy:
$$0=y''-xy, \; \text{so} \; y''(0)=0$$
$$0=(0)'=(y''-xy)'=y^{(3)}-xy'-y \; \text{so} \; y^{(3)}(0)=y(0)=0$$
$$0=(y^{(3)}-xy'-y)'=y^{(4)}-y'-xy'-y^{'}=0  \; \text{so} \;y^{(4)}(0)=2y'(0)=2$$
Can you find a general pattern?
Comment: I'm sorry. It was a typo.
Comment: That is not correct. $y^{(4)}(0)=2..$ because $y''=xy$ and therefore $y^{(3)}=y+xy'$ and $y^{(4)}=y'+y'+xy''$ and therefore $y^{(4)}(0)=2y'(0)+xy''(0)=2+0=2$.
Answer: A hint:
Prove, using induction, that
$$y^{(n+3)}=(n+1) y^{(n)}+x y^{(n+1)}\qquad(n\geq0) \ ;$$
then put $x=0$.
Answer: Thank you all for your help. I post this answer as an attempt and application of your advises. Feel free to correct me.
$y=a_0+a_1x+a_2x^2+...+anx^x+...$
Since $y(0)=0$, $y=0$ and we get $a_0=0$. Therefore $y=a_1x+a_2x^2+...+anx^x+...$.
$y'(0)=a_1+a_20+....=a_0=1$. Therefore $y=x+a_2x^2+...+anx^n+...$.
$y''=2a_2+2\cdot 3\cdot  a_3+3\cdot4\cdot a_4 x^2+...+(n-1)\cdot n\cdot a_n x^{(n-2)}...=yx=x^2+a_2x^3+...+anx^{n+1}+...$. We get that $a_2=a_3=0,a_n=a_{n+3}\Rightarrow a_4={1\over 3\cdot 4},a_7={1\over 3\cdot 4\cdot6\cdot 7}...a_{3n+1}={1\over 3\cdot4\cdot6\cdot7....(3n-1)\cdot 3n}$ and that $a_2=a_3=a_5=a_6=...=a_{3n}=a_{3n+2}=0$.
Therefore(for $n\ge 2$): $y=x+({1\over 3\cdot 4})\cdot x^ 4+({1\over 3\cdot 4\cdot 6\cdot 7})\cdot x^7+...+({1\over 3\cdot4\cdot6\cdot7....(3n-1)\cdot 3n})\cdot x^{3n+1}+...$
$y^{(1)}=1+({1\over 3})\cdot x^ 3...$ $\to 1$
$y^{(2)}= x^ 2...$ $\to 0$
$y^{(3)}= 2x...$ $\to 0$
$y^{(4)}= 2...$ $\to 2$
.
.
.
$({1\over 3\cdot 4\cdot 6\cdot 7})\cdot 7!...$ $\to 10$
And in 3 more cycles it is again not $0$ but $7!$.
It is easy to see, hence, that:
$y^{(n)}(0) =
\begin{cases}
{n!\over 3\cdot4\cdot6\cdot7....(3k-1)\cdot 3k},  & \text{if $n=3k+1$ with $k\in\Bbb{N}$ } \\[2ex]
0, & \text{otherwise.}
\end{cases}$

Find $y^{(n)}(0)$ for every $n$.


Sharp and flat errors

Question: Why does an error occur during using sharp or flat?
I just added a few more notes with "is" or "es" to my code:
         \relative {
      %\key g \minor
     % \numericTimeSignature
      \tempo "Tempo indication" 8=114
      %\time 7/4
      \pad
      \partial 8 % use part of the time
      g'4\fsol
      \pad {d'4\fre d\fre g,4\fsol c4\fdo c4\fdo g4\fsol
      b2.\fsi r4 g4\fsol
      d'4\fre d4\fre g,4\fsol c4\fdo b4\fsi g4\fsol} \undo \pad % using group \pad --start and stop for the group...
      ***c dis d c aes***  % just for examples....

 }

What am I doing wrong of using them?
Parsing...
C:/Users/TOMMY_~1/AppData/Local/Temp/frescobaldi-ro92knuj/tmpi_my1xgx/Aint-Necessarily-So.ly:85:5: error: not a note name: dis
  c
    dis d c aes  % just for examples....

C:/Users/TOMMY_~1/AppData/Local/Temp/frescobaldi-ro92knuj/tmpi_my1xgx/Aint-Necessarily-So.ly:85:13: error: not a note name: aes
  c dis d c
            aes  % just for examples....

Comment: The indentation of the code is a mess. Can you [fix it](https://music.stackexchange.com/posts/117458/edit)? You can [edit (change)](https://music.stackexchange.com/posts/117458/edit) your question.
Answer: You are probably using a notename language that doesn't have "dis" or "aes".  Chord macro names apparently have been chosen with Italian note name conventions, but the actual note name language uses "g" and its ilk, so my guess would be that you have a \language "english" line somewhere which would make "gs" and "gf" be the names for g sharp and g flat, respectively.
Comment: Great, Thanks a lot for your detailed explanation. it works when I added "s" and "f" instead of "is" and "es".

Sharp and flat errors


phantomjs-pdf not work

Question: I'm using phantomjs-pdf in my sailsjs app. This code working fine in my local machine(ubuntu 14.0). but server machine(ubuntu 12.0) cause error, like below
<code>  internal/child_process.js:274
      var err = this._handle.spawn(options);
                                 ^
    TypeError: Bad argument
        at TypeError (native)
        at ChildProcess.spawn (internal/child_process.js:274:26)
        at exports.spawn (child_process.js:339:9)
        at Object.exports.execFile (child_process.js:141:15)
        at /var/www/test/node_modules/phantomjs-pdf/lib/phantomjs-pdf.js:83:16
        at /var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:721:13
        at /var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:52:16
        at /var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:269:32
        at /var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:44:16
        at /var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:718:17
        at /var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:167:37
        at async.series.paperFormat (/var/www/test/node_modules/phantomjs-pdf/lib/phantomjs-pdf.js:51:70)
        at /var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:713:13
        at Immediate.iterate [as _onImmediate] (/var/www/test/node_modules/phantomjs-pdf/node_modules/async/lib/async.js:262:13)
        at processImmediate [as _immediateCallback] (timers.js:371:17)
</code>
This is my error. Any one tell me what is the problem. help me.
Answer: Uninstall all NPM packages and then reinstall NPM packages.

phantomjs-pdf not work


How does one set an array in hlsl?

Question: In glsl, array = int[8]( 0, 0, 0, 0, 0, 0, 0, 0 ); works fine, but in hlsl this doesn't seem to be the case. It doesn't seem to be mentioned in any guides how you do this. What exactly am I meant to do?
Answer: For example, like this:
int array[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

Edit:
Ah, you mean array assignment. It seems like that is not possible for now. In addition to trying every possible sensible option, I cross-compiled simple glsl code to hlsl code using glslcc (which uses spirv-cross).
GLSL code:
#version 450

layout (location = SV_Target0) out vec4 fragColor;

void main()
{
    int array[4] = {0, 0, 0, 0};
    array = int[4]( 1, 0, 1, 0);
    fragColor = vec4(array[0], array[1], array[2], array[3]);
}

HLSL code:
static const int _13[4] = { 0, 0, 0, 0 };
static const int _15[4] = { 1, 0, 1, 0 };

static float4 fragColor;

struct SPIRV_Cross_Output
{
    float4 fragColor : SV_Target0;
};

void frag_main()
{
    int array[4] = _13;
    array = _15;
    fragColor = float4(float(array[0]), float(array[1]), float(array[2]), float(array[3]));
}

SPIRV_Cross_Output main()
{
    frag_main();
    SPIRV_Cross_Output stage_output;
    stage_output.fragColor = fragColor;
    return stage_output;
}

As you can see, in this case the equivalent hlsl code uses static const array and then assigns it since that kind of array assignment is allowed in HLSL (and makes a deep copy unlike in C/C++).
Comment: I mean after declaration, as in rewrite all values

How does one set an array in hlsl?


The limit of periodic function sequence is periodic

Question: Suppose $f_n(x)$ is continuous and periodic, $f_n(x+T_n)=f_n(x)$.
If we know that $f_n(x) \to f(x)$ uniformly and $T_n \to T$,
can we conclude that $f(x+T)=f(x)$ ?
Comment: Have you checked does the standard trick $$\vert f(x+T) - f(x) \vert = \vert \left ( f(x+T) - f_n(x+T) \right ) + \left( f_n(x+T)- f_n(x+T_n) \right ) + \left ( f_n(x+T_n) - f(x) \right \vert $$ work here?
Comment: This trick (especially, the second term in the sum) requires _uniform_ continuity to work, doesn't it?
Comment: @Evgeny yes, seems that $|(f(x+T)−f_n(x+T)|$ and $|(f_n(x+T_n)−f(x)|$ is OK, but i don't know how to deal with $| (f_n(x+T)−f_n(x+T_n) |$
Comment: @IvanNeretin Yes, it does, but I thought that since we are dealing with continuous functions on compact domains, the uniform continuity (for each $n$) holds automatically.
Comment: @Evgeny That's right, but who said we have a compact domain?
Comment: @IvanNeretin Do you have a counterexample? I have a handwaving argument and so might be mistaken. For each $n$ you have a _periodic_ function. You can narrow its domain down to one period, attach its limit points and prove uniform continuity for this segment. Endpoints require extra work, but I think it's manageable. Still might be mistaken.
Comment: @Evgeny I don't have a counterexample, just a hand-waving counterargument. True, if the functions are defined on $\mathbb R$, then periodicity+continuity enforce uniform continuity, and we are done. Still, I don't see how we rule out possible pathological cases (like, domain is neither $\mathbb R$ nor compact).
Comment: @IvanNeretin But aren't these conditions mentioned in the beginning of the question? It is said that all $f_n(x)$ are continuous and periodic with its own periods $T_n$.
Comment: @Evgeny Not quite. $\tan x$ is periodic and continuous _within its domain_, and the domain is not nice.
Comment: @IvanNeretin Yes, you are right. If domains are tricky it might require extra work. By the way, Zestylemonzi's answer avoids using uniform continuity of $f_n$ on their domains and requires only uniform convergence.
Answer: Hint:
$$|f(x+T) - f(x)| = |f(x+T) - f(x+T_n) + f(x+T_n) - f_n(x+T_n) + f_n(x+T_n) - f(x)|$$
Since the $f_n$ are continuous and converge uniformly, what do you know about $f$?
Hope this helps.
Comment: The $f_n$ converge uniformly. So given $\epsilon$ if you take $n$ sufficiently large then $|f_n(y) - f(y)| < \epsilon$ for all $y$ in your domain. This applies to $x+T_n$ too, even though it changes with $n$.
Comment: how to show that $ |(f_n(x+T)−f_n(x+T_n)|$ is small enough?
Comment: oh  i understand, thank you
Answer: There is a catch to the question as we can only assume that $f_n$ converges to $f$ uniformly on compact subsets
(for example $\sin (2\pi x/T_n)$ converges uniformly to $\sin(2\pi x/T)$ on compacts but not on ${\Bbb R}$, except if $T_n=T$)
Let $K_N=[-NT, NT]$  (compact interval). Then $f_{|K_{N+2}}=\lim (f_n)_{|K_{N+2}}$
 is continuous, being the uniform limit of continuous functions.
Let $\epsilon>0$ and find $0<\delta<T$ so that $x,y\in K_{N+2}, |x-y|< \delta \Rightarrow |f(x)-f(y)| < \epsilon/3$.
For $n$ large enough $\|f-f_n\|_{K_{N+2}}<\epsilon/3$ and $|T-T_n|<\delta<T$.
 Let $x\in K_N$. Then for any $x\in K_N$ we have  $x+T_n, x+T\in K_{N+2}$. So:
$$ |f(x)-f(x+T)|\leq \epsilon/3 + |f(x)-f(x+T_n)| \leq \epsilon + |f_n(x)-f(x+T_n)| = \epsilon$$ and $\epsilon>0$ was arbitrary. The above can surely be tidied up somewhat...
Comment: Okay, so the problem had two tricks: "usual" trick (when we add and subtract additional terms to form nice pairs which could be easily estimated) and the trick with $K_N$ :)


Linear mixed effect model, repeated measures or non-parametric test?

Question: I have this study design: two groups (A & B) measured in 3-time points (pre, follow-up & post). I thought that a linear mixed model effect was the preferred option because I do have missing values at random instead of using repeated measures ANOVA. Here is an example of my model:
m0<-lmer(VD ~ Group*Time + (1|ID))#linear model DV predicted by the IV (Group*time)
summary(m0)
anova(m0)#show model as anova
eta_sq(m0, partial=TRUE) #partial eta sq
r.squaredGLMM(m0)#adjust R2 for the model as an alternative

emmeans(m0, pairwise~Group)
emmeans(m0, pairwise~Time, adjust="bonferroni")
emmeans(m0, pairwise~Time|Group)

qqnorm(resid(m0))

Here's the output:
Type III Analysis of Variance Table with Satterthwaite's method
            Sum Sq Mean Sq NumDF  DenDF F value    Pr(>F)
Group          4.6     4.6     1 185.50  0.0049 0.9442174
Time       12756.9 12756.9     1 144.14 13.7144 0.0003024 ***
Group:Time   946.4   946.4     1 143.14  1.0175 0.3148195
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> eta_sq(m1, partial=TRUE) #partial eta sq
# Effect Size for ANOVA (Type III)

Parameter  | Eta2 (partial) |       95% CI
------------------------------------------
Group      |       2.65e-05 | [0.00, 1.00]
Time       |           0.09 | [0.03, 1.00]
Group:Time |       7.06e-03 | [0.00, 1.00]

r.squaredGLMM(m1)#adjust R2 for the model as an alternative
            R2m       R2c
[1,] 0.07850414 0.2317482
>
> emmeans(m1, pairwise~Group)
NOTE: Results may be misleading due to involvement in interactions
$emmeans
 Group emmean   SE   df lower.CL upper.CL
     0   43.3 3.71 74.3     36.0     50.7
     1   37.7 3.72 75.7     30.3     45.1

Degrees-of-freedom method: kenward-roger
Confidence level used: 0.95

$contrasts
 contrast        estimate   SE df t.ratio p.value
 Group0 - Group1      5.6 5.25 75   1.066  0.2897

Degrees-of-freedom method: kenward-roger

> emmeans(m1, pairwise~Time)
NOTE: Results may be misleading due to involvement in interactions
$emmeans
  Time emmean   SE df lower.CL upper.CL
 0.957   40.5 2.63 75     35.3     45.8

Results are averaged over the levels of: Group
Degrees-of-freedom method: kenward-roger
Confidence level used: 0.95

$contrasts
 contrast  estimate SE df z.ratio p.value
 (nothing)   nonEst NA NA      NA      NA

Results are averaged over the levels of: Group
Degrees-of-freedom method: kenward-roger

> emmeans(m1, pairwise~Time|Group)
$emmeans
Group = 0:
  Time emmean   SE   df lower.CL upper.CL
 0.957   43.3 3.71 74.3     36.0     50.7

Group = 1:
  Time emmean   SE   df lower.CL upper.CL
 0.957   37.7 3.72 75.7     30.3     45.1

Degrees-of-freedom method: kenward-roger
Confidence level used: 0.95

$contrasts
Group = 0:
 contrast  estimate SE df z.ratio p.value
 (nothing)   nonEst NA NA      NA      NA

Group = 1:
 contrast  estimate SE df z.ratio p.value
 (nothing)   nonEst NA NA      NA      NA

Degrees-of-freedom method: kenward-roger

However, when plotting the residuals it does not follow a normal distribution. It doesn't happen to all variables, only a few. Therefore, I was wondering whether I could still use mixed-effect models or if I should still move to a non-parametric test (if yes, which one would be best for my study design) or maybe try to log transform the variables.
Comment: Hi! It's impossible to tell by looking at the code. Please either add the output or explain what the output is.
Comment: Welcome to Cross Validated! What do you mean that it doesn't happen to all variables, only a few?
Comment: Utobi: I've added the output.
Comment: Dave: I have several DV, so some of them meet normality, and others don't (as in the example provided). So I want to know how to proceed with those that don't meet normality.  I hope I have explained myself better.
Comment: You first need to consider the process creating your dependent variable(s). E.g., are they measured directly and in the interval [-inf, inf], are they counts, are they cesored, are they proportions, are they fractions, ....
Comment: They are continuous variables, more precisely physiology variables (i.e.: blood pressure)
Answer: You have a modeling problem, as well as possibly a non-normality problem. My reading is that you have three time points, but if you look at the anova, you have 1 d.f. for Time because it is being modeled as a quantitative predictor rather than a factor. That's why in your emmeans output, you have results for just one time value -- the average value of Time -- rather than the three time points, and no comparisons for time.
So the non-normality is the lesser of your problems, given that the model itself has no reasonable interpretation.
For starters, I suggest fitting models like this:
m1 <- lmer(DV ~ Group * factor(Time) + (1|ID), data = data)

I suspect you may still have a non-normality problem for some response variables. That often comes up because the variation in the data is related to the mean, and you can tell the most about that situation by plotting the residuals vs. the fitted values:
plot (resid(m1) ~ predict(m1))

There will be six stacks of points for this model. If those vary in scatter is a systematic way (especially if they get more dispersed to the right than to the left), it can often be helped by transforming the response variable, e.g.,
m2 <- lmer(sqrt(DV) ~ Group * factor(Time) + (1|ID), data = data)
    ### or ###
m3 <- lmer(log(DV) ~ Group * factor(Time) + (1|ID), data = data)

The EMMs will then be on the transformed scale, but you can put the means (not the comparisons) back on the response scale by adding type = "response" to the emmeans() call.
It may serve you well to find a statistical consultant. It is vitally important to get the model right and to understand what you have. It isn't enough to just be able to get programs to run.
Comment: Thanks for all the information. I want to check whether there are differences between groups (treated vs control). I have followed your advice and log transform those variables which were not normally distributed. I thought my model was actually solid since I was following a similar article method with the same study design. But I'll make sure to check with a statistician.


Add button to table chart (AngularJS/Google Charts)

Question: I am trying to use the Table Charts component in an AngularJS 1.2.10 app.
I wrote a wrapper directive, which brings table chart into an AngularJS context.
    angular.module('my.charts.table', [])
        .directive('myTableChart', [function() {
            return {
                restrict : 'E',
                scope : {
                    columns : '=',
                    rows : '='
                },
                templateUrl : 'my.charts.table/myTableChart.tmpl.html',
                link : function(scope, element) {
                    var data = new google.visualization.DataTable();

                    // add columns

                    var table = new google.visualization.Table(element[0].childNodes[0]);

                    table.draw(data, { allowHtml : true });
                }
           };
       }
  ]);

For given columns and rows the data table is initialized and drawn.
What I want to do is to add a column, which holds a button with AngularJS directives.
<button class="btn btn-primary" onclick="alert(\'Works\')" ng-click="testLog()">Test</button>

You can assume that the testLog() method is defined on the current scope.
The table chart component allows the direct insertion of HTML as cell values. However, this lies outside of the AngularJS lifecycle and, therefore, simply inserting the above HTML snippet won't work.
Now, I tried to compile and link the button manually.
var btn = $compile('<button class="btn btn-primary" onclick="alert(\'Works\')" ng-click="testLog()">Test</button>')(scope);

I can append the button manually.
element.append(btn);

However, the table chart expects HTML, not a DOM element.
If I pass btn[0].outerHTML, the ngClick directive won't trigger.
Is there a way to solve this problem?
Here is the complete code snippet:

google.load('visualization', '1', {
  packages: ['corechart', 'table']
});

google.setOnLoadCallback(function() {
  angular.bootstrap(document, ['my.app']);
});

angular.module('my.app', [])
  .directive('myTableChart', function() {
    return {
      restrict: 'E',
      scope: {
        columns: '=',
        rows: '='
      },
      template: '

',
      link: function(scope, element) {
        var data = new google.visualization.DataTable();

        for (var i = 0; i < scope.columns.length; i++) {
          data.addColumn(scope.columns[i].type, scope.columns[i].name);
        }

        data.addRows(scope.rows);

        var table = new google.visualization.Table(element[0].childNodes[0]);
        table.draw(data, {
          width: '100%',
          allowHtml: true
        });
      }
    };
  })
  .directive('myTestTable', ['$compile',
    function($compile) {
      return {
        restrict: 'E',
        scope: {},
        template: '<my-table-chart ng-if="curRows != null" columns="curCols" rows="curRows"></my-table-chart>',
        link: function(scope, element) {
          scope.curCols = [{
            type: 'string',
            name: 'Test'
          }, {
            type: 'string',
            name: ''
          }];

          scope.curRows = [];

          scope.testLog = function() {
            alert('Works too');
          };

          var btn = $compile('<button class="btn btn-primary" onclick="alert(\'Works\')" ng-click="testLog()">Test</button>')(scope);

          var btnHtml = btn[0].outerHTML;

          element.append(btn);

          scope.curRows.push(['test entry', btnHtml]);
        }
      };
    }
  ]);
<my-test-table></my-test-table>

Answer: Better late than never, the following solution allows to trigger testLog event via ng-click directive:

since Google Chart google.visualization.Table does not support
adding DOM elements, move compilation from myTestTable to
myTableChart
to access testLog function from myTableChart directive scope, change the declaration to ng-click="$parent.testLog()"
perform compilation once the chart is rendered:
google.visualization.events.addListener(table, 'ready', function() {
    var table_div = table.getContainer();
    $compile(table_div)(scope);
});

Example

google.load('visualization', '1', {
  packages: ['corechart', 'table']
});

google.setOnLoadCallback(function() {
  angular.bootstrap(document, ['my.app']);
});

angular.module('my.app', [])
  .directive('myTableChart', function($compile) {
    return {
      restrict: 'E',
      scope: {
        columns: '=',
        rows: '='
      },
      template: '

',
      link: function(scope, element) {
        var data = new google.visualization.DataTable();

        for (var i = 0; i < scope.columns.length; i++) {
          data.addColumn(scope.columns[i].type, scope.columns[i].name);
        }

        data.addRows(scope.rows);

        var table = new google.visualization.Table(element[0].childNodes[0]);
        google.visualization.events.addListener(table, 'ready', function() {
            var table_div = table.getContainer();
            $compile(table_div)(scope);
        });

        table.draw(data, {
          width: '100%',
          allowHtml: true
        });
      }
    };
  })
  .directive('myTestTable', ['$compile',
    function($compile) {
      return {
        restrict: 'E',
        scope: {},
        template: '<my-table-chart ng-if="curRows != null" columns="curCols" rows="curRows"></my-table-chart>',
        link: function(scope, element) {
          scope.curCols = [{
            type: 'string',
            name: 'Test'
          }, {
            type: 'string',
            name: ''
          }];

          scope.curRows = [];

          scope.testLog = function() {
            alert('Works too');
          };

          var btnHtml = '<button class="btn btn-primary" onclick="alert(\'Works\')" ng-click="$parent.testLog()">Test</button>';
          scope.curRows.push(['test entry', btnHtml]);
        }
      };
    }
  ]);

<my-test-table></my-test-table>


.htaccess file blocks css, js but how?

Question: I have a .htaccess file inside an existing project folder. The code for the .htaccess file is below.
# Use PHP54 Single php.ini as default
#Options +FollowSymLinks
#Options +Indexes
RewriteEngine On
RewriteBase /
#RewriteRule ^users/([A-Za-z0-9_]+)$ users/index.php [NC,L]
#RewriteRule ^([A-Za-z0-9_]+)$ users/$1 [NC,L]

#RewriteRule ^ - [L]
#RewriteCond %{DOCUMENT_ROOT}/users/$1 -f
#RewriteRule .* users/$1 [L]
#Options -Indexes
#RewriteEngine On
#RewriteRule ^[!/.]*([A-Za-z0-9]+)/?$ /index.php?id=$1 [NC,L]

#<FilesMatch "\.(?i:vcf)$">
#  ForceType application/octet-stream
#  Header set Content-Disposition attachment
#</FilesMatch>

# If requested resource exists as a file or directory, skip next two rules
RewriteCond %{DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule (.*) - [S=2]
#
# Requested resource does not exist, do rewrite if it exists in /users
RewriteCond %{DOCUMENT_ROOT}/users/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/users/$1 -d
RewriteRule (.*) users/$1 [L]
#
# Else rewrite requests for non-existent resources to /index.php
RewriteRule (.*) users/index.php?q=$1 [L]

So what happens it, when I try to open the project in url at localhost
    http://localhost/projectfolder

it opens the index file without any javascript and css. Also the links to other pages do not open and the error message shows as -"Object not found". So I can only view index.php with out css and js files.
But when I remove / rename the .htaccess file, all works fine. So there must be something in this file which blocks all css, js files. So I am not asking for all the rules of writing a .htaccess file, I just need to know which line of code is blocking  the files and how can I edit them, so it will not block any file wile working in localhost.
Note:- This question I am asking only for my knowledge. As I have written, if I remove the file then its working fine. But still I want to know which line of code is blocking the access to files. Thanks.
Answer: I suspect this rule is not doing what you think it should be doing:
RewriteCond %{DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule (.*) - [S=2]

Replace this with:
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

Also you might be using relative links for css/js/images which will also cause 404 after rewriting to /users/. You have 2 options to fix that:

use absolute path in your css, js, images files rather than a relative one. Which means you have to make sure path of these files start either with http:// or a slash /.
You can try adding this in your page's HTML header:
<base href="/" />

Comment: yes, when I replaced that its working. the problem is in those 3 lines. thnks for finding it..

.htaccess file blocks css, js but how?


Adding missing rests to 9/8 meter

Question: I am trying to figure out the missing rests in a couple of bars with the time signature 9/8.

I think for the first bar there will be a dotted quarter rest. I am not too sure about the next one. Any hints or directions appreciated.
Answer: The time signature 9/8 is used for a compound triple metre, i.e., three dotted quarter note beats (of three eighth notes each).

For the first measure in your question, the first and last beats are filled with eighth notes and only the middle beat is missing. This should be filled by a single dotted quarter rest — as you said.

For the second measure, the middle beat is filled by the dotted quarter note, but both the first and last beats are incomplete.
The first beat has two eighths notes missing.  This should be filled in as two separate eighth rests.  A single quarter rest symbol is not appropriate here because this rest is not at the start of a beat.
The third beat also has two eights missing, but because these rests are at the start of the third beat they should be combined and written as a single quarter rest.

As stated in Elaine Gould's Behind Bars, p. 163:

[R]ests at the beginning of a beat may be combined.

Rests that follow a beat should expose all three divisions[.]
Answer: In 9/8 time, it is customary to notate it as three groups of three beats each. Thus, you are correct that the first measure would be completed by a dotted quarter rest.
Keeping this convention in mind, and observing that the second measure's "middle" three beats are accounted for by the dotted quarter-note, should allow for the question to be answered.
Comment: I thought I've read that a quarter rest shouldn't be used at the end of a compound meter grouping of 3 eighth notes - two eighth rests should be used instead. (Similarly, in 3/4 time, two quarter rests should be used at the end of a measure instead of a half rest.)
Comment: @Swaraj Looking through your questions on this site, it appears you're working your way through a music theory textbook? Is that the case? If yes, then the book should already have addressed the question of 3/4 time and also given you the information needed for 3/8 time. I suggest re-reading the earlier parts of the book. If you're not working from a textbook, then I recommend finding either a textbook, a YouTube video series, a tutorial website, or other resource to walk you through some of the basics.
Comment: @Dekkadeci:  [Elaine Gould agrees with you](https://imgur.com/a/NNrxAOR) (screenshot from p. 163 of *Behind Bars*). Basically, if you have an eighth note on the third sub-beat, you can precede it by either a quarter rest or two eighth rests ("if it is important that the player sense all three divisions".)  But if you have an eighth note on the first sub-beat, it should be followed by two eight rests.
Comment: And just in case the above wasn't enough: the first eighth note should be followed by a quarter rest, and the final eighth note should be preceded by a quarter rest. The measure should be eighth note, quarter rest, dotted quarter note, quarter rest, eighth note.
Comment: @Dekkadeci - can't see how - they're only specified silences, like specified notes, and a quarter note/rest = two eighth notes/rests. A question is born?
Answer: 9/8 is equivalent of 9 eighth notes per bar. BUT because the top number is a multiple of 3, those eighth notes are set out in groups of 3 (or equivalents of 3 quavers). As in, the bar could be divided into 3 equal parts.
It's the same with other compound time signatures - 6/8 divides into 2x3, 12/8 into 4x3.
So, now, it's pretty simple sums!

Adding missing rests to 9/8 meter


Can I daisy chain two mixers together to create more input channels (a sub mixer)?

Question: Last week in a live show I had some guest singers join me on stage for additional harmony and I had maxed out my mic channels and could not add another microphone.  I love my powered mixer and don't really want to replace it and most of the time it provides all the channels I need.  But occasionally, I might run out of channels.  I have a Y connector XLR cable that will allow me to plug two microphones into a single input, but then the volume and EQ cannot be adjusted independently.
I have a Mackie 808S powered mixer Mackie 808S  running passive speakers with a non powered monitor output to which I connect a series of powered monitors as floor wedges.  It has 8 channels with an XLR input and a line input on each channel.  Two of the channels (7 and 8) have a left/right stereo input for keyboards or other stereo line level inputs.
I am wondering if I can use a non powered mixer such as the Behringer Xenyx
Small Format Mixer (or any similar mixer) as a sub-mixer by connecting it to my powered mixer.  I am just using this mixer as an example and not asking for opinions on the quality of that particular mixer.
My theory is that I could use 1/4 inch cables to connect the stereo main outputs from the non-powered mixer (or the control room out) into one of the two stereo inputs on my powered mixer.  Then I am thinking I can plug additional microphones, guitars, pianos, electronic drums, etc. into the non powered mixer, and send the mixed signal from that mixer into channel 7 or 8 of my powered mixer which would then send the signal to the passive speakers.
In an ideal world, I would be able to apply effects from the non-powered mixer to the devices and instruments plugged into it, and turn the effects to zero on the powered mixer and thereby use a different effects set on the instruments and/or microphones plugged into the non powered mixer.
Is this feasible?  Are there potential pitfalls?  Will it cause any problems?  And if it is feasible, should I use an instrument cable or speaker cable to connect the two mixers together?
EDIT: Could I send the main signal out through the "tape out" RCA jacks of the sub mixer into the tape input (RCA) of the powered mixer and send the monitor output from the sub mixer into channel 7 or 8 on the main mixer to preserve the ability to control the monitor feed from the sub mixer?
Comment: "Could I send the main signal out through the "tape out" RCA jacks of the sub mixer into the tape input (RCA) of the powered mixer and send the monitor output from the sub mixer into channel 7 or 8 on the main mixer to preserve the ability to control the monitor feed from the sub mixer?"
Yes, no problem. You could also do the same thing with the effects send and another channel.
Comment: @biggvsdiccvs thanks - that may solve the problem of not having individual monitor level adjustments.  The more I think about the possibilities, the more I see advantages to a sub mixer for keyboards, another for drums, another for vocals, and another for guitars.  Then I can EQ each of those using the sub mixer graphic equalizer and have more control than just high mid and low on each channel.
Comment: Definitely. That is what it's designed for. That's why it has outputs labeled "control room out".
Answer: You can definitely do something like that. One potential problem is not having independent monitor level controls for every channel in the additional mixer (let's call it mixer 2). If that matters to you, you can run monitor outputs through a simple two-channel passive mixer (mixer 3), for example.
You can use separate effects. Using the same effect and having separate controls can also be done with a simple passive mixer.
Definitely do not use speaker wire. I would actually suggest using the tape input of your main Mackie powered mixer and connecting it to the tape output of the additional mixer, if it has one, or to its main output through RCA/TRS adapters, in which case you would need to keep in mind the difference in levels (the normal level for tape input will be about -12dB at the output of mixer 2, again, only if you connect line out to tape in of mixer 1).
Using the tape input frees up one of the input channels, which would otherwise be used by the daisy-chained mixer 2, and partially solves the monitor control problem.
Comment: Definitely use tape inputs
Answer: Entirely feasible. In my studio, there's a small mixer for all the keyboards, which is fed in stereo to two channels of the main mixer. Or could go to a single stereo channel. That way, I save 8 channels and substitute them for one, or two, on the main. There are many smallish mixers, stereo, which have monitor mix facilities as well as eq. Often there are phonos too, for a CD, etc. And if one is desperate, there's usually a 'phones socket which could even take another signal out to another mixer. It just goes on and on...
Cabling needs to be co-ax, balanced preferably, as the leads are carrying signals, not voltage going straight to speakers.
In a big band, having a separate little mixer for the horns, another for vox, and yet another for rhythm section was a cheap and cheerful way to have separate mixes, easily adjustable, with different monitor mixes available, without having a huge mixer for everything. Hard-wired, they did a sterling job.
Answer: Here's what I have done with more than two mixers and I suggest trying this. Assuming your mixers (like most of them) both have Tape In and Tape Out RCA inputs, just run RCA from Tape Out of one mixers into Tape In of the other.
The Tape In should have its own fader/control pot. This will let you keep all of the channels in each mixer free. You should be able to daisy chain many mixers together this way if you need to.
Just remember, the "Master Volume" for the 2nd (or 3rd or 4th, etc) mixer is the Tape In Fader/control pot of the mixer it is being fed to.
Answer: Connecting two or more outputs of mixers can work but sometimes their outputs are not at the same level... You need to connect a separate piece of equipment, that has a analog or digital meters on them, to each mixer output one at a time and see which mixer has the lowest output - using a standard 1000 hertz tone for each mixer... And using a stereo variable resistor at the output of each mixer, attenuate the loudest mixer the most and set them all to have the same level output or your mixing levels could start to become confusing - i.e. - a singer on a mic on mixer 1 might sound louder or lower than the same type singer on another mic from a different mixer even after setting each mic level the same... good luck... BOB
Comment: That's over-thinking it.  Just know whether you're dealing with mic or line levels.  Or, if it's speaker level, from a power amp, don't connect it to ANYTHING except a DI box specifically designed to take speaker level.
Answer: Connect the main output of your sub-mix to Mix-Insert or 2-track inputs of main mix, not to stereo channel inputs! Use separate stage monitor or instruments amp for sub-mix instruments. This is the best wiring, all other is a compromise.


problema superfatorial recursivo

Question: Estou com uma duvida na realização desta função recursiva de matematica.
Calculo do superfatorial:
O superfatorial de um número N é definida pelo produto dos N primeiros fatoriais
de N. Assim, o superfatorial de 4 é
sf(4) = 1! * 2! * 3! * 4! = 288
Faça uma função recursiva que receba um número inteiro positivo N e retorne o superfatorial desse número.
Meu código:
int super (int n, int m) {
   if (m == 1) return 1;
   if (n == 1) return super (m - 1, m - 1);
   return n * super(n - 1, m);
}

Ao chamar a função, super (n, n), o valor do superfatorial de n é devolvido corretamente.
Observe que utilizei dois parametros, n e m.
O parametro m de auxiliar para realização da função. Esta é a minha dúvida, pois na questão ele pede apenas um parametro (n). Eu não consegui pensar em uma maneira de faze-la com um paramentro super(n). É possivel?
Agradeço desde ja.
Comment: Duas tags de duas linguagens diferentes, o problema pode ser resolvido em qualquer uma das duas?
Comment: chama-lhe `superaux`e cria outra função `int super(int n){ return superaux(n,n);}`
Comment: Você tem que fazer tudo em uma única função ou podem ser duas? Por exemplo, um fatorial e a superfatorial?
Comment: A ideia do exercio  é essa.
Answer: Olá, eu resolveria criando uma função adicional, sem mudar nada desta que você postou.
É basicamente o que você mesmo falou, só que não fazer isso no main, lá seria chamada a superfat, que tem só um parâmetro.
int super (int n, int m) {
   if (m == 1){
        return 1;
   }
   if (n == 1){
        return super (m - 1, m - 1);
   }
   return n * super(n - 1, m);
}

int superfat (int n){
    return super(n, n);
}

int main(){

    printf("%d", superfat(4)); //288

    return(0);
}

Answer: Uma alternativa é usar uma função fatorial(n), e assim a função super(n) fica recursiva sem precisar de uma auxiliar:
#include <stdio.h>

int fact(n) {
    if(n == 0) {
        return 1;
    }

    //return n*fact(n-1); /* descomentar aqui se preferir definição recursiva (pior performance) /*

    int result = 1;
    while (n > 0) {
        result = n*result;
        n--;
    }
    return result;
}

int super(n) {
    if(n == 0) {
        return 1;
    }
    return fact(n)*super(n-1);
}

int main() {
    printf("Result fact(%d): %d\n", 4, super(4));
    return 0;
}

Vale lembrar que esta implementação não é ótima, visto que a cada recursão de super() diversos fatoriais que já foram calculados antes são novamente calculados. (Para um problema real que envolva fatorial eu imagino que o mais eficiente seja ter um conjunto de valores tabelados mesmo).
Mas para sua pergunta essa resposta é suficiente.
Answer: Praticamente o que o user2856432 falou só que de maneira mais compacta:
int fat(int val){
       if(!val) return 1;
       else return val * fat(val-1);
}

int sfat(int val){
       if(!val) return 1;
       else return fat(val) * sfat(val-1);
}

Answer: Isso pode não ter tanta relevância nesse caso (pois o valor do fatorial - e consequentemente do superfatorial - cresce tão rápido que é inviável calculá-lo para números grandes), mas o modo como você e os demais respondentes estão calculando possui uma ineficiência, que é calcular de novo e de novo componentes usados em diversas partes do cálculo (como já apontado por user2856432). Ao calcular 4! por exemplo você já calcula 3!, melhor usar esse resultado depois que calcular 3! novamente no próximo termo. A complexidade no caso é quadrática com o valor do argumento.
Vou mostrar uma alternativa aqui, nem tanto pelo problema em si (que como já falei, é inviável fazer para números grandes) mas para demonstrar uma técnica muito útil quando se trabalha com recursão - o acumulador:
int sfat(n) {
    return sfat2(1, n, 1); // Vai de 1 a n, e o valor acumulado é 1
}

int sfat2(inicio, fim, acumulador) {
    if ( inicio > fim )
        return acumulador;
    return acumulador * sfat2(inicio+1, fim, inicio*acumulador);
}

Explicando, caso não tenha ficado claro o que o código está fazendo:

A chamada inicial passa 0! = 1 como acumulador, e o intervalo vai de 1 a n;
A primeira chamada - termo 1 - multiplica esse (n-1)! = (1-1)! = 0! pelo resultado da chamada recursiva, que por sua vez recebe como acumulador n*(n-1)! = 1*(1-1)! = 1*0! = 1!;

O resultado é 0! * sfat(1)

A segunda chamada - termo 2 - multiplica esse (n-1)! = (2-1)! = 1! pelo resultado da chamada recursiva, que por sua vez recebe como acumulador n*(n-1)! = 2*(2-1)! = 2*1! = 2!;

O resultado é 0! * 1! * sfat(2)

A terceira chamada - termo 3 - multiplica esse (n-1)! = (3-1)! = 2! pelo resultado da chamada recursiva, que por sua vez recebe como acumulador n*(n-1)! = 3*(3-1)! = 3*2! = 3!;

O resultado é 0! * 1! * 2! * sfat(2)

...
A enésima chamada - termo n - multiplica esse (n-1)! pelo resultado da chamada recursiva, que por sua vez recebe como acumulador n*(n-1)!;

O resultado é 0! * 1! * 2! * ... * (n-1)! * sfat(n+1)

A chamada seguinte - termo n+1 - encontra a condição de parada, retornando o acumulador ((n+1) - 1)! = n!;

O resultado é 0! * 1! * 2! * ... * (n-1)! * n!

Como você pode ver, o número de chamadas recursivas agora é linear com o valor do argumento.
Nota: se você quisesse implementar a recursão de cauda - em que a chamada recursiva é a última operação executada (útil em linguagens cujo compilador otimiza esse tipo de chamada, transformando-a em iterativa) - você poderia fazer isso através de dois acumuladores: um para o fatorial, e outro pro resultado:
int sfat(n) {
    return sfat2(1, n, 1, 1); // Acumula (n-1)! e o resultado
}

int sfat2(inicio, fim, fat_acc, sfat_acc) {
    if ( inicio > fim )
        return sfat_acc;
    return sfat2(inicio+1, fim, inicio*fat_acc, inicio*fat_acc*sfat_acc);
}

Exemplos no ideone.

problema superfatorial recursivo


LIBSVM RBF kernel time complexity

Question: Is it known what is the LIBSVM time complexity when using RBF kernel functions?
Answer: The training complexity for nonlinear kernels is roughly between $O(n^2)$ and $O(n^3)$ where n is the number of training data points.
If you are using scikit-learn's implementation of LIBSVM the documentation claims (http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html):

The fit time complexity is more than quadratic with the number of samples which makes it hard to scale to dataset with more than a couple of 10000 samples.

A reference you can use is: http://colt2009.cs.mcgill.ca/papers/021.pdf
Also, the LIBSVM reference which explains the computational complexity can be found in section 4.3 of: http://fbim.fh-regensburg.de/~saj39122/Diplomarbeiten/Miklos/SVM%20Toolboxes/libsvm.pdf

LIBSVM RBF kernel time complexity


Proof of the bound for Laplace distribution

Question: I tried to search online but I couldn't seem to be find a proof for the bound of Laplace distribution. There are 2 bounds for Laplace distribution that is used in my textbook for the derivation of some other statistical result.
The two bound are if $Y \sim Lap(b) $, then $Pr[|Y| \geq tb] = exp(-t)$ and (union bound) $\Pr[max_{i\in[1,..,k]} |Y_i| \geq tb] \leq k \exp(-t)$.
Can someone show me the derivation for the bounds?
Comment: What book are you using? I believe the second bound should be $k\exp(-t)$.
Answer: If $Y\sim\operatorname{Lap}(b)$, then $Y$ has density $$f_Y(t) = \frac1{2b} \exp\left(-\frac{|y|}b\right),\ y\in\mathbb R.$$
It follows that
\begin{align}
\mathbb P(|Y|\geqslant tb) &= \mathbb P(Y\geqslant tb) + \mathbb P(Y\leqslant -tb)\\
&= 2\mathbb P(Y\geqslant tb)\quad \\
&= 2\int_{tb}^\infty \frac1{2b} \exp\left(-\frac{|y|}b\right)\,\mathsf dy\\
&= \int_t^\infty \exp(-|y|)\,\mathsf dy\\
&= e^{-t}.
\end{align}
If $Y_i\stackrel{\small\mathrm{i.i.d.}}{\large\sim} \operatorname{Lap}(b)$,  $i=1,\ldots, k$ then
\begin{align}
\mathbb P\left(\max_{1\leqslant i\leqslant k} |Y_i| \geqslant tb \right) &= \mathbb P \left(\bigcup_{i=1}^k \{|Y_i| \geqslant tb\} \right)\\
&\leqslant \sum_{i=1}^k \mathbb P(|Y_i|\geqslant tb)\\
&= ke^{-t}.
\end{align}


Basic Question Concerning Elementary Functions

Question: I have a homework problem which says

If $f(x) = \dfrac{x^2 - x}{x - 1}$ and $g(x) = x$. Is it true that $f = g$?

What do they mean by saying is it true that $f = g$? Aren't these two functions completely different from each other? Let's say it's true,then what reasoning should I give?
I'm not sure how to even get started. Please help.
Comment: for $f$ you can factor out one factor $x$ in the numerator.
Comment: Please also read [this Wiki article](http://en.wikipedia.org/wiki/Removable_singularity)
Answer: Hint: can $f$ be simplified? (yes)
You can compare the simplified version of $f(x)$ with $g(x)$, and you'll see they are they same; $f$ and $g$  have equal values at any point $x$ where they are both defined.
Does this mean $f$ and $g$ are equal as functions?
Look at the original definition of $f$ and ask yourself: "do $f$ and $g$ have the  same domains"?
Actually, all you have to do is ask yourself that last question.

They are attempting to trick you here:
You might make the observation that
$$
f(x)={x^2-x\over x-1}={x(x-1)\over x-1};
$$
and then be tempted to cancel the $x-1$ terms.
If you did, you might    say: "$f(x)=x$" and then conclude that $f$ and $g$ are equal as functions.
This conclusion would be incorrect, because you can only do that cancellation above if $x-1$ is non-zero; that is, if $x\ne1$.
In fact, $x=1$ is not  in the domain of $f$. (It is true that $f(x)=x$ when $x$ is in the domain of $f$, but just writing the rule $f(x)=x$ does not define the same function as what you started with. )
Two functions are equal if the have the same domain, range, and the same rule.
So, since $x=1$ is not in the domain of $f$ but is in the domain of $g$, the functions $f$ and $g$ are different.
Comment: Ok i get it.Thank you
Comment: Having sat in high-school math classes for several years now, I'd say that an endemic teaching error there is to emphasize far too little the importance of the domain of a function.
Answer: The answer depends crucially on the denotation of the terms elementary function and function.
Other answers have already explained what happens when said rational functions are viewed as (set-theoretic) functions. Here I discuss a more formal algebraic viewpoint, which is useful to keep in mind even when approaching analytic problems (e.g. below).
In algebra (and differential algebra), to obtain maximal generality (universality)  such polynomial and rational "functions" are interpreted formally. In this case polynomials are not functions but instead are formal expressions (elements of certain free algebras). In turn, rational "functions" are also formal (not functional) objects, namely elements of the fraction field of formal polynomials. Thus, in $\rm\:\mathbb Q(x)\:,\:$ the fraction field of the polynomial ring $\rm\:\mathbb Q[x]\:,\:$ it is true that $\rm\ x\ =\ (x^2-x)/(x-1)\ $ since one can always cancel nonzero elements from fractions. More explicitly, if $\rm\ x,\:f\in F\: $ a field (or domain) then $\rm\: x\ne 1\ $ and $\rm\ (x-1)\ f\ =\ x^2-x\ \ \Rightarrow\ \ f\: =\: x\ $ by cancelling $\rm\ x-1\ne 0\:.\:$
It's remarkable that such formal algebra frequently enables slick proofs of results that would be cumbersome analytically. In particular,  "generic" or "universal"  proofs can yield quite nontrivial results, e.g. one can "generically" algebraically cancel "apparent singularities" in one fell swoop, before evaluation - thus avoiding alternative  topological arguments (e.g. by density). For example, see this slick proof of Sylvester's determinant identity $\rm\ det\ (I+AB)=det\ (I+BA)\ $ that proceeds by universally cancelling $\rm\ det\ A\ $ from the $\rm\ det\ $ of $\rm\ \  (1+A\ B)\ A\ =\ A\ (1+B\ A)\:,\:$ thus trivially eliminating the "apparent singularity" at $\rm\ det\ A\: =\: 0\:.\:$ For further discussion see here.
NOTE $\ $ It is worth emphasizing that this equality, like many equalities, is a simple consequence of a uniqueness theorem, thus yielding yet another example of the power of uniqueness theorems for proving equalities. For the ring-theoretic property of being a domain is equivalent to the uniqueness of solutions to linear equations $\rm\ a\ x = b,\ a\ne 0\:.\: $ Your equality is a consequence of this simple uniqueness theorem, viz. both $\rm\:x\:$ and $\rm\:(x^2-1)/(x-1)\:$ are solutions $\rm\:f\:$ of $\rm\ (x-1)\ f\ =\ x^2-x\:,\:$ and $\rm\: x\ne 1\:,\:$ hence  they are equal by uniqueness. Normally one deduces this using an equivalent property, namely that a ring is a domain iff all nonzero elements are cancellable. Thus in a domain one may deduce such equalities by cancelling nonzero factors from both sides of an equation. But it is essential to stress the uniqueness viewpoint since this applies in much more general contexts which may not enjoy an equivalent reformulation via cancellation, e.g. see above linked posts.
While such remarks may seem rather trivial if interpreted only in a specific ring, e.g. the ring of real rational functions (formal or functional), they are quite nontrivial when interpreted more generally, as illustrated quite forcefully in the above example employing formal vs. functional matrices and determinants - by working over a ring where the matrix entries are indeterminates. The abstraction from polynomial functions to formal polynomials, while it may seem rather impotent at first glance, yields great power when exploited to the hilt by universal reasoning. Alas, such universal viewpoints don't always receive the emphasis that they rightfully deserve in first algebra courses (if they did, my trivial remark here would not be one of my highest-voted posts!)
Comment: I won't downvote this answer, but I do want to disagree strongly. From the viewpoint of the OP, the important things are the cancellability of the factor $x−1$ and the fact that the two functions don't have the same domain. Ignoring the domain leads to such errors as saying that the function 1/x is discontinuous. It's not, because *on its domain*, it's continuous everywhere. It's not continuous on the real line because it's not *defined* on the real line. But the function is not discontinuous.
Comment: @lubin My answer, as is frequently the case, strives to teach not only the OP, but other readers too. It is meant to complement the prior more focused answers. It is especially important to emphasize the algebraic (vs. analytic) viewpoint since there is often much misunderstanding on such matters at the level of many students here.
Answer: Since the functions have different domains they are not the same. The domain of $f$ is $[x\in R:x\neq1]$  where as the domain for $g$ is $[x\in R]$


When should surf works and pcolor sholudn't?

Question: I have a big complex array v. When I run surf(abs(v)) I get a perfectly normal surface figure, even with colored height. Alas, when I try to run pcolor(abs(v)) I get a black figure. When I slice v to be smaller, but as I enlarge the slice more and more the pcolor map grows darker, until it gets entirely black.
Should you find it necessary I can copy the code that creates v, I just didn't want to overload the massage.
Thanks
Amir
Comment: It's hard to tell what the problem is without data to plot or an image showing the problem, but I'll have a go anyway.
Answer: You're probably just seeing the edges around the color pixels.
As this answer points out, the easy solution is to remove the edges. This is relatively easy:
h = pcolor(X,Y,C);
set(h, 'EdgeColor', 'none')

Comment: is it the same as `shading flat;`?
Answer: Since pcolor gives You a 'checkboard' style of plot the lines separating neighboring elements can get too dense for high resolutions and shade the original picture. I'd suggest using imagesc instead:
% working example %
x = -1:0.0075:1;
[X Y] = meshgrid(x,x);
g = exp(-X.^2 - Y.^2);

close all
% can't see a thing with pcolor '
figure
pcolor(g)

% clear and pretty
figure
imagesc(g)

if for some reason You wan't the griddy feel of it, check out grid on command on the imagesc picture.


Checking if Ticker is in another list, then adding a new key [RamdaJS]

Question: I'm trying to use Ramda to compare 2 lists, find which tickers in the tickersList are also in the portfolioTickers. If one is in the portfolio list as well then add a key portfolio:true.
Example data:
tickers = [
    { ticker: aa },
    { ticker: bb },
    { ticker: cc }
]

portfolio = [
    { ticker: aa }
]

Expected result:
tickers = [
    { ticker: aa, portfolio: true },
    { ticker: bb },
    { ticker: cc }
]

Sounds simple, but stuck here so far:
const checkTicker = _.curry((ticker, portTicker) => {
    if (ticker.ticker === portTicker.ticker) {
        ticker.portfolio = true;
    }
    return ticker;
});

const matched = R.anyPass([checkTicker]);

const setPortfolioFlag = _.curry((portfolioTickers, ticker) => {
    // const matched = R.filter(checkTicker(ticker), portfolioTickers);
    // console.log('matched', matched)
    const each = matched(R.forEach(checkTicker(ticker), portfolioTickers));
    console.log('each', each)

    return each;
});

const inPortfolioCheck = (tickersList) => {
    const portfolioTickers = R.filter(TickersFactory.isTickerInPortfolio, tickersList);
    const tickers = R.map(setPortfolioFlag(portfolioTickers), tickersList);
    console.log('tickers', tickers)
};

const displayTickers = (tickers) => {
    this.tickersList = tickers;
    const checkedTickers = inPortfolioCheck(this.tickersList);
    console.log('checkedTickers', checkedTickers)
};

Right now each is always true, and the list that all this logic returns is just a list the same length as my tickerList, but just true'.
A problem I keep running into is I feel that I need to run another 2nd R.map to do the check, however the result of that returned map is the Portfolio tickers, and not the original list.

Working code, but with an ugly for loop:
This obviously works because I'm using a for loop, but I'm trying to remove all object oriented code and replace with functional code.
const setPortfolioFlag = _.curry((portfolioTickers, ticker) => {
    for (var i=0; i<portfolioTickers.length; i++) {
        if (portfolioTickers[i].ticker === ticker.ticker) {
            ticker.portfolio = true;
        }
    }

    return ticker;
});

const inPortfolioCheck = (tickersList) => {
    const portfolioTickers = R.filter(TickersFactory.isTickerInPortfolio, tickersList);
    return R.map(setPortfolioFlag(portfolioTickers), tickersList);
};

const displayTickers = (tickers) => {
    this.tickersList = inPortfolioCheck(tickers);
    console.log('this.tickersList', this.tickersList)
};

LoDash version of the forLoop:
_.each(portfolio, (port) => {
    if (port.ticker === ticker.ticker) {
        ticker.portfolio = true;
    }
});

Answer: So the first thing you might notice is that the expected resulting tickers array is the same "shape" as the input tickers array, suggesting that we should be able to make use of R.map for the expression. Knowing that, we can then focus on what just has to happen to the individual elements of the array.
So for each ticker object, when found in the portfolio array, we would like to attach the portfolio: true property.
const updateTicker =
  R.when(R.flip(R.contains)(portfolio), R.assoc('portfolio', true))

updateTicker({ ticker: 'aa' })
//=> {"portfolio": true, "ticker": "aa"}

updateTicker({ ticker: 'bb' })
//=> {"ticker": "bb"}

Then we can just map over the tickers list to update each ticker.
R.map(updateTicker, tickers)
//=> [{"portfolio": true, "ticker": "aa"}, {"ticker": "bb"}, {"ticker": "cc"}]

Comment: Thanks! Trying this out now, could you explain what's going on in `R.when(R.flip(R.contains)(portfolio), R.assoc('portfolio', true))` Looking up `when`, `flip` and `contains` now.
Comment: This might be slightly more difficult if `portfolio` and `tickers` are oversimplified for demonstration purposes, and don't actually have the same shape.  I was going to try an answer with `any` and `eqProp` in place of `contains` for that case.  But if this one does what you need, I won't bother.
Comment: Well `portfolio` will most of the time always have less or none then `tickers` however this code pertains to a search function. So technically it's possible for a user to search for a list of tickers that are all in his portfolio, like if he added all the top ticker that started with `AA`.
Comment: [`contains`](http://ramdajs.com/docs/#contains) is simple: `contains(needle, haystack)` returns true if `needle` is in `haystack`.  [`flip`](http://ramdajs.com/docs/#flip) reverses parameters of the target function, so `flip(contains)(haystack, needle)` is similar, used above in a curried form as `flip(contains)(haystack)`.  This could also be written `contains(__, haystack)`, depending on your preference.  [`when`](http://ramdajs.com/docs/#when) returns an altered version of the original parameter if the predicate is true, or the parameter itself if it's false.
Comment: The question was about *shape*.  Will the entries of `portfolio` and `tickers` always have only the single `ticker` property, or might they be more complex?
Comment: BOOM! thanks this is what I needed to know `flip(contains)(haystack, needle)` And no these ticker objects have wayyy more stuff in them, but it's the same keys (price, company name etc).
Answer: The answer from @scott-christopher is, as always, excellent.  But subsequent comments make me think that it doesn't quite cover your use case.  If the data is more complex, and it's possible that items in the portfolio and the tickers might have distinct properties, then contains won't be strong enough.  So if your data looks more like this:
const tickers = [
    { ticker: 'aa', size: 1 },
    { ticker: 'bb', size: 2 },
    { ticker: 'cc', size: 3 },
    { ticker: 'dd', size: 4 }
]

const portfolio = [
    { ticker: 'aa', id: 'abc' },
    { ticker: 'dd', id: 'xyz' }
]

Then this version might work better:
const updateTicker =
  when(pipe(eqProps('ticker'), any(__, portfolio)), assoc('portfolio', true))

This nearly points-free version might be a little obscure.  It's equivalent to this one:
const updateTicker =
    when(
        (ticker) => any(eqProps('ticker', ticker), portfolio),
        assoc('portfolio', true)
    )

Also, if the any(__, portfolio) notation is unclear, it's equivalent to flip(any)(portfolio).
You can see this on the Ramda REPL.
Comment: Your original worked even with ticker objects that have over a dozen keys. Trying to wrap my head around this: `R.when(R.pipe(R.eqProps('ticker'), R.any(R.__, favorites))` Don't get what the `pipe` or `__` does, even after reading the docs a couple times lol. What I get is if the `prop` ticker of ticker matches `any` in favorites, then `assoc` the new key `favorites` with the value of true and return the ticker.
Comment: The two versions should work exactly the same.  The second is an expansion of the first.  `pipe` simply hooks several functions together in a pipeline, sending the result of one into the next.  `__` is just a way to partially apply the values of a function out of order.  If you supply the placeholder for the first parameter and an actual second parameter, then you get back a new function looking for that first one (and third, fourth...)


Graph theory problem about vertices

Question: If G is a connected graph with 100 vertices, and each vertex has at least degree 10, then prove that there is a path with at least 21 vertices in G
How can I solve this problem? I know it has something to do with the fact that 21 is around 10 times 2
Comment: Review the proof of Dirac's theorem you saw in class.
Comment: ok i looked at dirac, and now i'm thinking -
Comment: if i have 20 vtxs with each at least degree ten, i have a hamiltonian path,
and all i have to do is extend the path by 1, since i have 80 remaining
vertices, so now I have a path of 21 and the rest of the vertices I can
just add whatever, hence >= 21, is that a good enough proof?
Comment: If you don't convice yourself then is not.
Comment: Cool question bro! Here is what I found so far: Assuming the graph is triangle-free then it has a path of length at least 19. You consider the longest path v1v2....vl, and v1 has all its neighbours in the path. From this, we get that the path is of length at least 10. But no triangles means no consecutive neighbours of vl on the path, so need to add at least 9 no neighbours of vl on the path to give a path of length 19? DOES this help?
Comment: @Misha , the proof of Dirac's theorem in my notes uses induction on the number of absent edges of the graph for it to be complete. And the induction steps make use of machinery that divides the vertices of the Hamiltonian cycle, in the graph resulted from the old one by adding a new edge, into two groups that have a non-trivial intersection. And from that generate another Hamiltonian path. I don't see how that can be used in this problem? Please help!
Comment: That's disappointing - there is a proof of Dirac's theorem that immediately implies this one.
Answer: Here is an algorithm to construct such a path.
First, start with a single edge and greedily extend it in both directions. That is, for as long as you can add another edge to either end of the path which doesn't visit a previously used vertex, do so.
When we're done, we have a path on vertices $v_0, v_1, v_2, \dots, v_k$, visiting them in exactly this order, such that all neighbors of $v_0$ and $v_k$ are also on the path (or else we could extend it). We may assume that $k < 20$, because if $k\ge 20$, we are done.
Let $S \subseteq \{1,2,\dots,k\}$ be the set of indices $i$ such that $v_0$ is adjacent to $v_i$, and let $T \subseteq \{1,2,\dots,k\}$ be the set of indices $i$ such that $v_{i-1}$ is adjacent to $v_k$. Because the graph has minimum degree $10$, and all neighbors of $v_0$ and $v_k$ are on the path, we have $|S|\ge 10$ and $|T|\ge 10$.
But $S$ and $T$ together are contained in a set of size less than $20$. So there is no room for them to be disjoint: there must be an index $i \in S\cap T$, meaning that $v_0$ is adjacent to $v_i$ and $v_{i-1}$ is adjacent to $v_k$. This turns our path into a cycle: $v_0, v_1, \dots, v_{i-1}, v_k, v_{k-1}, \dots, v_i, v_0$.
Since the graph is connected and has more than $k+1$ vertices, at least one vertex on this cycle must have a neighbor $w$ outside $\{v_0, v_1, \dots, v_k\}$. This lets us make a longer path: start at $w$, take the edge to the cycle, and then walk all the way around the cycle.
Now go back to the first step, extending this path greedily, and repeat. This algorithm lets us keep going for as long as the path has fewer than $21$ vertices, so it stops when it finds a path on $21$ vertices or more.
This algorithm generalizes in two ways:

If the graph has minimum degree $d$, is connected, and has at least $2d+1$ vertices, then it contains a path on $2d+1$ vertices by this argument.
If the graph has minimum degree $d$ and has $n \le 2d$ vertices (in which case it's automatically connected), then the only place this algorithm can stop is when we're looking for the vertex $w$ and can't find it because there are no other vertices in the graph. In this case, we've found a Hamiltonian cycle. This is a proof of Dirac's theorem.

Graph theory problem about vertices


Port forward IPv6 to IPv4

Question: I have two servers, one is ROUTER - equiped with IPv6 IP and private IPv4 IP and the other one - WORKER has private IPv4 only. And I would like to configure NAT/port forward to access the second server through IPv6 of the first one.
So this will be possible and will connect me to WORKER server:
<code>ssh user@2a02:xxxxxxx::1 -p 30123
</code>
I have also included diagram to better explain what I need to achieve.

Note: Both servers are Ubuntu 18.04
I have tried to configure iptables and socat, but no sucess so far.
My tries:
<code># Using socat
socat TCP6-LISTEN:30001,fork TCP4:192.168.1.1:22
# Using 6tunnel
6tunnel -6 30001 192.168.1.1 22
</code>
Does anyone have any experience with this kind of forward using IPv6? If yes, how to do it so?
Answer: During debug I have discovered typo in command and after fixing it both commands work fine.
<code># Using socat
socat TCP6-LISTEN:30001,fork TCP4:192.168.1.1:22

# Using 6tunnel
6tunnel -6 30001 192.168.1.1 22
</code>
Creds

Use iptables to forward ipv6 to ipv4?

Port forward IPv6 to IPv4


Convergence of $\sqrt{\frac{\sum_{i=1}^n (\frac{1}{i} - \frac{1}{i^2})}{log(n)}}$

Question: I am having trouble with a part of a proof that says:
$\sqrt{\frac{\sum_{i=1}^n (\frac{1}{i} - \frac{1}{i^2})}{log(n)}} \rightarrow 1$
As n goes to infinity.
I am aware that the log and harmonic series are related by Euler's constant, but i'm not sure if that's relevant here.
Comment: Try using Euler-Maclaurin formula for $\int_1^n \frac{1}{x} dx$, it should help
Answer: Using Stolz theorem once to get rid of the sum we get:
$$\lim_{n\to\infty}\frac{\sum_{i=1}^n \frac{1}{i}-\frac{1}{i^2}}{\log(n)} = \lim_{n\to\infty}\frac{\frac{1}{n}-\frac{1}{n^2}}{\log(n)-\log(n-1)} = \lim_{n\to\infty}\frac{\frac{n-1}{n}-\frac{n-1}{n^2}}{\log[(1+\frac{1}{n-1})^{n-1}]} = 1$$
Comment: Can you elaborate on how you applied Stolz theorem to remove the sum?
Answer: It's standard that $\dfrac{\sum_{k=1}^{n}1/k}{\log n} \to 1.$ And we know $\sum_{k=1}^{n}1/k^2$ converges. Thus
$$\frac{\sum_{k=1}^{n}(1/k-1/k^2)}{\log n} = \frac{\sum_{k=1}^{n}1/k}{\log n} - \frac{\sum_{k=1}^{n}1/k^2 }{\log n} \to 1 + 0 =1.$$
Taking the square root leaves the limit at $1.$
Answer: If you enjoy generalized harmonic numbers,$$S_n=\sum_{i=1}^n \left(\frac{1}{i} - \frac{1}{i^2}\right)=H_n-H_n^{(2)}$$ Using the asymptotics
$$S_n=\log \left({n}\right)+\gamma-\frac{\pi ^2}{6} +\frac{3}{2
   n}+O\left(\frac{1}{n^2}\right)$$ making, using equivalents,
$$\sqrt{\frac{\sum_{i=1}^n (\frac{1}{i} - \frac{1}{i^2})}{\log(n)}} \sim\sqrt{1+\frac{\gamma-\frac{\pi ^2}{6}}{\log(n) } }\sim 1+\frac{\gamma-\frac{\pi ^2}{6}}{2\log(n) } $$
Even for rather "small" values of $n$, the approximation is not too bad. For $n=10$, the exact value is $\frac{1}{504} \sqrt{\frac{350339}{\log (10)}}\approx  0.773937$ while the approximation gives $\approx 0.768148$.


Preparatory studies for "Moonlight" 3rd movement

Question: I can successfully play the first movement and would otherwise consider myself to be at Canada's Royal Conservatory of Music level 8 to 9. (I can play Chopin's Prelude Op. 28, No. 6 with my own interpretation, and I can play Chopin's Nocturne in C sharp minor with difficulty and relying on the publisher's interpretation.) I've recently started studying the 3rd movement of "Moonlight", but I'm noticing that I'm not making much progress - although I am certainly progressing through the first page in the sense that I am playing the correct notes more often than not, I'm not noticing any significant increase in my ability to play new passages - all of the passages I encounter, unless they are similar in form to those I've already seen, I'm just brute forcing my way through.
Are there any studies around my level that might better prepare me to handle the full movement?
Answer: Most of the 3rd movement is pretty much a "study" in arpeggios and tremolos. If you are at the right level to realistically attempt it, you should be able to construct technical exercises yourself from what Beethoven wrote.
IMO the real problem here is not so much the technical difficulty of the notes as the stamina required for the relentless "Presto agitato" tempo mark, which paradoxically would be easier if it was also relentlessly loud - but that's not how Beethoven marked the dynamics!
The two Chopin pieces you mentions are not even close to the same level of technical difficulty as the Beethoven 3rd movement. If you can only play the C# minor Nocturne "with difficulty," maybe you just aren't ready for the Beethoven yet.
Comment: I can definitely accept that I'm not ready yet for sure. Are there any pieces that similarly challenge a student to gain stamina without as many technical difficulties?
Answer: I can only support the answer by alephzero! You should definitely be on a level that you do not have to search for the correct keys on the keyboard, but have a good feeling how to place your hands and fingers. Without this, you will probably have a hard time searching for the best finger position. Perhaps you should do some exercises before beginning the Moonlight (3.), for example some Czerny Etudes. They will help you improve your technical skills and stamina.
Comment: I agree. The question was really asking: which pieces are best to use as preparatory pieces?  With regards to Czerny, do you mean the finger dexterity etudes? (Op 740 I think?)
Comment: I don't remember the opus, but what you refer to sounds good!


C# Dropdown calendar for 1 year with MVC Razor

Question: New to razor and mvc, how to create a 1 year calendar in dropdown list starting from
<code>var dt = System.DateTime.Now.AddDays(7);
</code>
using two dropdowns ie. 1 for day and the other for month + year. for example
if i change the month + year ddl to "feb 2012" the day ddl must display 1 - 28 items
if change the month + year ddl to "jan 2012" the day ddl must display 1 - 31 items
Comment: Are you attempting to build a datepicker? - If so, you don't have to do this using dropdowns. you could use JQueryUI's datepicker and it will handle all this for you.

http://jqueryui.com/demos/datepicker/#default
Comment: @Kohan actually its a mobile web app, i have checked the jquery datepickers some of them do not work on opera mini
Answer: In that case this might help.
http://jquerymobile.com/demos/1.0a4.1/experiments/ui-datepicker/
I just viewed the demo on my mobile in opera mini and it worked great.

Alternatively if the drop downs are the way you want to go:
You could do it using jquery like so (Razor is not an issue here):
http://jsfiddle.net/Kohan/drrHH/
Answer: jQuery mobile has a datepicker.  Do not try and re-invent the wheel.


Redirecting .html internally on Apache

Question: I'm wanting to redirect all requests for .html pages to a perl script for processing. However, for some reason I'm also being redirected for pages with no .html like the root site / as well as directories like /images/
<code>RewriteCond %{REQUEST_URI} \.(html)$ [NC]
RewriteRule .* /page.cgi [L]
</code>
How can I make it so it will only redirect requests ending in .html
What am I missing?
Answer: Requests with no specified file default to requesting index.html in a particular directory, per a different Apache config option. Maybe try putting a blank index.php file in those directories (assuming your server also runs php?). You'd have to add index.php in httpd.conf as a recognized index file. That way, requests for a directory with no file specified would default to index.php, which does not trigger your re-write rule because it's not a .html.
Comment: Fantastic! I didn't think of that little thing, just setting DirectoryIndex do never do index.html fixed the problem. Thanks!

Redirecting .html internally on Apache


Pig not loading data into HCatalog table - HortonWorks Sandbox

Question: I am running a Pig script in the HortonWorks virtual machine with the goal of extracting certain parts of my XML dataset, and loading those parts into columns in an HCatalog table. On my local machine, I run my Pig script on the XML file and get an output file with all the extracted parts. However, for some reason when I run this same script in the HortonWorks VM the script appears to run successfully but the HCatalog table is still empty.
Here is my local script:
 REGISTER piggybank.jar

items = LOAD 'data1.xml' USING org.apache.pig.piggybank.storage.XMLLoader('row') AS  (row:chararray);

data = FOREACH items GENERATE
REGEX_EXTRACT(row, 'Id="([^"]*)"', 1) AS  id:int,
REGEX_EXTRACT(row, 'CreationDate="([^"]*)"', 1) AS  creationdate:chararray,
REGEX_EXTRACT(row, 'Score="([^"]*)"', 1) AS  score:int,
REGEX_EXTRACT(row, 'Title="([^"]*)"', 1) AS  title:chararray;

STORE data INTO '/tmp/postsETLResults' USING PigStorage();

The one I'm using in HortonWorks:
REGISTER piggybank.jar

items = LOAD 'data1.xml' USING org.apache.pig.piggybank.storage.XMLLoader('row') AS  (row:chararray);

data = FOREACH items GENERATE
REGEX_EXTRACT(row, 'Id="([^"]*)"', 1) AS  id:int,
REGEX_EXTRACT(row, 'CreationDate="([^"]*)"', 1) AS  creationdate:chararray,
REGEX_EXTRACT(row, 'Score="([^"]*)"', 1) AS  score:int,
REGEX_EXTRACT(row, 'Title="([^"]*)"', 1) AS  title:chararray;

STORE data into 'posts_table_1' USING org.apache.hcatalog.pig.HCatStorer();

validate = LOAD 'default.posts_table_1' USING org.apache.hcatalog.pig.HCatLoader();

Sample XML row (from the StackOverflow public dataset):
<row Id="149115" PostTypeId="2" ParentId="149078" CreationDate="2008-09-29T15:16:23.870" Score="1" Body="<p>I'm sure you can also have Oracle display a query plan so you can see exactly which index is used first.</p>
" OwnerDisplayName="user16324" LastActivityDate="2008-09-29T15:16:23.870" CommentCount="1" />

I created the HCatalog table manually, and all the correct fields exists and are of the correct type.
The strange thing is that if I do dump data in Pig, I get no output. If I illustrate data I see pieces of my data in the log, followed by large blank areas, followed by more data, and so on.
What am I missing here? I'd really like to take this messy XML file and get a neat table in HCatalog. Again, I get the results I'm looking for when running the local script on my machine, but when I run the second version designed for storing the output into the posts_table_1 HCatalog table, I get a success message but an empty table.
Alternatively, if I can just get the output on my local machine as a comma-delimited file, I can use that file and have HCatalog automatically load the data in the Hue interface. As of now, the output is space-delimited which is problematic in Hue because the titles of posts contain spaces.
Thanks in advance! This has me stumped.
Answer: I found the issue. I created the HCatalog table manually and had used all of the default options, including the delimiter which was set to ^A (/100). My output had columns separated by Tab spaces (\t), so when the table received the data, it found no ^A delimiter and stored an empty dataset. I recreated the table to look for \t and everything worked fine.


Dirichlet series for $\frac{\zeta(1-s)}{\zeta(s)}$

Question: Wikipedia (here) says that $\frac{\zeta(s-1)}{\zeta(s)}= \sum_{n=1}^{\infty}\frac{\varphi(n)}{n^{s}}$ where $\varphi(n)$ is the totient function. Similarly, is there a known expression involving a Dirichlet series for $\frac{\zeta(1-s)}{\zeta(s)}$?
Thanks, Gregory
Answer: $\zeta(1-s)$ is not a Dirichlet series (which by definition is $f(s)=\sum a_n n^{-s}$) since for example, it doesn't have a (finite) limit as $\Re s \to \infty$ which all Dirichlet series that converge somewhere do, so it doesn't make sense to ask about a Dirichlet series as above.
By the functional equation, we know that $$\frac{\zeta(1-s)}{\zeta(s)}=2^{1-s}\pi^{-s}\cos \frac{s\pi}{2}\Gamma(s)$$ so we know an expression for it but again the function (meromorphic with poles at $s=-2n$) is not a Dirichlet series
The symmetry of $\zeta$ is $s \to 1-s$ not $s \to -s$ so $\zeta(1-s)$ and $\zeta(s-1)$ do not have a priori any particular relationship