datatables avançadas CodeIgniter

Question: Estou quebrando cabeça com uma coisinha no CodeIgniter, preciso criar uma tabela avançada que expanda detalhes sobre cada item da tabela, como podem ver no código abaixo eu não consigo separar uma linha de detalhe para item da tabela,
att;

    <? //
    $tmpl = array(
        'table_open' => '
',
        'heading_row_start' => '
',
        'heading_row_end' => '
',
        'heading_cell_start' => '',
        'heading_cell_end' => '	',

        'row_start' => '
',
        'row_end' => '
',
        'cell_start' => '',
        'cell_end' => '	',

        'row_alt_start' => '
',
        'row_alt_end' => '
',
        'cell_alt_start' => '',
        'cell_alt_end' => '	',

        'table_close' => '
'
    );

    //        ?>

    <input type="hidden" id="idquadro" value="<? // echo @$quadro_por_id[0]->IDQUADRO; ?>">

            <? //

            $detalhes = '

                                Access Key
                                Secret Key
                                Status
                                 Created
                                 Expires

           ';

            if (isset($dados_produtos[0])) {
                foreach ($dados_produtos as $row) {
                    $cell = array('data' => $detalhes, 'class' => 'highlight', 'colspan' => 7);
                    $this->table->set_template($tmpl);
                    $this->table->set_heading('IdItem', 'Modalidade', 'Área', 'Titulo', 'Beneficiário', 'Valor Aprovado', 'Detalhes');
                    $this->table->add_row(

                        @$row->idpoaitem,
                        @$row->modalidade,
                        @$row->area,
                        @$row->titulo,
                        @$row->beneficiario,
                        @$row->valoraprovado,
                        '  <button class="btn btn-default btn-xs">
                    </button>'
                    );

                    $this->table->add_row($cell);
                }
            }
            ?>

    <? echo $this->table->generate() . '

'; ?>

Comment: Já adianto que você **não vai conseguir** fazer algo assim usando a classe nativa do `CodeIgniter` porque ela não permite alteração de atributos das linhas da tabela gerada (o que é lamentável, porque permite que se altere as `cells`).  A solução é estender ou substituir. Estender é melhor, porque você não mexe na base do `framework`.
Answer: Eu fiquei curioso, e fui pesquisar um pouco sobre sua dúvida. Achei que seu problema seria resolvido com isso aqui. Veja a aplicação (você clica na linha para expandir os detalhes):

.hiddenRow {
  padding: 0 !important;
}
<!DOCTYPE html>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet" />

  <title>Tabela Accordion</title>

          #ID
          Access Key
          Secret Key
          Status
          Created
          Expires

          0
          #Access Key0
          #Secret Key0
          #Status0
          #Created0
          #Expires0

Detalhes da line 0

          1
          #Access Key1
          #Secret Key1
          #Status1
          #Created1
          #Expires1

Detalhes da line 1

          2
          #Access Key2
          #Secret Key2
          #Status2
          #Created2
          #Expires2

Detalhes da line 2

Só que, pra fazer isso com CodeIgniter você tem que estender a classe. O problema é que o framework (em regra) não permite passagem de parâmetros para a composição da tabela. Assim, por exemplo, não seria possível determinar atributos para as linhas dela.
Como você já está usando Bootstrap, e já deve ter o CodeIgniter devidamente instalado, vamos estender a classe CI_Table pra poder modificar os atributos das
 e :

acesse https://github.com/dalehurley/codeigniter-table-rows/archive/master.zip e descompacte MY_Table.php para application/libraries da sua aplicação;
Crie um método no seu controller com esse código:
 function tabela(){
    // Carregando a biblioteca e setando os parâmetros genéricos
    $this->load->library('table');
    $this->table->set_empty(" "); //->Células vazias
    $this->table->set_heading(array('#ID','Access Key','Secret Key','Status','Created','Expires'));//->Cabeçalho
    // Dados principais
    $data = array(
        array('0','#Access Key0','#Secret Key0','#Status0','#Created0','#Expires0'),
        array('1','#Access Key1','#Secret Key1','#Status1','#Created1','#Expires1'),
        array('2','#Access Key2','#Secret Key2','#Status2','#Created2','#Expires2'),
    );
    // Loop de criação da tabela
    foreach ($data as $i => $row){
        // Insere cada item dos dados principais em uma linha
        $rows[] = [
            'data' => $row,
            'data-toggle' => 'collapse',
            'data-target' => "#line_{$i}_details",
            'class' => 'accordion-toggle'
        ];
        // Cria uma linha oculta com os detalhes de cada linha principal
        $rowData = ['
Detalhes da line '.$i.'
'];
        $rows[]=['data' => $rowData];//->Acrescentando os dados ao ARRAY
        // Este é o estilo da tabela. Só altere o que precisar alterar
        $tmpl = [
            'table_open' => '
',
            'cell_start' => '',
            'cell_alt_start' => ''
        ];
    }
    // Aplicando o estilo definido
    $this->table->set_template($tmpl);
    // Capturando a string gerada
    $data['tabela'] = $this->table->generate($rows);
    // Carregando dados na VIEW
    $this->load->view('tabela', $data);
}

A sua VIEW vai ter o seguinte:
<!DOCTYPE html>

    <title>Tabela Accordion</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous">

        <?= $tabela ?>

datatables avançadas CodeIgniter


How do I make funk rhythm guitar sound fuller and nicer?

Question: Christmas is coming and I'm the rhythm guitarist for our school production of 'The Wiz'. I'm not amazing but I consider myself quite good at guitar but I can't get funk. It just baffles me!
I am a lead guitarist, which is part of the issue. I play high level pieces, all of which chord-less and fast paced. Now that I come to do laid back, funky, chordal guitar, I am falling to pieces. The lead guitarist ironically is far better at the chords. There is something about what he does that makes them sing and song far nicer than mine. This is really hard to explain so you'll have to forgive me but my chords just sound like I've just started learning.
I know pretty much all the necessary chord shapes, my strumming and muting is up to standard, I'm using a good guitar but it still sounds bad.
I use strumming patterns like follows:

I have a stratocaster with a Marshall amp using neck-mid pickup and a slightly distorted tone. Am I doing something wrong. Help would be great. Thanks :)
Comment: Are you really supposed to play full 5-6 string "simple" b7 chords? I would have expected more "trebly" 2-4 (top) string chords with 9 and 13 chord extensions/colorings. All in quite simple, but strict and tight rhythm.
Comment: Why don't you just talk to the other guitarist and ask them what they're doing?
Comment: I have but what he tells me to do is just what I'm doing. He seems to be holding notes for longer with whole chord vibrato but that sounds horrible when I do it. His chords sound like, well, chords but mine sound quite murky, as if I was playing multiple out of tune strings. Would you advice using a pick or just fingers? He swaps between a pick a bass/chord style bosso nova like playing.
Comment: As for voicings, that may be it. The chords are mainly dominant 7 chords but I probably should play them on the top strings.
Comment: @TimH: Even if the chord symbols say dominant 7 you can add extensions at your own discretion (especially in funk or other jazz related genres). Just make sure that the extended notes don't conflict with notes of the melody, i.e. that the extended notes don't end up a semitone from a melody tone of the same scale step (e.g. don't play a natural 9 extension if the melody is on a b9, etc). Selecting extension notes that are diatonic to the key signature will likely work. :-)
Comment: Ewww, double-sharps for muted strums? Yucky!
Answer: Perhaps your issue is that you're asking for a"full" sound, when really the choppy guitar lines from James Brown style funk and Nile Rogers style disco are actually quite sparse and weedy in isolation.
The fullness comes from adding bass and drums. Brass and strings fill it out further.
Most of those parts are played with only three or four strings (the top ones). You don't even need to finger the remaining strings.
None of the notes should ring out for long. The act of muting is part of the percussive sound.
You might want to experiment with a delay pedal.
Answer: It's hard to know what you're doing wrong without witnessing what you're doing. I will say that, for what you're doing, there is a recognized master, and he plays what you play. Nile Rodgers is a Strat guy, and the style you're after is the style he created. Listen to "Get Lucky" by Daft Punk; he's all over that. Look into Chic. "I'm Coming Out" by Diana Ross. His "Hitmaker" Strat has played on $2 billion worth of music.
Backing back to dead clean might be a good place to start. Listen to the drummer, and when the drummer hits the snare, that's where you strum. Very loose right hand. I'm seeing "neck pickup only" and "compression" listed too.
Let's take that back. Listen to the drummer. It's all hanging off the drummer, and being in the groove is far more important than hitting the right note.
Good luck with that. Sounds like fun.
Answer: I think Slim has the right idea with playing the chords on fewer strings. I'd practice this by reducing it still further.
Try playing the rhythm on just the high E-string, with just the root note of the chord. Might want to use a drum machine to reduce the strain on the imagination (might want to grab the drum parts, too, if the rhythmic notation is less confusing than the snippet above).
Then do it with 2-note chords. Root on the high E- , 7 on the B-string. Or ♯9 on the E- , 7 on the B- . When you have a Bass player, you can pretty much drop all the roots and just focus on making the 7s jangle-out nice and clear. Any other chord tones you're fretting can sort of take care of themselves. But (IMO) ringing-out the 7s (and other dominant chord tones) is the funk guitar's function.

You mention that you're using a strat with the mid+neck pickups. Unless you have some kind of crazy high-gain humbucker in the bridge position, I'd try the bridge pickup or bridge+mid. This should give more treble, and more chunk to the sound.
Answer: You can try using percussive strumming on the muted strings. That always helps me in attaining fullness of tone. If that is not enough you can consider some sort of harmonizer pedal that adds one or two voices a certain interval above and below the root note.
Answer: I see this is an old question but I'd also advise experimenting with the bridge pickup.  And pace Nile Rodgers but the other classic guitar for funk rhythms is the Telecaster.


The sequence $n\sin(\sqrt{4\pi^2n^2 +x^2})$ converges on compacts:

Question: I'm not sure about the idea behind the sequence $f_n(x)=n\sin(\sqrt{4\pi^2n^2 +x^2})$ being uniformly convergent on every compact of the form $[0,a]$ for $a>0$. On $\mathbb{R}$ we can find a sequence such that $\sin$ alternates the sign, thus making it impossible for $f_n$ to have a limit.
But the compact case is a little more tricky: let $K=[0,a]$, then by Weierstrass Thm $\forall n\exists M_n\mid$ $|f_n(x)|<M_n$, thus we wish for $M_n$ to be convergent. As we are using Weierstrass Thm, we can take $x_n\in K$ and $f_n(x_n)=M_n$. But $K$ is compact in $\mathbb{R}$: $\exists x_{n_k}\mid x_{n_k}\rightarrow\bar{x}\in K$, thus $f_{n_k}(x_{n_k})=M_{n_k}\rightarrow\overline{M}\in\mathbb{R}$, making $f_n$ uniformly convergent. The proof seems to make sense but on the other hand it doesn't depend on $f_n$, so it sounds like I'm either missing something.
Comment: How do you get $f_{n_k}(x_{n_k})=M_{n_k}\rightarrow\overline{M}\in\mathbb{R}$?
Answer: HINT:
Note that we have for any fixed $x$
$$\begin{align}
\sin(\sqrt{4\pi n^2+x^2})&=\sin\left(2\pi n\sqrt{1+\left(\frac{x}{2\pi n}\right)^2}\right)\\\\
&=\sin\left(2\pi n \left(1+\frac{x^2}{8\pi n^2}+O(n^{-4})\right)\right)\\\\
&=\frac{x^2}{4\pi n}+O\left(n^{-3}\right)
\end{align}$$
whence multiplying by $n$ and letting $n\to \infty$ yields
$$\lim_{n\to \infty}n\sin(\sqrt{4\pi n^2+x^2})=\frac{x^2}{4\pi}$$
Answer: What you are missing is to actually use the functions you have.
Concretely, we have
$$
f_n(x)=n\,\sin\Big(2\pi n\,\sqrt{1+\frac{x^2}{4\pi^2n^2}}\Big).
$$
Using the binomial expansion,
$$
\sqrt{1+\frac{x^2}{4\pi^2n^2}}=1+\frac{x^2}{8\pi^2n^2}+o(n^{-4}).
$$
The sine is
$$
\sin t= t - o(t^3).
$$
Then
\begin{align}
f_n(x)&=n\,\sin\Big(2\pi n+\frac{2\pi nx^2}{8\pi^2n^2}+o(n^{-3})\Big)\\[0.3cm]
&=n\,\sin\Big(\frac{2\pi nx^2}{8\pi^2n^2}+o(n^{-3})\Big)\\[0.3cm]
&=\frac{2\pi n^2x^2}{8\pi^2n^2}-o(n^{-2})\\[0.3cm]
&=\frac{ x^2}{4\pi}-o(n^{-2})\\[0.3cm]
&\xrightarrow[n\to\infty]{}\frac{x^2}{4\pi}
\end{align}
When we consider $x$ only on some compact set, because it's bounded the convergence can be made uniform, as the estimates will not depend on $x$ (hidden, above in the terms $o(n^{-4})$, etc.)


send message to specified Red5 client

Question: When I was make a voice chat, I found a problem.
the problem is how to send message to specified RED5 client (Shared Object).
this is what I want :
Client 1
Message from client 2 : Hello!
To client 2 : How are you ?
etc....

Client2
To client 1 : Hello!
Message from client 12 :
etc....

Client3
Message from client X : How are you ?
etc....

Answer: You can use sharedObject to send a message to another clients with your own clientID and to clientID you want( something like this: sharedobject.send(fromId,toID,message)) , and other clients receive this message and decide to display it or not.
hope can help you.

send message to specified Red5 client


Jupyterlab: turn on tab completion for text editor as in Notebook?

Question: In Jupyterlab, there is a text editor that we can open .py files, is it possible to also turn on tab completion, just like how it works in Notebook ?
Answer: By now, tab completion in the text editor of jupyter lab has been implemented in this pull request (see also discussion in this issue). However, for it to be working you need to open a console for the editor (right click in the editor window and select Create Console for Editor).
Answer: No, it is currently an open issue. https://github.com/jupyterlab/jupyterlab/issues/1276
Answer: The package jupyterlab-lsp now provides tab completion in the text editor. You need can install it from pip or conda, along with a language server for Python:
pip install jupyter-lsp
pip install jedi-language-server

I also needed to enable the server side extension:
jupyter server extension enable --user --py jupyter_lsp

And enabled @krassowski/jupyterlab-lsp and @krassowski/completion-theme via JupyterLab's extension GUI (the puzzle piece on the right hand side). Then I restarted JupyterLab, and completion worked (with Tab). I am not sure if all these steps are neccessary, it might depend on your environment.


Properly set up MIDI to USB

Question: Essentially, I want to record myself playing the piano, which I've decided to do by recording the MIDI.
My hardware setup is a

Computer with Windows 10 x64
Yamaha P35
MIDI-to-USB cable

The cable has a

Male MIDI IN
Male MIDI OUT
Male USB
Interface (in lack of better words) which has three lights, one for each cable

The cable looks like this.

How to connect the MIDI cables is counter-intuitive (to me), but I've done according to the manual by connecting the MIDI OUT cable to the piano MIDI IN and visa versa.

The order of connecting the cables and turning things on is important so I've done the following according to the Yamaha manual:

Turn on computer
Connect cables
Turn on piano

At this point, the USB light is on, but the others are off even when playing the piano.
I've tried to use different kind of software

REAPER v6.08/x64 (Evaluating)
MidiEditor v. 3.3.0 (32-bit)
Ableton Live 10 Trial (10.1.9)

But none of them register anything when recording.
I tried to unplug and plug the USB cable from the computer.
Now, the MIDI IN flashes really fast to the point where it almost looks like it's constant. As far as I understand, the light is only supposed to be on when playing the piano.
The different programs tell me:

REAPER: "The following MIDI inputs could not be opened: USB20MIDI"
MidiEditor: "Input is not connected"
Ableton: Can actually record my playing but only weirdly. It doesn't always register when I press a key and never registers G1, D4, and B7. The keys that it registers are mostly sustained, but always. I believe that the MIDI IN light keeps blinking because the sustain pedal keeps sending MIDI data for some reason.

By searching on StackExchange, Google, and YouTube, it seems that people have a lot of different problems related to MIDI connections, and I can't find a problem that matches mine enough to find a solution.
I will appreciate any help that I can get.
The manual: https://uk.yamaha.com/files/download/other_assets/8/328158/p35_en_om_a0.pdf
Comment: I don't know how you tell for sure, but I bet you've got one of those cheap Chine cables that don't actually work properly :\ Check out the 1-star reviews at the bottom of this - https://www.amazon.co.uk/product-reviews/B000XRI3CC/ref=acr_dp_hist_1?ie=UTF8&filterByStar=one_star&reviewerType=all_reviews#reviews-filter-bar
Comment: Two things off the top of my head, one, does this USB interface require a driver to work and two, have you tried reversing the MIDI connections? Maybe they are mis-labeled. This is not worth spending a lot of time on, better to return it and buy one made by a well known company or maybe even step up and get an audio interface that includes MIDI connections  in case you want to record audio at some point.
Comment: @Tetsujin, ah, that's what I feared. I'll try to acquire another one. Thank you.
Comment: @JohnBelzaguy, good suggestions. I have tried the driver with no change in effect. Wrt. reversing the MIDI connection, I actually started that way and it didn't work at all. According to the other comment and the answer, the problem is the cable. I will try another one. Thank you for your suggestions.
Answer: Ah, the infamous Midi cable with the fantasy clef on it.  It's garbage, never mind that it appears to be the most-sold thing under the sun.  While you should be able to get it to work for single notes, it has problems with polyphony and will garble SysEx messages.  Try getting a cable/adapter from a reputable manufacturer.  It can be really antique: USB Midi was properly defined for USB1.1 (which also means that you won't need special drivers for anything but the most outlandish adapters) and the 12Mbps speed of USB1.1 is enough for a good adapter not to lose data.  Off the top of my head MidiSports, MAudio, Roland, Yamaha should be reliable.  Terrasoniq Midi One is great but no longer produced.
Comment: Where I live, only the `Roland UM-ONE mk2` is for sale. I will try that when the stores restock it. Thank you for your funny and very helpful answer. I will accept it when I have confirmed that another type of USB-MIDI cable will solve the problem.

Properly set up MIDI to USB


If $o(\mathrm{a})$ be finite, $\langle a\rangle\simeq \Bbb {Z}/m\Bbb{Z}$ for some positive integer $m$ using Isomorphism theorem.

Question: Let $G$ be a group. A mapping $\phi: \mathbb{Z} \rightarrow G$ is defined by
$\phi(n)=a^{n},$ where $a \in G$ and $n \in \mathbb{Z}$ show that
$\phi$ is a homomorphism. Moreover, if   $o(a)$ be finite, $\langle a\rangle\simeq \frac{\mathbb{Z}}{m\mathbb{Z}}$ for some positive integer $m$ using Isomorphism theorem.
My attempt:

First part : For $m,n\in \mathbb{Z}, \phi({m+n})=a^{m+n}=a^ma^n=\phi(m)\phi(n)\implies \phi$ is homomorphism.

How can I show the $2^{\text{nd}}$ part?
Comment: Think about the kernel of $\phi$.
Comment: @BSC As $\mathbb{Z}$ is generated by $1$ the image of $\varphi$ must be generated by $\varphi(1)=a$, in other words equal to $\langle a \rangle$. By virtue of the fundamental isomorphism theorem, you have the isomorphism $\mathbb{Z}/\mathrm{Ker}\varphi \approx \langle a \rangle$ and taking into account that any subgroup of $\mathbb{Z}$ is of the form $m\mathbb{Z}$ we gather $\langle a \rangle \approx \mathbb{Z}_m$ for a certain $m \in \mathbb{N}$. In case $a$ is of finite order, $m\mathbb{Z}$ must be of finite index in $\mathbb{Z}$ which means that $m \neq 0$ *(to be cont.)*
Comment: @BSC *(cont.)* in which case $|\langle a \rangle|=\left|\mathbb{Z}/m\mathbb{Z}\right|=(\mathbb{Z}\colon m\mathbb{Z})=m$.
Comment: I'm fairly sure this is a duplicate.
Comment: For the first part, see [here](https://math.stackexchange.com/q/2895616/104041).
Answer:
Let $G,H$ be groups and $\phi:G\rightarrow H$ be homomorphism. Then the First Isomorphism Theorem states that $$G/\ker \phi \cong \phi(G)$$

Let $m=o(a)$.
So first you had shown that $\phi$ is a homomorphism.
Next you want to show that $\phi(\Bbb{Z})=\langle a\rangle$.
Note that $\phi(\Bbb{Z})=\{a^z:z\in \Bbb{Z}\}=\langle a\rangle$ by the definition of subgroup generated by a single element.
Lastly you have to show that $\ker \phi =m\Bbb{Z}$.
Notice that $\ker \phi=\{z\in \Bbb{Z}:a^z=1\}$.
Recall a property that $a^z=1$ if and only if $m$ divides $z$.
Hence we get $\ker\phi=m\Bbb{Z}$ and the result follows.
Comment: I guess you meant $G/ker \phi\cong\phi(G)$, not $G/ker \phi\cong\phi(H)$.
Comment: @user750041 Corrected. Thanks.


Playing the Ukulele besides singing

Question: I love the ukulele, and I just bought one. The problem is I cannot sing, and I don't really want to.
It seems as though there are not a lot  fingerpicking songs and most songs just have the chords.
I also googled chord progressions but again, not a lot of documentation.
Is it possible to play the Ukulele without singing and still know a lot of songs?
Should I just suck it up and learn how to sing?
Answer: If you want to get started playing fingerstyle ukulele, there are lots of books you can pick from.  The one I used to get started and recommend is called 20 Easy Fingerstyle Studies for Ukulele by Rob MacKillop.  The book walks you through a lot of the different techniques used in fingerstyle through exercises and simple instrumental songs.  The book comes with a great CD that features both a fast and slow version of each song to help you understand what it is supposed to sound like.  The author also has YouTube videos of himself playing many of the songs from the book.
After you've mastered that book, you will be ready to take on a variety of ukulele songs in tablature format.
Answer: Although the ukelele is often used as an instrument to provide chordal accompaniment (strummed or picked) to other instruments, or commonly voice, there is absolutely no reason why you can't explore other ways to play it, which are not primarily as an accompanying instrument.
For instance, you can play single note lines, as you would on any other instrument, there is an interesting discussion about the right-hand techniques used for this on this forum page.
Of course, if you want to play recognisable pieces/songs solo on the ukelele, it will probably be more interesting if you can combine a chordal and melodic approach. The simplest way to do this, would be to learn a variety of chord shapes for each key and chord type, with different chord tones at the top. This would allow you to play the chords for a piece/song, with the melody notes at the top (of course, a little bit of extra study would be needed to find fingerings for non-chord tones in the melody above the chords).
In order to get started with learning more than just a few ukelele chord shapes, and so open up greater solo possibilities, it would be a good idea to find out about ukelele notation and technique. A good resource for this (and I just have to mention it, due to it's slightly naughty name!) is the amusingly named UkeHunt website. This has some great info about ukelele technique and notation. Also, there are a lot of TABs for pieces in a wide variety of styles on this site. Many of these illustrate the approach I outline above; they have a melodic line accompanied by some amount of harmony. Other pieces are far more complex, resembling the kind of pieces played on classical guitar, for instance. And then there are also short, relatively simple, single line riffs and melodies.
By all means learn to play chords on the ukelele, whether you choose to sing with it or not (and you may wish to accompany other instrumentalists and/or singers anyway), but there are plenty of resources available with a little bit of looking online, for learning to play single line melodies and pieces with more complex textures, too (melody and accompaniment or even contrapuntal).
Comment: Is it possible to just play the chords of a song and not sing? would it still sound recognizable?
Comment: Well, of course you can, and you can gain a lot of personal satisfaction from doing this, especially while you are first learning an instrument capable of playing chords (guitar, piano, ukelele etc.) But, without wanting to generalise, most players and listeners gain greater satisfaction from hearing and playing the melody of a piece or song, as this is far more recognisable than the chords (harmony) alone. And, then it is even more satisfying to hear chords and melody combined, even if you only play *some* of the chords (eg. one per bar).
Comment: There is great value from learning ukelele chords anyway, though. They are, after all, an important part of ukelele playing. And, arguably, learning to play chords would most easily give you the means to start playing with other musicians.
Answer: If you have the ability, you can rearrange songs yourself. There are plenty of fingerpicking style ukulele tabs out there, but their quality may not be the best.
As @MarkM suggests, Jake Shimabukuro is god-level at playing the ukulele but never sings.
I recommend listening to his songs, and if you like them, his songs and rearrangements are available as books.
Answer: Youtube is your friend when looking for this kind of inspiration:

I think it's safe to say that it possible to play the Ukulele without singing.
Comment: Jake admits that he can't sing. :)
Answer: Yes, of course you can play the ukulele without singing. You can play a lot of instruments while singing, but that doesn't mean that every time you play the instrument you should sing.
You should try it, and if you like it, you can sing and play ukulele at the same time.

Playing the Ukulele besides singing


Coefficients of a series in Maple

Question: I have been using
seq(coeff(series( f(x), x, n+1), x, n), n = 0 .. 40);

to obtain the coefficients of series expansions. It seems efficient enough until some comparisons are made with other platforms.
For example: the script
seq(coeff(series(1/mul(1-x^j, j = 1 .. 11), x, n+1), x, n), n = 0 .. 70);

takes 0.134 seconds to calculate in Maple but the same script in Mathematica
CoefficientList[Series[1/Product[1 - x^j, {j, 1, 11}], {x, 0, 70}], x]

takes 0.00739489 seconds. Pari has a similar fast calculation time.
The question becomes: Is there a faster, or more efficient, method to calculate the coefficients of a series?
Comment: You are computing the series 71 times in the seq call.  Compute the series separately first (to order 71), then extract the coefficients.
Answer: S:= series(1/mul(1-x^j,j=1..11),x,71):
seq(coeff(S,x,j),j=0..70);

took 0.031 seconds in Maple 2019 on my computer.  YMMV.
Answer: This takes approximately 0.005 sec in my Maple 2019:
PolynomialTools:-CoefficientList(convert(series(1/mul(1-x^j,j=1..11),x,71),
                                         polynom),x);

These two steps take (in total) approximately 0.002 sec in my Maple 2019:
S := series(1/mul(1-x^j,j=1..11),x,71):
seq(coeff(S,x,j),j=0..70):

The relative performance of the above two techniques may vary as the degree gets very large. If I recall correctly the CoefficientList procedure was intended for doing a single pass through the structure, and thus may scale up better than the approach of calling coeff many times.
On such a small example as yours, measuring the performance of this operation is delicate -- you have to be careful not to trick yourself.
For example, you may well wish to suppress printing of the results, because the computations are so very fast here. You don't really want a major portion of your measurements to reflect the time taken for the programs' interfaces to render/print/pretty-print these results, do you?
And, as James mentioned, you may want to avoid inadvertent duplicate re-creation of the series 70 times. Even deliberately doing such duplication in all those programs may be problematic for a comparison, as the programs may differ in how they each memoize parts of the computation.
Also, how will you ensure that none of these mentioned program are not (by chance) doing a garbage-collection (memory management act) during your requested computation. That might conceivably consume as much time as your actual computation.
And what about initialization of the commands in question? Are you deliberately timing how long the first such computation takes in a fresh session, or how long such computations take on average (after all relevant functions are loaded into memory)?
Just to illustrate how delicate such a timing measurement may be for such a small and quick computation, compare these:
restart;
CodeTools:-Usage( seq(coeff(series(1/mul(1-x^j,j=1..11),x,71),x,j),j=0..70) ):
  memory used=0.81MiB, alloc change=0 bytes, cpu time=3.00ms, real time=2.00ms, gc time=0ns

restart;
CodeTools:-Usage( PolynomialTools:-CoefficientList(convert(series(1/mul(1-x^j,j=1..11),x,71),polynom),x) ):
  memory used=0.61MiB, alloc change=0 bytes, cpu time=3.00ms, real time=2.00ms, gc time=0ns

restart;
CodeTools:-Usage( seq(coeff(series(sin(x),x,12),x,j),j=0..11), quiet ):
CodeTools:-Usage( seq(coeff(series(1/mul(1-x^j,j=1..11),x,71),x,j),j=0..70) ):
  memory used=0.81MiB, alloc change=0 bytes, cpu time=2.00ms, real time=2.00ms, gc time=0ns

restart;
CodeTools:-Usage( seq(coeff(series(sin(x),x,12),x,j),j=0..11), quiet ):
CodeTools:-Usage( PolynomialTools:-CoefficientList(convert(series(1/mul(1-x^j,j=1..11),x,71),polynom),x) ):
  memory used=0.58MiB, alloc change=0 bytes, cpu time=6.00ms, real time=6.00ms, gc time=0ns

restart;
CodeTools:-Usage( seq(coeff(series(1/mul(1-x^j,j=1..11),x,71),x,j),j=0..70),
                  iterations=100 ):
  memory used=358.69KiB, alloc change=0 bytes, cpu time=1.13ms, real time=1.13ms, gc time=136.30us

restart;
CodeTools:-Usage( PolynomialTools:-CoefficientList(convert(series(1/mul(1-x^j,j=1..11),x,71),polynom),x),
                  iterations=100 ):
  memory used=27.55KiB, alloc change=0 bytes, cpu time=140.00us, real time=140.00us, gc time=0ns

restart;
S := CodeTools:-Usage( series(1/mul(1-x^j,j=1..11),x,71) ):
  memory used=0.51MiB, alloc change=0 bytes, cpu time=1000.00us, real time=1000.00us, gc time=0ns
CodeTools:-Usage( seq(coeff(S,x,j),j=0..70) ):
  memory used=3.52KiB, alloc change=0 bytes, cpu time=0ns, real time=0ns, gc time=0ns

restart;
S := CodeTools:-Usage( series(1/mul(1-x^j,j=1..11),x,71), iterations=100 ):
  memory used=9.60KiB, alloc change=0 bytes, cpu time=30.00us, real time=30.00us, gc time=0ns
CodeTools:-Usage( seq(coeff(S,x,j),j=0..70), iterations=100 ):
  memory used=2.84KiB, alloc change=0 bytes, cpu time=50.00us, real time=50.00us, gc time=0ns

Coefficients of a series in Maple


Rails OpenID Authentication Plugin No Longer Installs Rake Tasks?

Question: I'm following the Railscasts tutorial on using OpenID with AuthLogic.
This command:
<code>$ script/plugin install git://github.com/rails/open_id_authentication.git
</code>
installs the plugin, but I don't see any OpenID Rake tasks (rake -T). In particular, I can no longer run the task:
<code>$ rake open_id_authentication:db:create
</code>
With previous applications, the Rake tasks were installed without a problem, so what's changed with the plugin? Which version of the plugin do I need to get the behavior I'm looking for?
Using Rails 2.3.5.
Answer: Looks like the task has been taken out (unnecessary?). This bug report (link now broken but less than one hour ago worked) outlines the problem, but doesn't seem to give a definite answer of what's going on.


Lines too long in piece with two sections for different instruments

Question: I'm trying to use Lilypond 2.18.2 to engrave a piece with two staff groups: a verse for piano (18 bars), and a chorus for choir (8 bars).  I'm trying to follow the Lilypond example "Solo Verse and Two-Part Refrain", which takes advantage of \RemoveEmptyStaves.  However, Lilypond doesn't seem to be inserting any line breaks within the verse, so the music runs off the edge of the page.
I have tried to reduce the following example as much as possible, but it needs to have a lot of notes to reproduce the problem, so it is still a bit long.  Sorry about that.
#(set-default-paper-size "letter")

\version "2.18.2"
\language "english"

global = {
  \key c \major
  \time 6/8
}

verseTreble = \relative c' {
  \global
  \clef treble
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  r2.*8
}

verseBass = \relative c {
  \global
  \clef bass
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  c8 e g c g e |
  r2.*8
}

chorusSoprano = \relative c' {
  \global
  \clef treble
  \autoBeamOff
  r2.*18 |
  g2. |
  r2.*6 |
  g2. |
}

chorusAlto = \relative c' {
  \global
  \clef treble
  \autoBeamOff
  r2.*18 |
  g2. |
  r2.*6 |
  g2. |
}

\score {
  <<
    \new PianoStaff <<
      \new Staff = "upper" { \verseTreble }
      \new Staff = "lower" { \verseBass }
    >>
    \new ChoirStaff <<
      \new Staff <<
        \new Voice = "s" {
          \chorusSoprano
        }
      >>
      \new Staff <<
        \new Voice = "a" {
          \chorusAlto
        }
      >>
    >>
  >>

  \layout {
    % ragged-right = ##t
    \context {
      \Staff
      \RemoveEmptyStaves
      \override VerticalAxisGroup.remove-first = ##t
    }
  }
}

Here is the output, converted to PNG.  Note that the last 8 measures of the piano verse are off the page.  No warnings are issued when compiling.
Answer: Remember that full-measure rests in LilyPond are input with a capital R. Thus every instance where you have r2. (or r2.*8, etc.), you should instead have R2. (or R2.*8, etc.).
Making this change in all voices corrects the problem. In the example you gave, it's present in the final lines of both the treble and bass and it's present in two lines each for the soprano and alto.

I'll also take this moment to mention the \unfold command in LilyPond. Perhaps you're already aware of this and just didn't include it in your MWE, but instead of writing out c8 e g c g e 18 times, we can instead input \repeat unfold 18 { c8 e g c g e } which will do all of that work for us. And if we need to make edits, it's also much easier to just change the 18 instead of having to add/delete lines as necessary.
Comment: Thanks, I did not know about `R`.  And thanks also for the note about `unfold`.  I had just wanted to replace the notes of the actual song with something simple, to rule out the possibility of a problem with them, and it seemed best not to try anything new and risk introducing more bugs.  But it could be useful in the future.


Need to create Footer for Gridview in Android

Question: See below layout. I am unable to put footer button below a GridView.
Any help will be appreciate.
When Gridview fill in the screen Button is not displayed.
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
 >

<GridView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:columnWidth="90dp"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/gridview"
    android:text="Load More Images" />

 </RelativeLayout>

Comment: See similar post: http://stackoverflow.com/questions/3670176/getting-a-button-to-scroll-into-view-at-the-bottom-of-a-gridview-on-android
Comment: You must close your GridView after the button like this  and ofcourse remove /> from <GridView
Comment: might be helpful for further readers like me! link: http://stackoverflow.com/a/24436309
Answer: I have been keeping searching for a long time for a GridView which allows us to addFooterView and addHeaderView like ListView.
It's a post 2 years ago. I come here by following the link in google search result. I don't know weather this problem has been solved or not.
If not, here is a library which may be helpful. https://github.com/liaohuqiu/android-GridViewWithHeaderAndFooter.
It's very simple:
GridViewWithHeaderAndFooter gridView = (GridViewWithHeaderAndFooter) v.findViewById(R.id.ly_image_list_grid);

LayoutInflater layoutInflater = LayoutInflater.from(this);
View headerView = layoutInflater.inflate(R.layout.test_header_view, null);
View footerView = layoutInflater.inflate(R.layout.test_footer_view, null);
gridView.addHeaderView(headerView);
gridView.addFooterView(footerView);

Here is a screen snapshot:

Hope this would be helpful. Good luck!
Answer: <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
>

 <GridView android:layout_height="match_parent" android:id="@+id/all_workouts_list"
  android:columnWidth="90dp"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp"  android:cacheColorHint="#ffffffff"
    android:layout_width="match_parent"
   android:layout_above="@+id/add_workout_all_workout_list"></GridView>

<Button android:layout_width="wrap_content"
 android:id="@+id/add_workout_all_workout_list" android:layout_height="wrap_content"
 android:text="Add Workout" android:layout_alignParentBottom="true"
 android:layout_alignParentLeft="true"></Button>

</RelativeLayout>

Works fine for me
Comment: NOt listview i want footer after gridview item.
Comment: Oh sorry forgot to change but it works for both List and Grid View Check updated Code
Answer: I managed to add footer to my gridview with a little trick. Lets say your adapters main data is
List of MyDataInfo objects list, now when you passed all the data to adapter you can add two empty(null)
objects and check in getView whether data is null or not and inflate desired view .
// in the adapter
public void addVoid(YourInfo info) {
    dataList.add(info);
    dataList.add(info);
    notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
if (dataList.get(position) !=null) {
    View vi = convertView;
    ViewHolder holder;
    if (convertView == null || convertView.getTag().equals("stop")) {
        //inflate your gridview item
    }
    else {
        holder = (ViewHolder) vi.getTag();
    }

    // provide data to views

    return vi;
    }
    else {
        View v;
        if (position == dataList.size() - 2) {
            v = inflater.inflate(R.layout.show_more, null); // load more view
            v.setTag("stop");
        }
        else {
        v = inflater.inflate(R.layout.progress_bar, null); // progress bar
            v.setTag("stop");
        }
        return v;
    }

}
Before this in your main activity where you set adapter you'll have something like this
YourAdapter adap = new YourAdapter(this, dataList);
gridView.setAdapter(adap);
YourInfo info = null;
adapter.addVoid(info);

And important thing you'll have to handle onitemclick
int size = adapter.getCount();
public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
    if (position == size - 2) {  // user selected SHOW MORE view
         int wantedPosition = size - 1;
         int firstPosition = grid.getFirstVisiblePosition();
     int wantedChild = wantedPosition- firstPosition;
         ProgressBar progBar = grid.getChildAt(wantedChild);
         progBar.setVisibility(View.Visible);
         return;
         }
    if (position == size - 1) // user selected progress bar
         return;
    }

Hope this helps ^^
Answer: Add to GridView two attributes:

android:paddingBottom of the size as your Button;
android:clipToPadding="false"

This will make some space for button at the bottom of the grid.
Answer: Try adding the button first and putting the grid view on top of it. Something like this ought to work:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Load More Images" />

    <GridView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/button1"
        android:columnWidth="90dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp" />

</RelativeLayout>

EDIT
Based on your comments, I can see why the above does not work. Assuming you mean that you want the button to appear only after you scroll to the bottom (and not be on the screen the entire time), here's the layout I recommend:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <GridView
            android:id="@+id/gridview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:columnWidth="90dp"
            android:gravity="center"
            android:horizontalSpacing="10dp"
            android:numColumns="auto_fit"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp" />

        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Load More Images" />

    </LinearLayout>
</ScrollView>

Comment: @DhavalKhant - Let's see if I got the requirements right. When the GridView is short, the button should be just below it, with all extra space below the button. But when the GridView is tall, it should get truncated vertically and the button should be at the bottom of the screen. Is that right?
Comment: its by mistake add by me. see updated code.and i want button after gridview like listview footer.
Comment: @DhavalKhant - Did you try the layout I posted? It should put the button after the gridview at the bottom.
Comment: @DhavalKhant - I'm a bit uncertain about what you do want. Can you elaborate on why this doesn't work for you?
Comment: your code is working fine but i want footer view of gridview like LIstview footer
Comment: @DhavalKhant - Do you mean that when the GridView is shorter than the screen, the button should be below the GridView and not at the bottom of the screen? What do you want to happen when the GridView is taller than the screen? Should there be a ScrollView in here somewhere?
Comment: when gridview is taller than screen , footer should be display after last row in gridview.
Comment: when the GridView is tall, it should not truncated but display in scroll by default and footer after last row.
Comment: I'm trying to show the button at the bottom as well - only after scrolling to the bottom. I tried the second layout (ScrollView), but the grid doesn't scroll anymore :(
Comment: Lint even gives me a warning on this: 'The vertically scrolling ScrollView should not contain another vertically scrolling widget (GridView)'
Comment: @kilaka - Android does not allow nested scrolling (especially if they scroll along the same axis). The framework does not have any support for delivering events to the correct view. You will need to rethink your interface.
Comment: @TedHopp - what do you mean rethink my interface? I gave a feedback regarding your solution - a GridView within a ScrollView prevents the GridView from scrolling.
Comment: @kilaka - It had been the better part of a year since my post and I admit that I didn't go back and look at it after your comment. My mistake. However, with the GridView inside a ScrollView, will it need to scroll? It's going to have a very tall virtual screen in which to lay itself out.
Comment: @TedHopp - It just doesn't scroll, even though there are plenty of elements in the grid. I wish it did :(
Answer: Use the same as the below:
Edited:
<FrameLayout android:id="@+id/linear_Layout_List"
        android:layout_gravity="center_horizontal|top|bottom"
        android:layout_marginTop="90dip" android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:layout_marginBottom="60dip" android:background="#E4E4E4">
        <GridView android:layout_width="fill_parent"
            android:layout_gravity="center_horizontal|top|bottom"
            android:columnWidth="90dp" android:numColumns="3"
            android:horizontalSpacing="10dp" android:stretchMode="columnWidth"
            android:gravity="center" android:id="@+id/Search_Result_Grid"
            android:background="#E4E4E4" android:focusable="true"
            android:verticalSpacing="10dp" android:layout_height="wrap_content"
            android:layout_marginBottom="45dip">
        </GridView>
        <Button android:id="@+id/txt_LoadMoreGrid"
            android:layout_width="fill_parent" android:layout_gravity="center_horizontal|bottom"
            android:layout_height="wrap_content" android:text="Load More...."
            android:clickable="true" android:textColor="#ffffff"
            android:visibility="invisible" android:background="@drawable/top_bar_bg"></Button>
    </FrameLayout>

and Call the onScroll method to hide the same as you want...........this implementation for LOAD MORE functionality in GridView.............It works for me.
grid.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                System.out.println("The first visible Item:"+firstVisibleItem);
                if(width<=320 && height<=480)
                {
                if(firstVisibleItem+5==totalItemCount-1)
                {
                    /*FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT,Gravity.NO_GRAVITY);
                        layoutParams.setMargins(0, 0, 0, 45);
                        grid.setLayoutParams(layoutParams);*/
                    tv_Load.setVisibility(tv_Load.VISIBLE);
                }
                else
                {
                    /* FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT,Gravity.NO_GRAVITY);
                        layoutParams.setMargins(0, 0, 0, 0);
                        grid.setLayoutParams(layoutParams);*/
                        tv_Load.setVisibility(tv_Load.GONE);
                }
                }
                else
                {
                    if(firstVisibleItem+8==totalItemCount-1)
                    {
                        /*FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT,Gravity.NO_GRAVITY);
                            layoutParams.setMargins(0, 0, 0, 45);
                            grid.setLayoutParams(layoutParams);*/
                        tv_Load.setVisibility(tv_Load.VISIBLE);
                    }
                    else
                    {
                        /* FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT,Gravity.NO_GRAVITY);
                            layoutParams.setMargins(0, 0, 0, 0);
                            grid.setLayoutParams(layoutParams);*/
                            tv_Load.setVisibility(tv_Load.GONE);
                    }
                }
            }
        });

Comment: Actually Dhaval I had also get the same problem before 6 months, and I searched for the same enough on web but unable to succeed even I also get the same answer as you have but failed then after I implemented on my own and get the positive result which is the my answer, if this answer is not working for you then please think yourself, how to do it, because Gridview doesn't have any footerview.
Comment: Hello Sanat, how did you get the width and height values? Thanks.
Comment: if(width<=320 && height<=480) width?
Answer: check if this helps
<Button
    android:id="@+id/button1"
    style="@android:style/ButtonBar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:text="Load More Images" />


Inserir se não existir ou Atualizar se já existir no Mysql?

Question: Como posso no MySql dar um INSERT ou um UPDATE se a linha em questão já existir ou não?
Tentei da seguinte forma mas não funcionou:
IF EXISTS (SELECT * FROM configs WHERE id_serie = :id)
           UPDATE configs
                SET dados = :valor
                WHERE id_serie = :id
ELSE
    INSERT INTO configs (id_serie, dados) VALUES (:id, :valor)

Porém não funcionou, li sobre o ON DUPLICATE KEY UPDATE mas como a coluna que uso para verificar no caso id_serie não é a chave primaria da tabela, imaginei que não fosse funcionar, ou funciona?
Answer: Você pode tentar utilizar o REPLACE INTO. Ele é semelhante ao INSERT, porém se o registro a ser inserido possua o mesmo valor de uma chave primária ou de um índice único, o registro existente é apagado e o novo registro é inserido.
REPLACE INTO configs (id_serie, dados) VALUES (:id, :valor)

Caso queira dar uma olhada na documentação: Mysql - REPLACE Syntax
Comment: Mas neste caso, se eu alterar só uma coluna, o novo registro vai obter todos os valores das outras colunas antigas e inserir no novo atualizando somente o que eu preciso?
Comment: Não. Se você deixar alguma coluna sem informar, você perderá o valor desses campos.
Comment: Não me parece muito seguro fazer desta forma, acho que vou acabar tendo que combinar um pouco de PHP com esse UPDATE / INSERT
Answer: Tente uma das formas abaixo.
Atribuindo em uma variável o total de registros encontrados.
declare @total int;
set @total = (select count(*) from configs where id_serie = :id)

if (@total > 0)
    update anime_configs set dados = :valor
    where id_serie = :id
else
    insert into configs (id_serie, dados) values (:id, :valor)

Ou verificando a quantidade de registros afetados no update. Se o update der erro (porque já existe) então será retornado zero registros, e com isso, chamará o insert.
update anime_configs set dados = :valor where id_serie = :id
if (@@rowcount = 0)
    insert into configs (id_serie, dados) values (:id, :valor)

Comment: Isso funciona pra MySql? Testei ambas aqui e da erro
Comment: E qual o erro em ambas?
Comment: Já tentou assim (ps: não sei se funciona)? `IF(INSERT INTO configs (dados)
       SELECT :valor WHERE NOT EXISTS (SELECT 1 FROM config WHERE id_serie = :id))
ELSE
       UPDATE configs SET dados = :valor WHERE id_serie = :id;`
Answer: O mysql possui um parâmetro que verifica se o registro existe e caso exista vc poderá dar um update. segue o exemplo.
INSERT INTO cliente (id, nome) VALUES (10, 'nome do cliente') ON DUPLICATE KEY UPDATE nome = 'nome do cliente';

você poderá atualizar vários campos separando por "," Vírgula. a única obrigação é a chave única (primary key).


Why Assumed Density Filtering is also called Moment Matching?

Question: I am learning about Assumed Density Filtering (ADF) and Expectation Propagation in the context of bayesian deep neural networks. I have seen in some textbooks and papers that ADF is also called moment matching. Is it called moment matching because we always solve it by minimizing KL Divergence by showing the moments of two distributions match? is this the reason behind it?
Answer: Hope it's not too late...
I also wandered about this when working on my thesis.
In a nutshell, this is true for any approximating distribution which belongs to the exponential family of distributions.
Recall that in EP we are repeatedly performing the assumed density filtering algorithm (ADF) until convergence. The moment matching happens at each ADF iteration, i.e. when solving:
$$ \min_{\xi} D_{KL}\left( \hat{p}_{i}(\theta|\xi_{i-1})||q(\theta|\xi) \right)$$
Where $\hat{p}_{i}$ is what Minka calls the exact posterior and $q$ is the approximating posterior and in general is assumed to belong to the (non-curved) exponential family of distributions. Hence:
$$ q(\theta|\xi) = exp\left( \xi^{T}T(\theta)+S(\theta)+A(\xi) \right)$$
We can easily show that $D_{KL}$ in the optimization problem is convex w.r.t $\xi$ thus the first order condition (i.e. equating the derivative to zero) is sufficient for optimality.
If you do the math (we also need to assume we can switch between derivatives and integrals) the first order conditions are:
$$ {E}_{\hat{p}_i}\left[ T(\theta) \right] = \frac{\partial}{\partial \xi}A(\xi)$$
To see why the last equation is interpreted as moment matching notice the for distribution from the non-curved exponential family, the first derivative of the log-partition function $(A(\xi))$ is the expectation of the sufficient statistic $(T(\theta))$. So the first order condition can be written as:
$$ {E}_{\hat{p}_i}\left[ T(\theta) \right] = E_{q}\left[T(\theta) \right]$$
Which is interpreted matching expectation of the sufficient statistic between the exact posterior and the approximating posterior.
Answer: Assumed Density Filtering approximates the Bayesian posterior to a distribution we wish to assume. If we assume the posterior to be a Gaussian Approximation, then it can be called Gaussian Density filtering.
So to approximate it, we only need to compute the mean and variance of the resultant distribution and use them as parameters of the gaussian posterior.  Hence the name moment matching.

Gaussian-density filtering computes an exact one-step posterior p(θ) and then approximates it to get qnew(θ) which is a Gaussian Distribution. So essentially, we want-

A more detailed explanation of this can be found in T.Minka's paper -https://tminka.github.io/papers/ep/minka-thesis.pdf
To see one application of assumed density filtering, you can read this article Understanding the Working of Multi-Armed Bandit in VWO
Comment: So the broad idea is because true posterior is intractable we assume a posterior distribution and try to estimate its parameter s.t. our approximated assumed density is close to true posterior. In the case of gaussian, it is simply by matching the mean and variance.
The same rule I believe should work for other distributions also like Laplace provided we are able to estimate its parameters from these moment parameters.
Comment: Thank you for your answer. So, you mean that the matching of the moments only occur when the assumed density is a gaussian? what if the assumed density is a Laplace for example? in this case after minimizing KLD, we will get a matching among the moments again. Am I right?
Answer: The reason this is called moment matching is that the prior & approximate posterior is generally taken to be in the exponential family, the parameters of which can be estimated by matching the appropriate moments. See
Zhou, E., Fu, M. C., & Marcus, S. I. (2010). Solving continuous-state POMDPs via density projection. IEEE Transactions on Automatic Control, 55(5), 1101–1116.
There are many names for this approach, which has been rediscovered in numerous fields.


CSS - media queries / RWD , logo image file hiding behind fixed nav

Question: I'm working on the media queries for a site and I'm stuck on a static logo image which sits within the header but only when the screen size is min-width 960px.
Above that size I have an interactive particle logo image but when the screen is reduced down to mobile-size I just want a logo in the header. The problem is the logo simply isn't showing. I suspect it is being hidden by the nav bar which is fixed in position.
This is how I have my code at the moment -

            Home
            What we do
            Who we are
            Who we work with
            Say hello
            Blog

styles.css/media queries
 #logo {

  width: auto;
  height: auto;
}

#logo img {

   width: 200px;
  height: 100px;
}

/* RWD for logo (particle-slider is id for interactive logo) */

@media screen and (max-width: 960px) {

    #particle-slider {
        display: none;
    }

}

@media screen and (min-width: 960px) {

    #logo img {

        display: none;
    }

}

     @media screen and (max-width: 480px) {

    body {
    max-width: 500px;

}

  header {

    height: auto;

  }

  nav {

    text-align: center;
    padding-bottom: 10px;
    padding-top: 10px;

  }

  nav a {
    display: block;
    border-bottom: 0;

  }

  #logo {

    height: auto;

  }

  #logo img {

    width: 200px;
    height: 100px;
  }

So, when I shrink the page right down to 480px or less then nothing shows in the header other than the nav bar. How do I show the logo image in the header when I shrink the page?
Comment: According to your code, for the large sizes (min-width:480px), you have hide the the main logo and less than 480px, then logo will show in your page.

So what do you need to do exactly?
Comment: pls provide a working jsfiddle
Comment: @sajee My problem is, the logo is not showing when I shrink the screen and I need to find out why.
Answer: I found the answer with this Q&A here
Basically my nav was held in a fixed position and covering the logo so I had to revert the position:fixed rule to position:static


if else in inner join for select query

Question: I want to perform select query if else in innner join
if IsStatus =0 then i want to inner join with T_valDob and show val column from that table.
if IsStatus =1 then i want to inner join with T_valSob and show val column from that table.
IsStatus  is bit type.
T_MappingTable

MappingID
valID
IsStatus

0
1
0

1
2
0

2
3
0

3
4
0

4
5
0

5
1
1

6
2
1

7
3
1

8
4
1

9
5
1

10
6
1

T_valDob

valID
val

1
val1

2
val2

3
val3

4
val4

5
val5

6
val6

7
val7

8
val8

T_valSob

valID
val

1
valSop1

2
valSop2

3
valSop3

4
valSop4

5
valSop5

6
valSop6

7
valSop7

8
valSop8

Like i want final output like this in single resultset

MappingID
valID
IsStatus
val

0
1
0
val1

1
2
0
val2

2
3
0
val3

3
4
0
val4

4
5
0
val5

5
1
1
valSop1

6
2
1
valSop2

7
3
1
valSop3

8
4
1
valSop4

9
5
1
valSop5

10
6
1
valSop6
Answer: I would think you probably want to do a UNION query, such as:
SELECT MT.MappingID, MT.valID,MT.IsStatus, TD.val
FROM T_MappingTable MT
INNER JOIN T_valDob TD on MT.valID = TD.valID
WHERE MT.IsStatus = 0

UNION ALL

SELECT MT.MappingID, MT.valID,MT.IsStatus, TS.val
FROM T_MappingTable MT
INNER JOIN T_valSob TS on MT.valID = TS.valID
WHERE MT.IsStatus = 1

Answer: I don't think that this can be done with two INNER joins because no row from T_MappingTable can have both IsStatus = 0 and 1.
I think you want two LEFT joins with a CASE as part of your SELECT something like this:
SELECT TMap.MappingID,
       TMap.valID,
       TMap.IsStatus,
       CASE WHEN TMap.IsStatus = 0 THEN TDob.val ELSE TSob.val END AS val
FROM T_MappingTable AS TMap
     LEFT JOIN T_valDob AS TDob ON TMap.valID = TDob.valID AND TMap.IsStatus = 0
     LEFT JOIN T_valSob AS TSob ON TMap.valID = TSob.valID AND TMap.IsStatus = 1;

if else in inner join for select query


Views filter referenced content when end date is over

Question: This view is the result of a given postcode. how could I hide/filter referenced content when its end date is over? The referenced content should disappear but the non referenced content should still be displayed.
Answer: I'm not so sure this is possible through the views interface. But, you can easily do this through your theme layer.
In your view admin area, under advanced there's the page: Theming information. Clicking on that will give you a list of available tpl.php names that can be used to create your own tpl.php files that can be added to your theme. Your probably gonna wanna use a row style output. The list of those files go from general to specific, so the last time will only be applied to your view. Clicking on the link of row style will give you the content of the default file.
All you would need to do is just print the fields as normal, with the exception of the fields you want to exclude. Just use a standard if to check to make sure they're still valid, if not, don't print them.
Comment: Thanks for the answer. It's not about the layout, it's about the functionality. I'm not sure if I understand what you're saying.
Comment: Did it with custom JS
Answer: My suggestion would be that you display your Starts/Ends timer in another view as an attachment (or you could bring it in using views field view module).
Create this second view as your timer interface, but set your Filter Criteria to only show results when
Current Time > Start Time AND
Current Time < End Time
I've done something similar where I only wanted to show something based on a property within the view

In my example above, the first date/time is set to greater than or equal to now, the second is set to less than or equal to now. In the setup, you set the relative date as 'now' and it will work on what time the page has loaded

Then you can pull this second view in as mentioned above, but it should mean that this second view will return no results outside of the times you specify. However, unless you have an AJAX method that will refresh the table when the timer reaches 0, it will show a result based on when they first load the page
Comment: thanks for the answer and the visual aid. I did as you suggested with the views embed module. It looks good but it shows all the second view 's content, it's not related to the 'shop' anymore. Also the filters dont work ( I have a referenced start date equals today & end date equals to or greater than now. If I use greater than, everything disappears, this shouldn't be the case. ) I need help this is way too complicated for me. thanks guys
Comment: I don't think it's possible to do that and still keep the relationship


Encryption of data in an Ionic App

Question: I was working on an Ionic app where the requirement was to store the data locally while the n/w is not available. So I was using PouchDB with sqlite to store the data locally and we need to make sure to send the data in an encrypted format when the n/w is available.
I know I should go for an assymetric encryption here but is there a cordova plugin, I shoud look at or should I look at developing one?
Answer: You have a couple options:

Cordova-sqlite-storage with sqlcipher adapter
crypto-pouch

The advantage of the first one is that encryption is done at the SQLite level rather than the JavaScript level, so it ought to be more performant. The disadvantage is that the SQLite Plugin is typically not recommended for PouchDB due to bugginess.
If the second one is performant enough for your use case, I'd say go with it.
Comment: Hi nlawson,
I am confused whether to use sqlcipher adapter  with the SQLite plugin or use it as a standalone plugin for sqlite db operations? I have gone through the documentation but I am unable to get started.

Encryption of data in an Ionic App


Have I found an error in Williams' "Martingales" exercises?

Question: I want to solve Problem EG.2. from Probability with Martingales:

Planet X is a ball with centre O. Three spaceships A, B and C land at random on its surface, their positions being independent and each uniformly distributed on the surface. Spaceships A and B can communicate directly by radio if $\measuredangle AOB < 90^\circ$. Show that the probability that they can keep in touch (with, for example, A communicating with B via C if necessary) is $(\pi + 2)/(4\pi)$.

I believe I have shown that the probability is in fact $(2 \pi + 1) / (4 \pi)$. To begin, we denote by $AB$ (resp. $AC$, $BC$) the event that $A$ and $B$ are within $90^\circ$ of each other. We then observe that the probability that communication is possible is given by:
$$P(comms) = P(AB \cup (AC \cap BC)),$$
which after some basic manipulation may be re-written as
$$P(comms) = P(AB) + P(AC \cap BC) - P(AB \cap AC \cap BC).$$
We then proceed by computing each term on the right-hand side. (A warning that my argument and notation is somewhat loose, and I would appreciate any ideas about tightening it.) For $P(AB)$, we have
$$P(AB) = \iint_S P(AB | A = x) \frac{1}{|S|} dS(x),$$
where $S$ denotes the planet's surface and $|S|$ its surface area. By symmetry, we see $P(AB|A) = 1/2$, so that $P(AB) = (1/2)(1/|S|)|S|=1/2$.
Next,
$$P(AC \cap BC) = \iint_S P(AC|C = x) P(BC|C = x) \frac{1}{|S|} dS(x).$$
By the same argument as above, $P(AC|C) = P(BC|C) = 1/2$, and hence $P(AC \cap BC) = 1/4$.
Finally, we have
$$P(AB \cap AC \cap BC | A=x) = \iint_{S/x} P(AC \cap BC | A = x, B = y) \frac{1}{2|S|} dS(y),$$
where $S/x$ denotes the hemisphere of $S$ centred on $x$. Now, $P(AC \cap BC|A=x,B=y)$ corresponds to the fraction of $S$ covered by the intersection of $S/x$ and $S/y$. If we define a spherical coordinate system on $S$ with $x$ corresponding to polar angle $\theta = 0$, then this fraction is given by $1/2 - \theta(y)/(2 \pi)$ for $0 \leq \theta(y) \leq \pi/2$ (i.e. $\theta(y)$ in $S/x$), and hence
$$P(AB \cap AC \cap BC | A=x) = \frac{1}{4} - \frac{1}{4\pi}$$
(where I skip performing the double integral above here explicitly for brevity).
All up, we then obtain
$$P(comms) = \frac{2 \pi + 1}{4 \pi},$$
as stated above, which disagrees with Williams' stated result, although no mistake is obvious to me. Moreover, I have written a Monte Carlo simulator in Python that seems to confirm my result (and which I can provide if anyone would find it useful).
In summary, I ask the following: (1) Is Williams correct, or am I?; and (2) How can my argument be made tighter, more rigorous, or more elegant?
Answer: The problem is ambiguously worded. You sensibly took "they" to refer to spaceships A and B, the subject of the previous sentence, but it's meant to refer to all three spaceships, the subject of the sentence before that.
Your calculations are correct, and for the probability that all three spaceships are in contact they yield
\begin{align}
P(AB\cap BC\cap CA)+3P(AB\cap BC\cap\overline{CA})
&=
3P(AB\cap BC)-2P(AB\cap BC\cap CA)
\\
&=
3\cdot\frac14-2\cdot\left(\frac14-\frac1{4\pi}\right)
\\
&=
\frac{\pi+2}{4\pi}\;.
\end{align}


Put a List into natural order. Doesn't work

Question: It is maybe not a good implementation but I want to know why my sorting doesn't work. The only thing I managed is to get rid of the "text" from the list. Maybe it is not a good practise to use list in sort() method and I should use an array but I want to see that it can be done with a List aswell.
public class MyProgram {

    public static void main(String[] args) {

        // Text from TextField.
        String unorderedMixedText = "10 text 2 43 -12 0 41";

        String[] toArrray = unorderedMixedText.split(" ");

        List<Integer> numbers = new ArrayList<>();

        // To get only numbers in text.
        for(int i = 0; i < toArrray.length; ) {
           try {
              numbers.add(Integer.parseInt(toArrray[i]));
              i++;
           } catch (NumberFormatException e) {
               i++;
           }
        }
        // Unordered
        Arrays.stream(toArrray).forEach(s -> System.out.print(s + " "));

        // Empty line
        System.out.println();

        sort(numbers);

        // Ordered
        numbers.stream().forEach((number) -> System.out.print(number + " "));
    }

    private static void sort(List<Integer> list) {
        for(int i = 0; i < list.size() -1; i++) {
            for(int j = i+1; j  list.get(j)) {
                    int big = list.get(i);
                    int small = list.get(j);
                    list.set(i, small);
                    list.set(j, big);
                }
            }
        }
    }
}

I get this output from my program.
10 text 2 43 -12 0 41
10 2 43 -12 0 41

Comment: just call `Collections.sort(numbers);`
Comment: "Ready to use code" is always better, but this is for learning purpose. :)
Answer: There is a problem in your loop:
        for(int j = i+1; j  list.get(j)) {
                int big = list.get(i);
                int small = list.get(j);
                list.set(i, small);
                list.set(j, big);
            }

i+1 is always > i so your loop won't work
Comment: Exactly. you don't enter the inner loop.
Comment: `for(int j = i+1; j < list.size(); j++)` solved my problem! Thanks! :)
Answer: As an alternative to your approach, you might like to know about the Comparator, which is a class that  you can use for arbitrary comparisons of Collections (like Lists and ArrayLists). For your example, for instance, we could do something like this:
import java.util.*;
public class Test {

  public class NaturalNumbers implements Comparator<Integer> {
    // natural comparison is strictly based on what the result
    // of "a minus b" is. So let's just do that!
    public int compare(Integer a, Integer b) {
      return a.intValue() - b.intValue();
    }
  }

  public static void main(String[] args) {
    new Test();
  }

  public Test() {
    String s = "1 cats 5432 one two 32 63 12 364 -243 13 lol";
    // turn that into a list of valid Integers:
    List<String> _terms = Arrays.asList(s.split(" "));
    ArrayList<Integer> terms = new ArrayList<Integer>();
    for(String term: _terms) {
       try {
         terms.add(Integer.parseInt(term));
       } catch (Exception e) {}
    }
    // sort that list using a natural ordering comparator:
    Collections.sort(terms, new NaturalNumbers());
    System.out.println(terms.toString());
  }
}

We define a string list, split it and then discard all the "these are not number" elements, and then we run a natural ordering comparator over the resulting list of Integers. Success, the resulting sorted list starts at -243 and ends in 5432.
In fact, we technically don't even need the Comparator to sort numbers by natural ordering, because without an explicit comparator Collections.sort(list) will sort according to natural ordering anyway, but frankly I'm assuming this is homework and tomorrow you're going to be asked to sort this list in a completely different way. Now you know how you'll be able to achieve that.
Comment: Why not just `Collections.sort(terms)` ?
Comment: mostly because if his sorting requirement changes at the drop of a hat (this smells like homework, after all), oxyt now knows enough to do so. Worth pointing out that plain sort()'s natural already in the answer, though.
Comment: Well, you won't need a custom comparator to sort in reverse order either.
Comment: you don't need a comparator for many things, if you're willing to get crafty enough with your preprocessing. I didn't post this answer to get the points for being right, I posted it because the person asking the question deserves to see more than one way to tackle a problem, and the most encompassing way Java lets you do this is comparators. Other people already gave "right" answers.
Comment: Mike thank you for your answer/effort. Its good practise to see an alternative solution aswell. Thank you! :)


Piano agility -- hitting a wall with speed

Question: I've started up practicing piano again in the last few months after 15 years of classical lessons and then a 7 year gap, and I'm running into a similar issue to one I had back in the day playing piano, hoping you can help me find a solution.
With a piece, I can get up to a moderate tempo, depending on the piece, somewhere in the ballpark of 16ths at quarter = 100, but I can't get it up faster than that while maintaining clarity and accuracy.
This is the section I am having the most trouble with, early in Scriabin sonata no. 1. I'm much further along in the piece and most everything after this point has been coming together nicely, but the 16ths in the left hand are creating problems for me. I'm currently kind of stuck in the dotted quarter = 65-70 range (i.e. quarter = ~100), but generally I need to practice for a while in the 55-60 range, then depending on day, I can play at 65-70 for a bit with good accuracy/clarity, but it degrades as I continue playing, and overall I'm not making progress towards getting it faster than that while playing cleanly.

I think my problem is that at lower tempi I'm playing more rigidly, each note quite distinct rather than blending together with the others, and probably too much tension, then to get faster I have to relax and play more 'flowy', which allows me to play faster, but I can't maintain sufficient control, I have trouble playing precisely with a metronome, and my hands get a bit out of sync in spots (not completely separate, but notes don't line up perfectly). My pedaling also goes to junk as I'm focusing too much on my hands. Another issue is that my legato gets bad at higher tempi when I play without pedal, the left hand kinda just becomes jumpy, but when I try to fix that, the tension builds up in my left hand and I am forced to slow down.
I've found that the times I play best are when I'm only thinking about my right hand and just letting my left hand go along for the ride, then increase the speed of my right hand and the left hand somehow manages to keep up for the most part and sound pretty good. I think this helps my left hand relax and for my hands to synchronize without actively trying to synchronize. But it's still not perfectly accurate, and I don't know how to clean it up without putting my mental focus on the left hand again.
Basically, I think I'm playing with a different feel at higher tempi, but I'm having difficulty practicing that same feel at lower tempi, so it's difficult to clean up.
I practice scales, can do a C major at a little over 100 quite cleanly, but as I speed up, I have the same issue with my left hand building up tension, particularly on the descent with the thumb cross-unders. I do practice arpeggios a bit but I struggle with them - perhaps that's where I'd benefit most.
Does anyone have any suggestions on how I can fix this? My professor in college focused a lot on hand positions, angles, and especially addressing my tension issues, and I've been trying to be conscious of all that and find mechanical solutions to my problems that aren't just 'practice more', but it's been years since those lessons and I'm probably forgetting things she taught me that could be helpful here. Not that I'm opposed to practicing more -- definitely not -- but the fact that I've hit a wall for over a month on this one section where I really can't get it faster without messing up other things, I think there's gotta be something smarter I can do in how I practice.
Comment: There are levels of musicianship that can be almost impossible to achieve without a teacher - something to strongly consider. Tension in my experience has always been the main thing that slows us down on any instrument. Playing with the minimum amount of effort is usually the key to unlocking speed. Without a teacher, one thing I can think of is looking at exercises suggested by Josh Wright and others: https://www.youtube.com/results?search_query=josh+wright+speed
Comment: There are really two questions here: 1) How, in general, to improve speed, and 2) How to practice the Scriabin. I suggest refocusing your question on the Scriabin, because the more general question is a duplicate of [Playing a classical piece at full speed](https://music.stackexchange.com/q/38578/70803) and [How to practice for speed and consistency](https://music.stackexchange.com/q/97635/70803) as well as other posts specific to scales and arpeggios.
Comment: A further question other than what Aaron noted, and related to what Todd wrote: how to improve "performance". Not just in the sense of "music performance", but of the physical (and psychological) efficiency. It's normally explained as "best result with minimal effort", but a better way to consider it is to put the minimal effort required to get the best result (which is quite different). While it's not impossible to achieve that, it requires a lot of self-awareness, proper self-criticism, knowledge/experience and personal (psychological) research. Most of the times, that means a good teacher.
Answer: The following are only my experiences and may not work for everyone.
First I start with slow playing. Getting it correct. You've done this and seems to be OK.
Next, I go absolutely as fast as I can. The goal now is to see what motions I have subconsciously changed because I'm going faster, then revisit my slow playing and see if I am using incorrect techniques.
One common mistake is keeping the fingers on the keys for far too long. This will affect your wrist movement as you twist it all over the place just to keep your fingers on the keys. At sub 100 speed playing scales, you can do that, but at around 120 playing 16th, you can play a 123 (on the right hand), literally shift the entire hand to position the thumb on the 4th note, while keeping your wrist and fingers in the exact same position, and start playing. If you keep the proper speed (we're talking 8 notes a second here), you actually cannot hear much of a gap. At this speed, the techniques change because you no longer need to keep your fingers on the keys for so long.
The way you play at high speed involves very minimalized wrist movement, highly predictable and practiced vertical finger motions so that your focus is on horizontal positioning. The wrist position will cater to sections of music instead of individual notes.
If I need a high-speed run, and there are a lot of black notes, I will angle my wrist and practice doing the entire fast run in one wrist position, instead of twisting and changing my wrist as it goes up. This WILL involve some odd feeling finger extensions, since you will be reaching out further than normal on some keys, but at that speed, nobody cares.
I would also look at videos of other pianists and observe their movements at high-speed playing. Pay attention to what exactly they move and don't move. You'll notice that the wrists move LESS at high speeds.
Comment: This is all very helpful, but in particular the idea of playing as fast as I can, then going back to a slower tempo has already shown great results for me. I need to do a bit more conscious analysis of what I'm doing at those faster tempi, but even just playing through a couple times as fast as possible, then slowing back down to where I was at before has helped enormously even just in my practice last night. Playing at the slower tempo immediately felt way easier and lighter and I was able to maintain accuracy, tone, musicality, etc better as I increased speed. Thank you for the great answer.


Is there a good Guitar Chord building web site?

Question: I'm looking for a chord builder web site. Is there one that shows what strings are being played and what chord it is?
I'm specifically looking for the following chord, but ask for a web site so I can learn to fish.
<code>$6.x.$5.0.$4.2.$3.1.$2.2.$1.0 ||
</code>
Comment: This is Amaj7 chord.
Answer: This site is gona do it for You:
http://chordfind.com/
Here You can browse by chord type and see chord shape on fretboard, or enter the fret numebers or x - and find a chord name.
This is a basic to intermediate chord site, You won't find any advanced voicings there.
Answer: Chorderator lets you look up chord shapes by name, names by shape, and scales, in any tuning.
http://www.chorderator.com
Comment: That is a great designed web site!!
Answer:
Feel free to add websites/apps/etc to the list below.

List of Guitar Chord Websites

Chord Find
Chorderator
Study Bass
Chord Book
Gitarrengriffe Online (German)

List of Guitar Chord Apps

Guitar Toolkit
Garage Band Chord Trainer
Answer: I use this one:
http://www.studybass.com/tools/chord-scale-note-printer/
Don't let the url fool you, this little tool can give you chords and scales for most stringed instrument.
Very handy. :-)
Answer: The iPhone app Guitar Toolkit is awesome for this type of chord search. You can plot the exact fingering and it will tell you what chord you have. This differs from most chord lookup sites and apps in that you don't have to search through a bunch of chords to identify the one you are looking for.
Find it here: http://itunes.apple.com/us/app/guitartoolkit/id284962368?mt=8
There may be some other resources out there to look up chords in this "reverse engineering" approach, but this app is something I started using when it first came out and is a good all in one tool for a number of things.
Comment: There's also an app called Guitar Tools, by Planet Waves, which is great as it has both types of chord lookup. You can name the chord and scroll through different voicings, OR you can punch in your fingerings and it'll tell you the chord. (It also has a scale tool, tuner and metronome). My only complaint is that I can never remember which type of chord lookup tool I need; they're rather cryptically named. http://itunes.apple.com/us/app/planet-waves-guitar-tools/id375703586?mt=8
Answer: http://www.ultimate-guitar.com/top/top100.htm and
http://www.hotfrets.com/chordfinder.asp are the best guitar website, I know so far.
pretty cool!
Hope will help you!
Answer: This is a good one I've been using though:
http://musictheorysite.com/namethatchord


lowercase a string with struts?

Question: I have a need to lowercase some text coming back from an external web service in all caps. I need to do this with with struts and not Javascript. Is it possible?
I am pretty new to Struts and I didn't really find anything searching the tag reference.
Answer: Maybe with the toLowerCase() java.lang.String method?
Comment: +1 also for simple things like this you should look at the underlying language to see if it is possible. As an example googling for "convert string to lowercase struts" probably won't get you much but "convert string to lowercase java" should reveal the answer.
Comment: @Flash84x : It is surprising, how much can go wrong, If you know just little less, then you do now.
Comment: This one saved my day. :)
Answer: I assume you mean in the jsp? Then the following OGNL in a property tag will work fine:
<s:property value="myStringValue.toLowerCase()"/>

PS: +1 to Enrique but the OP may not have known OGNL expressions of type string could use string methods.
Comment: This was exactly what I was looking for - I wanted to just convert a String to lowercase on the JSP without any additional processing in the Java actions.
Answer: Some beginners are surprised, that
String exVal = "SOMETEXT";
exVal.toLowerCase();

does not work. This is because Strings are immutable in Java, so you need to use
String exVal = "SOMETEXT";
exVal = exVal.toLowerCase();

or just "SOMETEXT".toLowerCase() before use.
Answer: If you're using the JSTL: ${fn:toLowerCase(myString)}

lowercase a string with struts?


How to programmatically change a Views page's html  separately to its on-page title?

Question: Similar to Views: how to programmatically change Views title?, I want to update the title of a Views page using logic/data only possible in PHP.
However, I want this to update only the appropriate
 part of the <title> of the HTML  without  mirroring the change in the displayed title in the 's
.
To illustrate, imagine a view with some exposed filters that are used for navigating a product catalogue. Currently, every filtering of this page has the same titles:
<title>Products | My site name</title>
...

Products

I've written some code requiring access to $view->exposed_input that generates an appropriate string based on exposed filter choices (for example, "red, low cost, good condition"), similar to Using exposed filters as part of the rendered page's title. I want these in the html head title, so each navigable URL has a unique title with appropriate keywords for the content. I don't want them in the
, however, because they're already clearly visible in the exposed filter page UI and I don't want to duplicate the information. I want it to look like this:
<title>Products: red, low cost, good condition | My site name</title>
...

Products

Things I've tried:

Everything on that linked question applies to both the head and body titles

<title>Products: red, low cost, good condition | My site name</title>
...

Products: red, low cost, good condition

drupal_set_title() doesn't work at all from any of the Views hooks I've tried, presumably because the view overrides this further down the line. I've tried:

hook_preprocess_views_view
hook_views_pre_render
hook_views_post_render

Setting $vars['head_title'] in hook_preprocess_views_view also doesn't work, presumably for the same reason: Views overrides this.

Someone commenting on the hook_views_post_render API page with the exact same problem as me 3 years ago reports that it still doesn't work if you pass the variable to through to hook_preprocess_html and apply it to $vars['head_title'] from there
Answer: I think what you're looking for is hook_preprocess_HOOK where HOOK is either html, page or both.
Comment: Just done some tests, `hook_preprocess_html` can override the view set title, `hook_preprocess_page` it seems can't; but the next problem is piping the string variable generated in the views hook using views data somewhere it'll be available within `hook_preprocess_html`. I've tried just attaching it to a custom key on the `$vars` variable within `hook_preprocess_views_view` but it's then not present within `hook_preprocess_html` for some reason.
Comment: Aha, cracked it: using [a static variable function](https://drupal.stackexchange.com/questions/24362/pass-variables-from-html-preprocess-function-to-page-preprocess-function) with a call that sets the variable in `hook_preprocess_views_view` (or any Views hook, really) and a call that gets the variable in `hook_preprocess_html`
Answer: It might be possible to do this through tokens and the Views UI if you have the Metatag module and its Metatag Views sub-module installed; one of the options in the Metatag box it adds to the Views interface is a title builder that applies only to the  <title>.
Unfortunately this isn't an option in this example because exposed filter selections aren't currently available as tokens. There is one module to allow this, but it's an unsupported experimental sandbox.

If it's not possible or practical to use tokens, after a lot of experimenting I found something that works on the PHP side:

Generating the Views-based content in any Views hook
Setting it as a Drupal static variable using a helper function as outlined in the answer to Pass variables from html preprocess function to page preprocess function
Retrieving it from within hook_preprocess_html then setting it using $vars['head_title']
Re-apply the | My Site Name part of the string

Example code which can all go in the theme's template.php:
// variable getter and setter function, modified slightly from Clive's
function _something_var($var_name, $new_val = NULL) {
  $vars = &drupal_static(__FUNCTION__, array());

  if ($new_val != NULL) {
    $vars[$var_name] = $new_val;
  }
  return isset($vars[$var_name]) ? $vars[$var_name] : NULL;
}

// set the variable using data from the view object
function something_preprocess_views_view(&$vars) {
  $view = $vars['view'];

  if ( $view->name == 'something' ){
    $title_override = '...'; // do stuff with $view to generate title
    _something_var( 'title_override', $title_override );
  }
}

// get the variable after Views has finished setting its title
function something_preprocess_html(&$variables) {
  $title_override = _something_var( 'title_override' );

  if( $title_override ){
    $variables['head_title'] = $title_override . ' | ' . variable_get('site_name');
  }
}

Comment: The example code above has caching issues. Unless you disable the render cache or set the view's caching setting to 'none' the something_preprocess_views_view hook only gets called the first time the page is accessed because the view gets cached for subsequent page views. So your custom page title will only appear on the first page view.


Zend serialization is not storing relationship between objects

Question: I'm working on an app in PHP with Zend in which I need to store a list of people and the city of each one.
So I have $person->city.
When I get the person information I do $person->setCity($aCity) to setup the corresponding city information.
And person has all the information.
Then I do $this->Sesion->People = serialize($people) [$people is an array of person objects]
Then, when I do unserialize($this->Sesion->People), People just have the information about the people, not about the city of each person, so If I try to do $person->getCity() the result is null or empty, what is different to what I had before the serialize.
Is it possible to do that? Can I do it in a different way?
Answer: For serialize to work with object as requested.
You need to implement __sleep for serialize and __wakeup for unserialize
Please read http://php.net/manual/en/oop4.magic-functions.php for more details.


GAE custom domain but with SMTP control

Question: I understand that in order to link my domain to my GAE application I need to setup Google Apps according to this.
But Google Apps seems to take control of SMTP and email addresses. I need to have my own SMTP server in GCS, which is working perfectly right now using the static ip like firstname.lastname@example.com
What I need is to be able to enter my GAE web application thru mydomain.com but at the same time being able to receive firstname.lastname@example.com at my SMTP instance at GCS. Is it possible?
Comment: The second approach, not modifying DNS registers should do it.
Comment: Probably in this case is safe to skip mail-related DNS registers. Google Apps is does more than support GAE, and probably you don't need this additional functionality.
Comment: Xavier: you are saying that I can skip using Google Apps or that I can use Google Apps and skip its mail related functionality not modifying some DNS registers?
Answer: Your email settings are determined by your registrar, not by Google Apps. If you don't want to use Gmail as your mail server, you simply keep your DNS records unchanged, as Xavier correctly suggested.

GAE custom domain but with SMTP control


Where do I go on the Citrix XenApp server to recreate Outlook profile?

Question: We are running Citrix Xen Servers 6.5. We are using roaming profiles with folder re-direction.
I am having an issue with a single user's Outlook 2010 application where during the launch process and the inbox loading, the following error will display:
Microsoft Outlook has stopped working. A problem caused the program to stop working correctly. Please close the program.
One cannot continue. I have to click 'close the program' and Outlook closes.
The user has no other problems with any of the other streamed applications. No other users are experiencing any issues with any applications.
It was doing the same in the user's XenApp Desktop environment. No issues via OWA or on the smartphone. No other user has this issue. I resolved the crashing on the XenApp desktop by recreating the local profile there (control panel – mail –profiles).
Where would I go to re-create a new Outlook profile for the user streaming via XenApp? I tried re-creating his Outlook folder under UPM_profile on our file server where all our user data is stored but that doesn't seem to be it.
Path is X:\Shares\XenAppData\XenAppStore\problemsuser\UPM_profile\AppData\Roaming\Microsoft\Outlook.
I tried renaming the folder there but still getting the same error. So where is the ICA client drawing profile information about the user when Outlook is launched?
Comment: Make sure you have the following: The folder location where the AppData (Outlook profile info) is stored, the person has Full security permissions to there. If not it can cause crazy problems.
Comment: First, it's likely not sufficient to clear the Outlook folder under AppData. There will also be settings in registry, which are not easily reset. I would start off by renaming the entire profile, to confirm this is actually related to the profile (which it likely is). Second, did you configure AppData folder redirection?
Comment: Yes, I did configure AppData folder redirection. Renaming the citrix folder did the trick, I thought one could drill down to a more granular fashion for certain streamed applications i.e Outlook but apparently not. Thanks!
Answer: Adding my comment as answer, so question can be closed or marked answered.
First, it's likely not sufficient to clear the Outlook folder under AppData. There will also be settings in registry, which are not easily reset.
I would start off by renaming the entire profile, to confirm this is actually related to the profile (which it likely is).
Second, did you configure AppData folder redirection? In that case, you may also want to rename that folder, to avoid that potentially interfering.


Bivariate time series VAR models always show serial correlation

Question: I am looking at a VAR model for two sets of time series data, the LIBOR interest rate and the Federal Funds rate for a particular time from Quand. If you install the "Quandl" package anyone can run this code.
Differencing the data does not make a difference, and they are not normally distributed as seen with a Jarque-Bera test.
My question is more conceptual. Why does this bivariate series show low $p$-values of the serial correlation test no matter what the lag for VAR?
library(Quandl)
library(fpp)
library(vars)
library(tseries)

Libor=Quandl("FRED/CADONTD156N",collapse = "weekly")

FederalFunds=Quandl("FRED/DFF",start_date="2001-01-02",
        end_date="2013-05-31",collapse="weekly")

Libor.ts=ts(Libor[,2])
# Reverse the data in the time series object.
Libor.ts[]=rev(Libor.ts)
FederalFunds.ts=ts(FederalFunds[,2])
FederalFunds.ts[]=rev(FederalFunds.ts)

combined_data <- cbind(Libor.ts,FederalFunds.ts)
ts.plot(Libor.ts,FederalFunds.ts,gpars = list(col = c("black", "red")))
lines(FederalFunds.ts,col="red")
lags <- VARselect(combined_data,type="both",lag.max = 15)
lags$selection
#Perhaps a stationarity test
# Note same results if we difference the data, which we do not
#d.Libor.ts=diff(Libor.ts)
#d.FederalFunds.ts=diff(FederalFunds.ts)
lags <- VARselect(combined_data,type="both",lag.max = 15)
lags$selection
jarque.bera.test(Libor.ts)
jarque.bera.test(FederalFunds.ts)
# So we know they are not normal.
# Now brute force a few tests
var = VAR(combined_data, p=1)
serial.test(var, lags.pt=10, type="PT.asymptotic")
var8 = VAR(combined_data,p=8)
serial.test(var8, lags.pt=10, type="PT.asymptotic")
var9 = VAR(combined_data,p=9)
serial.test(var9, lags.pt=10,type="PT.asymptotic")
var10=VAR(combined_data,p=10)
serial.test(var10, lags.pt=10, type="PT.asymptotic")
var50=VAR(combined_data,p=50)
serial.test(var50, lags.pt=50, type="PT.asymptotic")

The output of the graph is

The output of lags$selection
lags$selection
AIC(n)  HQ(n)  SC(n) FPE(n)
    11     10      9     11

I used the SC lag suggestion as 9, but then brute forced it.
No matter what the lag, from 1, all the way to 50, very small p values.
Here is the test for lag 9, supposedly the best.
The best Portmanteau test (the highest p-value is)
    Portmanteau Test (asymptotic)
data:  Residuals of VAR object var9
Chi-squared = 30.57, df = 4, p-value = 3.746e-06

Comment: Sorry for the delay.  Yes it is a very helpful answer. It seems you are saying the problem is there are strong linear patterns in the data.    I haven't accepted it yet because I'm still looking it over.  I found for example an ARIMA model did fairly well on modeling the LIBOR rate with (1,0,2).  Be curious if that made sense to you.
Comment: Eyeballing the graph it does not seem to behave like ARIMA(1,0,2). The local trends just don't fit in...
Answer: The series appear nonstationary but not of the unit-root kind. They appear to have local patterns such as prolonged almost linear increases and decreases.
If one fits an autoregressive model to either one of the series, the model will not be able to capture this kind of behaviour in a satisfactory way, and the residuals will contain traces of these local patterns observed in the data. An autoregressive model will expect the series to revert to some long-term mean. When producing fitted values, the model will thus make a series of wrong guess in the long-increase or long-decrease episodes, with mistakes being of the same sign within the episode. That will lead to autocorrelated residuals. You can "kill" autocorrelations up to lag $p$ by fitting an AR($p$) model but the autocorrelation will likely still be significant in higher lags.
If one runs a vector autoregression, one could hope for somewhat better fit, but the essence remains the same.
In my opinion, a VAR model is just not adequate for this data.