Garbled Lilypond Output

Question: I divided the notes of my score into 6 variables respectively called: \partOne, \partTwo, \partThree, \partFour, \partFive and \partSix. Each variable contains 20 measures of music. Then I call the variables in the score block. Whenever I call just one of the variables it works fine. If I call more than one, the output is completely messed up. Any ideas what's going on?

Edit: responding to a few kind suggestions here.

I used the word "part" as it's used in books and movies, not how it's used in music, so I probably should have said "sections." The point is they're successive and not simultaneous.

I'm using hacklily.org web editor on an iPad because that's all I have (no laptop or desktop).

Here is the full code I have so far:

\header {
  title = "Six Choose Four"
  composer = "Niall Mac Giolla Rua"
}

partOne = {
    c16^[ d] e_[ g] c,^[ d^] e_[ b'] c,^[ d] e_[ c']
    c,^[ d] g_[ e] c^[ d] g_[ b] c,^[ d] g_[ c]
    c,^[ d] b'_[ e,] c^[ d] b'_[ g] c,^[ d] b'_[ c]
    c,^[ d] c'_[ e,] c^[ d] c'_[ g] c,^[ d] c'_[ b] \break
    %5
    c,^[ e] d_[ g] c,^[ e] d_[ b'] c,^[ e] d_[ c']
    c,^[ e] g_[ d] c^[ e] g_[ b] c,^[ e] g_[ c]
    c,^[ e] b'_[ d,] c^[ e] b'_[ g] c,^[ e] b'_[ c]
    c,^[ e] c'_[ d,] c^[ e] c'_[ g] c,^[ e] c'_[ b] \break
    %9
    c,^[ g'] d_[ e] c^[ g'] d_[ b'] c,^[ g'] d_[ c']
    c,^[ g'] e_[ d] c^[ g'] e_[ b'] c,^[ g'] e_[ c']
    c,^[ g'] b_[ d,] c^[ g'] b_[ e,] c^[ g'] b_[ c]
    c,^[ g'] b_[ d,] c^[ g'] b_[ e,] c^[ g'] b_[ c] \break
    %13
    c,^[ b'] d,_[ e] c^[ b'] d,_[ g] c,^[ b'] d,_[ c']
    c,^[ b'] e,_[ d] c^[ b'] e,_[ g] c,^[ b'] e,_[ c']
    c,^[ b'] g_[ d] c^[ b'] g_[ e] c^[ b'] g_[ c]
    c,^[ b'] c_[ d,] c^[ b'] c_[ e,] c^[ b'] c_[ g] \break
    %17
    c,^[ c'] d,_[ e] c^[ c'] d,_[ g] c,^[ c'] d,_[ b']
    c,^[ c'] e,_[ d] c^[ c'] e,_[ g] c,^[ c'] e,_[ b']
    c,^[ c'] g_[ d] c^[ c'] g_[ e] c^[ c'] g_[ b]
    c,^[ c'] b_[ d,] c^[ c'] b_[ e,] c^[ c'] b_[ g] \break
    }

    partTwo = {
    %21
    d16^[ c] e_[ g] d^[ c^] e_[ b'] d,^[ c] e_[ c']
    d,^[ c] g'_[ e] d^[ c^] g'_[ b] d,^[ c] g'_[ c]
    d,^[ c] b'_[ e,] d^[ c^] b'_[ g] d^[ c] b'_[ c]
    d,^[ c] c'_[ e,] d^[ c^] c'_[ g] d^[ c] c'_[ b]  \break
    %25
    d,^[ e] c_[ g'] d^[ e^] c_[ b'] d,^[ e] c_[ c']
    d,^[ e] g_[ c,] d^[ e^] g_[ b] d,^[ e] g_[ c]
    d,^[ e] b'_[ c,] d^[ e^] b'_[ g] d^[ e] b'_[ c]
    d,^[ e] c'_[ c,] d^[ e^] c'_[ g] d^[ e] c'_[ b]  \break
    %29
    d,^[ g] c,_[ e] d^[ g] c,_[ b'] d,^[ g] c,_[ c']
    d,^[ g] e_[ c] d^[ g] e_[ b']  d,^[ g] e_[ c']
    d,^[ g] b_[ c,] d^[ g] b_[ e,] d^[ g] b_[ c]
    d,^[ g] c_[ c,] d^[ g] c_[ e,] d^[ g] c_[ b] \break
    %33
    d,^[ b'] c,_[ e] d^[ b'] c,_[ g'] d^[ b'] c,_[ c']
    d,^[ b'] e,_[ c] d^[ b'] e,_[ g]  d^[ b'] e,_[ c']
    d,^[ b'] g_[ c,] d^[ b'] g_[ e] d^[ b'] g_[ c]
    d,^[ b'] c_[ c,] d^[ b'] c_[ e,] d^[ b'] c_[ g] \break
    %37
    d^[ c'] c,_[ e] d^[ c'] c,_[ g'] d^[ c']c,_[ b']
    d,^[ c'] e,_[ c] d^[ c'] e,_[ g] d^[ c'] e,_[ b']
    d,^[ c'] g_[ c,] d^[ c'] g_[ e] d^[ c']  g_[ b]
    d,^[ c'] b_[ c,] d^[ c'] b_[ e,] d^[ c'] b_[ g] \break
    }

  partThree = {
    %41
    e16^[ c] d_[ g] e^[ c^] d_[ b'] e,^[ c] d_[ c']
    e,^[ c] g'_[ d] e^[ c^] g'_[ b] e,^[ c] g'_[ c]
    e,^[ c] b'_[ d,] e^[ c^] b'_[ g] e^[ c] b'_[ c]
    e,^[ c] c'_[ d,] e^[ c^] c'_[ g] e^[ c] c'_[ b]  \break
    %45
    e,^[ d] c_[ g'] e^[ d] c_[ b'] e,^[ d] c_[ c']
    e,^[ d] g_[ c,] e^[ d] g_[ b] e,^[ d] g_[ c]
    e,^[ d] b'_[ c,] d^[ e^] b'_[ g] e^[ d] b'_[ c]
    e,^[ d] c'_[ c,] e^[ d^] c'_[ g] e^[ d] c'_[ b]  \break
    %49
    e,^[ g] c,_[ d] e^[ g] c,_[ b'] e,^[ g] c,_[ c']
    e,^[ g] d_[ c] e^[ g] d_[ b']  e,^[ g] d_[ c']
    e,^[ g] b_[ c,] e^[ g] b_[ d,] e^[ g] b_[ c]
    e,^[ g] c_[ c,] e^[ g] c_[ d,] e^[ g] c_[ b] \break
    %53
    e,^[ b'] c,_[ d] e^[ b'] c,_[ g'] e^[ b'] c,_[ c']
    e,^[ b'] d,_[ c] e^[ b'] d,_[ g]  e^[ b'] d,_[ c']
    e,^[ b'] g_[ c,] e^[ b'] g_[ d] e^[ b'] g_[ c]
    e,^[ b'] c_[ c,] e^[ b'] c_[ d,] e^[ b'] c_[ g] \break
    %57
    e^[ c'] c,_[ d] e^[ c'] c,_[ g'] e^[ c']c,_[ b']
    e,^[ c'] d,_[ c] e^[ c'] d,_[ g] e^[ c'] d,_[ b']
    e,^[ c'] g_[ c,] e^[ c'] g_[ d] e^[ c']  g_[ b]
    e,^[ c'] b_[ c,] e^[ c'] b_[ d,] e^[ c'] b_[ g] \break
    }

    partFour = {
    %61
    g'16^[ c,] d_[ e] g^[ c,^] d_[ b'] g^[ c,] d_[ c']
    g^[ c,] e_[ d] g^[ c,^] e_[ b'] g^[ c,] e_[ c']
    g^[ c,] b'_[ d,] g^[ c,^] b'_[ e,] g^[ c,] b'_[ c]
    g^[ c,] c'_[ d,] g^[ c,^] c'_[ e,] g^[ c,] c'_[ b]  \break
    %65
    g^[ d] c_[ e] g^[ d] c_[ b'] g^[ d] c_[ c']
    g^[ d] e_[ c] g'^[ d] e_[ b'] g^[ d] e_[ c']
    g^[ d] b'_[ c,] g'^[ d^] b'_[ e,] g^[ d] b'_[ c]
    g^[ d] c'_[ c,] g^[ d^] c'_[ e] g^[ d] c'_[ b]  \break
    %69
    g^[ e] c_[ d] g^[ e] c_[ b'] g^[ e] c_[ c']
    g^[ e] d_[ c] g'^[ e] d_[ b']  g^[ e] d_[ c']
    g^[ e] b'_[ c,] g'^[ e] b'_[ d,] g^[ e] b'_[ c]
    g^[ e] c'_[ c,] g'^[ e] c'_[ d,] g^[ e] c'_[ b] \break
    %73
    g^[ b] c,_[ d] g^[ b] c,_[ e] g^[ b] c,_[ c']
    g^[ b] d,_[ c] g'^[ b] d,_[ e] g^[ b] d,_[ c']
    g^[ b] e,_[ c] g'^[ b] e,_[ d] g^[ b] e,_[ c']
    g^[ b] c_[ c,] g'^[ b] c_[ d,] g^[ b] c_[ e,] \break
    %77
    g^[ c] c,_[ d] g^[ c] c,_[ e] g^[ c] c,_[ b']
    g^[ c] d,_[ c] g'^[ c] d,_[ e] g^[ c] d,_[ b']
    g^[ c] e,_[ c] g'^[ c] e,_[ d] g^[ c]  e,_[ b']
    g^[ c] b_[ c,] g'^[ c] b_[ d,] g^[ c] b_[ e,] \break
    }

    partFive = {
    %81
    b'16^[ c,] d_[ e] b'^[ c,^] d_[ g] b^[ c,] d_[ c']
    b^[ c,] e_[ d] b'^[ c,^] e_[ g] b^[ c,] e_[ c']
    b^[ c,] g'_[ d] b'^[ c,^] g'_[ e] b'^[ c,] g'_[ c]
    b^[ c,] c'_[ d,] b'^[ c,^] c'_[ e,] b'^[ c,] c'_[ g]  \break
    %85
    b^[ d,] c_[ e] b'^[ d,] c_[ g'] b^[ d,] c_[ c']
    b^[ d,] e_[ c] b'^[ d,] e_[ g] b^[ d,] e_[ c']
    b^[ d,] g_[ c,] b'^[ d,^] g_[ e] b'^[ d,] g_[ c]
    b^[ d,] c'_[ c,] b'^[ d,^] c'_[ e,] b'^[ d,] c'_[ g]  \break
    %89
    b^[ e,] c_[ d] b'^[ e,] c_[ g'] b^[ e,] c_[ c']
    b^[ e,] d_[ c] b'^[ e,] d_[ g]  b^[ e,] d_[ c']
    b^[ e,] g_[ c,] b'^[ e,] g_[ d] b'^[ e,] g_[ c]
    b^[ e,] c'_[ c,] b'^[ e,] c'_[ d,] b'^[ e,] c'_[ b] \break
    %93
    b^[ g] c,_[ d] b'^[ g] c,_[ e] b'^[ g] c,_[ c']
    b^[ g] d_[ c] b'^[ g] d_[ e] b'^[ g] d_[ c']
    b^[ g] e_[ c] b'^[ g] e_[ d] b'^[ g] e_[ c']
    b^[ g] c_[ c,] b'^[ g] c_[ d,] b'^[ g] c_[ e,] \break
    %97
    b'^[ c] c,_[ d] b'^[ c] c,_[ e] b'^[ c] c,_[ g']
    b^[ c] d,_[ c] b'^[ c] d,_[ e] b'^[ c] d,_[ g]
    b^[ c] e,_[ c] b'^[ c] e,_[ d] b'^[ c]  e,_[ g]
    b^[ c] g_[ c,] b'^[ c] g_[ d] b'^[ c] g_[ e] \break
    }

    partSix = {
    %101
    c'16^[ c,] d_[ e] c'^[ c,^] d_[ g] c^[ c,] d_[ b']
    c^[ c,] e_[ d] c'^[ c,^] e_[ g] b^[ c,] e_[ b']
    c^[ c,] g'_[ d] c'^[ c,^] g'_[ e] c'^[ c,] g'_[ b]
    c^[ c,] b'_[ d,] c'^[ c,^] b'_[ e,] c'^[ c,] b'_[ g]  \break
    %105
    c^[ d,] c_[ e] c'^[ d,] c_[ g'] c^[ d,] c_[ b']
    c^[ d,] e_[ c] c'^[ d,] e_[ g] c^[ d,] e_[ b']
    c^[ d,] g_[ c,] c'^[ d,^] g_[ e] c'^[ d,] g_[ b]
    c^[ d,] b'_[ c,] c'^[ d,^] b'_[ e,] c'^[ d,] b'_[ g]  \break
    %109
    c^[ e,] c_[ d] c'^[ e,] c_[ g'] c^[ e,] c_[ b']
    c^[ e,] d_[ c] c'^[ e,] d_[ g]  c^[ e,] d_[ b']
    c^[ e,] g_[ c,] c'^[ e,] g_[ d] c'^[ e,] g_[ b]
    c^[ e,] b'_[ c,] c'^[ e,] b'_[ d,] c'^[ e,] b'_[ g] \break
    %113
    c^[ g] c,_[ d] c'^[ g] c,_[ e] c'^[ g] c,_[ b']
    c^[ g] d_[ c] c'^[ g] d_[ e] c'^[ g] d_[ b']
    c^[ g] e_[ c] c'^[ g] e_[ d] c'^[ g] e_[ b']
    c^[ g] b_[ c,] c'^[ g] b_[ d,] c'^[ g] b_[ e,] \break
    %117
    c'^[ b] c,_[ d] c'^[ b] c,_[ e] c'^[ b] c,_[ g']
    c^[ b] d,_[ c] c'^[ b] d,_[ e] c'^[ b] d,_[ g]
    c^[ b] e,_[ c] c'^[ b] e,_[ d] c'^[ b]  e,_[ g]
    c^[ b] g_[ c,] c'^[ b] g_[ d] c'^[ b] g_[ e] \break
    }

\score {

    \relative c' {
    \time 3/4

    \partOne
    % \partTwo %these calls all commented out
    % \partThree
    % \partFour
    % \partFive
    % \partSix

    }
}

  \layout { indent = 0.0 }
  \midi {}

This is what it looks like when I try calling more then one of the 6 variables:
Comment: Would you please edit the question and add the code you are compiling?
Comment: (or perhaps a version of the code that is greatly simplified, yet still exhibits the same bug)
Comment: Thanks for the second update. When I un-comment parts two–six, it seem to work just fine — but I'm not using Hacklily; I suspect this bug has something to do with the complier.
Comment: @ElementsinSpace I hadn't tried that particular combination (2-6). Just tried now, and it doesn't work in hacklily, so the problem may be their compiler or some other back end process.
Comment: By "parts two–six", I mean "two through six" i.e. all of them; I couldn't get the bug to appear at all using an offline complier.
Comment: @ElementsinSpace I guessed that's what you meant, and that's what I tried. Going over the responses, it's looking more and more like an issue with Hacklily.org Thanks again.
Answer: I copied and pasted exactly what you entered in the question. I uncommented \partTwo and here's what it spat out. With this kind of inconsistency, it's probably best to find a different online LilyPond editor.

Addendum: hovering over some of the notes that were not included references lines that are outside the scope of your code. In other words: "Find this note on line 410!" There were only 200 lines in your code. Something, somewhere, is colliding. It's like it's accidentally mixing up your piece with some piece somewhere else. Accordingly, it wouldn't surprise me if buggy code is getting silently inserted unbeknownst to you.
Answer: Using the code from https://music.stackexchange.com/a/38118 this can be abbreviated to
\version "2.20.0"

\header {
  title = "Six Choose Four"
  composer = "Niall Mac Giolla Rua"
}

#(define (perm lst r)
  (if (zero? r) '(())
   (append-map
    (lambda (x)
     (append-map
      (lambda (old) (if (member x old) '() (list (cons x old))))
      (perm lst (1- r))))
    lst)))

showperm =
#(define-music-function (parser location r notes) (index? ly:music?)
  (make-sequential-music
   (map (lambda (x) (music-clone notes 'elements (ly:music-deep-copy x)))
        (perm (ly:music-property notes 'elements) r))))

\score {
  {
    \time 3/4
    \set beamExceptions = \beamExceptions { \repeat unfold 6 { 16[ 16] } }
    <<
      \showperm 4 { c'16 d' e' g' b' c'' }
      \repeat unfold 30 { \skip 2.*4 \break }
    >>
    \bar "|."
  }
}

\layout { short-indent = 0.0 indent = 0.0 }
\midi {}

and works fine in current LilyPond.  Maybe the problem is with hacklily.org and/or the version of LilyPond it is running?  There have been LilyPond versions that had problems with forced line breaks; this abbreviated input makes it easy to take out the forced breaks and see what happens.
Comment: This is amazing. Thank you. I knew there had to way of automating things with functions and loops, just didn't know how! Unfortunately the website Hacklily.org doesn't seem able for your code, but I'm trying create a set up on my iPad starting with a linux shell emulator I downloaded. This is all new for me but, I'll look forward to trying your example out when I figure this set up. (I don't have a computer!)
Answer: Anybody's guess without example code, but if you mix six parts via plain <<…>> into a single Voice context, "messed up" might describe the results pretty well since you get only one beaming, one stemming, one tie/fingering mechanism.  Even tnough the noteheads will be at the right point of time but without proper collision avoidance.
Answer: If we stipulate that your other parts are similar to the first part (your example does not show the problem, so one has to fantasize about it), then it starts with an unqualified pitch c and ends with g a fifth above.  If you put two of those parts in \relative, the second one will end up an octave higher than the first one.
The sanest solution is to put \relative c' in the definition of every "part" variable so that it won't bounce around in its octaves depending on what precedes it.
Comment: Hi I added the full code as per your suggestion, however, as I had said, the other variables are identical in length and structure (only the pitches change). Calling any one of the variables alone works. Calling more than one results in garbles. Thank you.

Garbled Lilypond Output


Executar modal somente se existir uma chamada

Question: Estou querendo executar o modal somente se existir a chamada. Pois está demorando muito para abrir a página.
Abaixo segue o modal utilizado:

<div class="modal fade" id="m_modal<?php echo $count ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

                Produtos Licenciados

          Nº do Produto

          Validade

          Tipo

          Valor

              <?php
    $comprador = $row['cod_comprador'];
    $sqlrec = $db->prepare("SELECT pro.numero_produto, pro.validade, pro.tipo_produto, pro.valor_produto FROM prouto pro where rec.cod_comprador = '$comprador' ORDER BY pro.validade desc");
    $sqlrec->execute();   $arec = 0  ;
      while($rowrec=$sqlrec->fetch(PDO:: FETCH_ASSOC)){
        $arec++; ?>

        <? echo $rowrec['numero_produto']?>

              <?php echo date('d/m/Y', strtotime($rowrec['validade']));?>

                  <?php
              switch ($rowrec['tipo_produto']) {
                case '1':
                  echo "Avulsa";
                break;
                case '2':
                  echo "Mensal";
                break;
                }
             ?>

        R$<? echo  str_replace('.', ',', $rowrec['valor_produto'])?>

                <?php } ?>

Aqui eu chamo o Modal

<a href="javascript:;" class="btn btn-secondary m-btn m-btn--icon m-btn--icon-only" data-toggle="modal" data-target="#m_modal<?php echo $count++ ?>">

Comment: Utilize *Ajax*. Toda vez que você quiser abrir determinado *modal*, basta fazer uma requisição para uma nova página capturar, formatar e retornar o *modal* com as informações (tudo isso via JS).
Comment: São vários modais na página?
Comment: de onde vem essa variavel `$count`?
Comment: Certo. Você tem algum exemplo ?
Comment: Então. estou usando um datatable com 3 mil registro. para cada linha ele tem o botão que chama um modal com informações de uma outra tabela, que tem ligação. Ele funciona perfeitamente do modo atual. só que demora 17 segundos para abrir a página, pois está lendo também a sql desse modal. Como ela não é exibida de início, é só para aparecer os dados ao clicar no botão. Fiz alguns exemplos, mas não deu certo.
Comment: Essa variável uso dentro do **tbody** Se eu não colocar essa info, ele não apresenta os dados por linha. Ou seja, o modal vem com a mesma informação em todas as linhas.
Comment: @RobsonFreitas Na página https://cursos.alura.com.br/forum/topico-carregar-modal-com-ajax-47058 (resposta do Rodrigo Adolfo de Paula) ele postou um exemplo legal, mas você pode usar uma biblioteca caso não consiga criar a função. http://jquerymodal.com/#example-4
Comment: Certo, vou dar uma olhada.
Comment: Então, cada botão tem um modal?
Comment: Temo como eu te mandar um exemplo por link ?
Comment: Não é necessário.
Comment: http://riftec.com.br/ranking/temp.php

Na coluna de ação, o botão da esquerda.

Limitei à 5 registros. mas seria esse senário.
Answer: Pode fazer desta forma chamando um Ajax para carregar o respectivo conteúdo no conteúdo da modal.
Primeira coisa é deixar apenas 1 modal na página. Essa única modal servirá para todos os botões que forem abri-la, e deixe apenas até a div class="modal-content". O resto do corpo da modal será enviado pelo PHP na requisição do Ajax.
Modal:

Nos botões, inclua dois atributos dataset: um para o código que servirá na consulta ao banco de dados (data-codigo) e outro para identificar que tipo de informação será carregada (data-tipo), pois dependendo do tipo, o conteúdo da modal pode variar.
Os valores dos data-* você irá carregar pelo PHP, como vem fazendo. Os valores abaixo (10 e 20) são apenas para exemplo. Os "tipos" também você deve pegar pelo PHP de acordo com o tipo do botão.
Botões:
          ↓               ↓

          ↓               ↓

Script:

O script acima irá pegar todas as informações necessárias e enviar para pagina.php (use o nome que desejar) que deverá retornar o código em HTML, tal como:

          Produtos Licenciados

                    Nº do Produto

                    Validade

                    Tipo

                    Valor

        <?php
$comprador = $row['cod_comprador'];
$sqlrec = $db->prepare("SELECT pro.numero_produto, pro.validade, pro.tipo_produto, pro.valor_produto FROM prouto pro where rec.cod_comprador = '$comprador' ORDER BY pro.validade desc");
$sqlrec->execute();   $arec = 0  ;
while($rowrec=$sqlrec->fetch(PDO:: FETCH_ASSOC)){
  $arec++; ?>

              <? echo $rowrec['numero_produto']?>

        <?php echo date('d/m/Y', strtotime($rowrec['validade']));?>

            <?php
        switch ($rowrec['tipo_produto']) {
          case '1':
            echo "Avulsa";
          break;
          case '2':
            echo "Mensal";
          break;
          }
       ?>

              R$<? echo  str_replace('.', ',', $rowrec['valor_produto'])?>

          <?php } ?>

O HTML acima é apenas a parte interna da div class="modal-content", que é o HTML que interessa.
No lugar de $comprador = $row['cod_comprador']; você deverá usar o valor enviado pelo Ajax, por exemplo, $comprador = $_POST['codigo'];.
Na página PHP pagina.php você deverá fazer um if com o valor tipo enviado pelo Ajax ($_POST['tipo']) para saber qual a estrutura de HTML para cada caso.


Finding a rare biased coin from an infinite set

Question: I'm trying to develop an algorithm for finding biased coins. The basic problem formulation is this:

There are an infinite number of coins
Some proportion $t$ of the coins is biased (this number is known)
All biased coins have the same probability $p_b$ of coming up heads (this number is also known)
All other coins are fair
Biased coins are otherwise indistinguishable from fair ones

The task is to find one biased coin, with some confidence, using the fewest number of coin flips.
I know the basic solution to a related problem, i.e. determining whether a single coin is biased. Following the formulation in https://en.wikipedia.org/wiki/Checking_whether_a_coin_is_fair, I can set my desired maximum error $E$ to be equal to $|p_b - 0.5|$ and use the equation $n = \frac{Z^2}{4E^2}$ to get the number of coin tosses $n$ required to determine whether the coin is indeed fair using a given $Z$ value.
However, I'm curious how the method might change given my formulation, where there are multiple coins and a known proportion are biased. A brute force algorithm, I suppose, would be to select a coin, flip it $n$ times, select another coin, flip it $n$ times, etc. until a biased one is found. But this feels sub-optimal.
Is it possible, for instance, to abandon a coin before $n$ flips is reached based on some criteria, i.e. using the evidence collected so far to judge whether it is worthwhile to keep flipping that coin or move on to another? It seems like the value of $t$, particularly if it is low, should be a useful prior that I can leverage.
I'm also concerned that if I test multiple coins, I am at risk of inadvertently finding significance where there is none.
Comment: You can only work with finite samples from the infinite set. With $2^n$ coins flipped $2^n$ times in parallel, you may have instances of coins, amongst the $2^n$ sample of parallel flips, that land up to all heads or all tails without being biased.  If the density of biased coins in the infinite set is rarer than $1$ in $2^n$ all you are doing is studying the noise floor in your data. The number of biased coins needed in your sample before you can detect them using some chosen statistical significance test, is going to depend on how biased they are, which you don't know in advance.
Comment: I do know the density of biased coins in the infinite set, as well as the bias itself, ahead of time.
Answer:
Is it possible, for instance, to abandon a coin before n flips is reached based on some criteria, i.e. using the evidence collected so far to judge whether it is worthwhile to keep flipping that coin or move on to another? It seems like the value of t, particularly if it is low, should be a useful prior that I can leverage.

A Bayesian approach might go like this, for a single coin ...
Let $\widetilde p$ be the unknown probability of success, with prior given by
$P(\widetilde p =p_b)=t$ and $P(\widetilde p =1/2)=1-t$. Then the posterior, after $n$ conditionally i.i.d. tosses $X_1,...X_n$, with $k$ being the number of successes, is given by
$$\begin{align}
P(\widetilde p =p_B\mid X_1=x_1,...X_n=x_n)
&= {P(X_1=x_1,...X_n=x_n\mid \widetilde p =p_B)\cdot P(\widetilde p =p_B)\over P(X_1=x_1,...X_n=x_n)}\\[3mm]
&= {p_B^k(1-p_B)^{n-k}\cdot t\over P(X_1=x_1,...X_n=x_n)}\\ \\
\end{align}$$
and
$$\begin{align}P(\widetilde p =1/2\mid X_1=x_1,...X_n=x_n)
&= {P(X_1=x_1,...X_n=x_n\mid \widetilde p =1/2)\cdot P(\widetilde p =1/2)\over P(X_1=x_1,...X_n=x_n)}\\[3mm]
&= {(1/2)^n\cdot (1-t)\over P(X_1=x_1,...X_n=x_n)}
\end{align}$$
Then we could, for example, use the posterior odds-ratio,
$$R:={P(\widetilde p =p_B\mid X_1=x_1,...X_n=x_n) \over P(\widetilde p =1/2\mid X_1=x_1,...X_n=x_n)}={p_b^k(1-p_b)^{n-k}\over(1/2)^n }{t\over 1-t}$$
with a decision rule like this:
$$\ \begin{cases}R>r &\implies \text{decide "biased"}\\
R<1/r &\implies \text{decide "unbiased"}
\end{cases}
$$
... tossing until one alternative becomes sufficiently more probable than the other, as judged by some threshold ratio value $r$. To guarantee a bound on the number of tosses, one would probably want to set some maximum number $n_{max}$, such that if $n_{max}$ were ever reached without a decision being made, then a default rule would be applied to stop and decide in favor of whichever alternative had the higher posterior probability at that time. (A hybrid Bayesian-frequentist approach could also set $n_{max}$ based on the frequentist estimation value you quoted.)

EDIT:
Note that if we let $P_n := P(\widetilde p =p_B\mid X_1=x_1,...X_n=x_n)$ and subscript the corresponding $R$-value, then $R_n$ and $P_n$ are in 1-1 correspondence, each being an increasing function of the other:
$$P_n = {R_n\over R_n+1},\quad R_n = {P_n\over 1-P_n}.$$
Consequently the decision criteria can be written equivalently in terms of either quantity:
$$\text{using $(r_{lo}, r_{hi})$:}\quad\quad\begin{cases}R_n>r_{hi}\\[6mm] R_n<r_{lo}\end{cases}\iff\begin{cases}P_n>{r_{hi}\over r_{hi}+1}\\[3mm] P_n<{r_{lo}\over r_{lo}+1}\end{cases} $$
and
$$\text{using $(p_{lo}, p_{hi})$:}\quad\quad\begin{cases}P_n>p_{hi}\\[6mm] P_n<p_{lo}\end{cases}\iff \begin{cases}R_n>{p_{hi}\over 1-p_{lo}}\\[3mm] P_n<{p_{lo}\over 1-p_{lo}}\end{cases}
$$
I've written $lo$ and $hi$ quantities in case you want to explore setting the two criteria independently of one another, instead of my example above using $(r_{lo},r_{hi})=({1\over r}, r)\iff (p_{lo},p_{hi})=({1\over r+1},{r\over r+1})$. (E.g., @quasi's answer uses $(p_{lo},p_{hi})=(t, a)\iff (r_{lo}, r_{hi})=({t\over 1-t},{a\over 1-a})$ seeking to minimize the expected total number of flips required to decide that a biased coin has been found.)
Comment: This is very helpful, thank you. I had a feeling Mr. Bayes would make an appearance.
Comment: @FowlerA  You're welcome.  NB: I had originially written $P(X_1=x_1,...X_n=x_n\mid \widetilde p =p_B)$ $=\binom{n}{k}p_B^k(1-p_B)^{n-k}$, but the binomial coefficient should not be there. (Now corrected; the posterior is unaffected by this.)
Answer: I'll interpret the problem this way . . .

A bucket of coins is such that

Some coins are biased, the rest are fair, but the coins are physically indistinguishable.$\\[4pt]$
The fraction of coins which are biased is equal to $t$, with $0 < t < 1$, and where the value of $t$ is known.$\\[4pt]$
For each of the biased coins, the probability of heads is $p$, with
$0 < p < 1$ and $\;p\ne{\large{\frac{1}{2}}}$, and where the value of $p$ is known.

Fix an acceptance threshhold $a$, with $0 < a < 1$.

Initialize a flip counter to zero.

A game is played as follows . . .

Selecting a coin at random from the bucket, you can flip it repeatedly until you either

Decide to reject the coin, putting it back in the bucket, then starting over, but not resetting the flip count back to zero.$\\[4pt]$
Accept the coin, ending the game, and declaring that, based on the results, the conditional probability that the coin is biased is at least equal to $a$.$\\[4pt]$

The objective is to choose a strategy which minimizes the expected flip count.

Such a strategy can be described as follows . . .

Select a coin at random from the bucket.$\\[4pt]$
After each flip of the selected coin, compute, based on the results so far, the conditional probability, $b$ say, that the coin is biased.$\\[4pt]$
If $b\ge a$, accept the coin, else if $b < t$, reject the coin.

As a numerical example, for the values
$$
t=\frac{1}{4},\;\;\;\;p=\frac{3}{4},\;\;\;\;a=\frac{9}{10}
$$
the above strategy, based on a Maple simulation (shown below), yields an expected flip count of about $42$.


How do I set a row as x axis in matplotlib bar chart?

Question: I want to have the x axis as the years, the y axis as the number of crime and i am looking to do this for each crime.
Any help would be much appreciated.
Comment: Please don't include data, code, error messages as pictures, post them directly here on SO. You should also read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Comment: Do you need a barplot with years on X-axis and for each year total number of crimes happened? Or I've not understood it correctly?
Comment: @dataLeo yeah thats correct, sorry im new to this and actually have no idea where to start
Comment: Totally agreed with @Mr.T However as a beginner it's good to learn by doing mistakes ;)
Answer: I've included the xticks as years and yaxis as total count of crimes which is present in your first row. Have a look on this and tell me what else you need.
<code>import pandas as pd
import matplotlib.pyplot as plt

# Creating a dummy dataframe
df = pd.DataFrame({'Offense':['Total violence', 'Attempted Murder', 'Harrasment'],
                   '01/2018':[23, 21, 2],
                  '05/2018':[140, 80, 60]})
df
#   01/2018 05/2018 Offense
# 0 23      140     Total violence
# 1 21      80      Attempted Murder
# 2 2       60      Harassment

plt.bar(np.arange(2), df.iloc[0,:2])
plt.xticks(np.arange(2), df.columns[:2])
plt.show()
</code>
Comment: Im trying to do this but having problems with 'np.arange(2)' im trying to understand what it does here
Comment: `np.arange(2)` gives you a sequence of 2 numbers [0, 1]. Consider forming a sequence equal to number of bars you need to plot. I suggest you better study basics of `matplotlib` first. Refer here for good understanding of any of the common python packages https://aivic.github.io/tutorial/Python-important-libraries/ Also, you can upvote the answer if it helped you ;)


How to access domain properties from a controller in Grails?

Question: I have the following Grails domain class:
class Product {
    String name
    Float basePrice
    Category category
    String image = "default.jpg"

    static constraints = {
        name(size:3..25, blank:false)
        basePrice(scale:2, nullable:false)
        category(inList:Category.list(), nullable:false)
        image(blank:false)
    }
}

From a controller, I want to get the default value for the image property (in this case "default.jpg"). Something like this:
def productInstance = new Product(params)
productInstance.image = getProductPicturePath() ?: Product().image

getProductPicturePath returns an image path, but in case no image was submitted, the controller shall replace the null value with the default. While I could certainly write something like this:
productInstance.image = getProductPicturePath() ?: "default.jpg"

It's certainly not very DRY, and I would prefer to keep that default value in one place. How can I achieve this?
Answer: The obvious solution is to declare it as a constant and then refer to it.
class Product {
    static DEFAULT_IMAGE = "default.jpg"
    String name
    Float basePrice
    Category category
    String image = DEFAULT_IMAGE

    static constraints = {
        name(size:3..25, blank:false)
        basePrice(scale:2, nullable:false)
        category(inList:Category.list(), nullable:false)
        image(blank:false)
    }
}

productInstance.image = getProductPicturePath() ?: Product.DEFAULT_IMAGE

Even better, make getProductPicturePath() return the default value.
Answer: If there is no image key in params
def productInstance = new Product(params)

will skip this property and leave the default value defined in the domain class. So, assuming that your params doesn't contain an image key, the simplest way would be to skip the assignment of the image property at all for those products that have no image:
def imagePath = getProductPicturePath()
if(imagePath) {
    productInstance.image = imagePath
}

Comment: I was not aware of that. My params contains an image key, it comes from a upload form with other fields and the user may or may not upload an image file.


Do we unconsciously favour one eye when we sight-read?

Question: If you were to make a musician wear an eye patch over one of their eyes as they sight-read a piece for the very first time, would you expect their accuracy to be different depending on which eye was covered? Would the accuracy be better still if both eyes were uncovered (assuming that vision quality is the same for both eyes)? If there were differences, how would you explain them?
Comment: The notion of "left brain vs right brain" is a relic of outdated understandings of the brain (https://www.healthline.com/health/left-brain-vs-right-brain), and music frequently gets pulled into its pseudoscientific morass ("Do left- or right-brained people make better musicians?"). I've never heard the idea that one could "access" one hemisphere or the other simply by looking out of one eye, but that sounds even more imaginary. What *is* true is that you can't sight-read what you can't see, so whatever hinders your visual acuity will hinder your sight-reading. Vote to close, since...
Comment: This question doesn't make any sense to me; some people are left-eye dominant, and others are right-eye dominant. Are you interested in what happens when the dominant eye is covered? Is this really a question for an opthalmologist?
Comment: I strongly suspect that left- or right-**eyed**-ness will quickly swamp any left- or right-brained tendency when your exercise is performed. My right-eyed-ness is so strong that I was treated for lazy eye when I was 5-6, and even to this day, I can catch my left eye wandering badly if I opt to go double-vision in the mirror, and I see a substantial shift in my image in the mirror if I cover my right eye. The musician just might be disoriented by the point of view of the non-dominant eye, or find the sheet music objectively harder to read with it given the same head position (e.g. tilts right).
Comment: The idea of "left vs right brain" is not true, but even if it were, the visual pathway has part called optic chiasma that splits the left part of field of view from both eyes to right hemisphere and vice versa. To see the sheet music with one hemisphere you'd need to look past it so that you see it out of the corner of your eyes, and peripheral vision isn't good enough for reading.
Comment: Thank you user45266 I've reworded the question, removing the brain reference.
Comment: Sight reading is more pattern recognition, like normal reading. It is not an alignment procedure like shooting where you cannot two eyes with one sight, hence favouring one. Do you experience troubles reading work one eye?
Comment: ... Vote to close, since this is a question about either optometry or neuroscience, with hints at a false assumption.
Comment: BTW, editing a question to a different one after it has been answered is not cool, even if the original one didn't make sense. Just ask a new one.
Comment: @ojs I was going to say that OP should roll back my edit if that is not what they meant to ask. I made the edit because I believed the question seemed to otherwise be good but the title seemed like it was just a badly-chosen phrasing of "which eye". We can roll it back if needed, but I would say we should check to make sure the question is on-topic if it asks about neuroscience. It just seemed to me like the "right-left-brained" stuff in the title was entirely tangential to the "which eye" question, so I thought I was clearing it up.
Comment: I'm with @exnihilo on this - anyone who's ever tested themselves for left- or right-eyed-ness knows that they **consciously** favour one eye when they sight-read. If they're anything like me, a book for children brought up the test.
Comment: "unconsciously favor..." - something about eye dominance, and "wear an eye patch" are really two very different scenarios. One is basic question, the other describes an experiment.
Answer: This answer concerns itself only with "reading" in the sense of symbol recognition and does not address the auditory, tactile, spatial, or motor aspects of music reading.

In Shentong Wang and Mark Agius's "The Neuroscience of Music: A Review and Summary", music-reading is shown to be a highly complex and significantly bilateral activity. Of particular important for the question at hand are the fusiform gyrus (Rhythm reading) and superior parietal cortex (Melody reading) (Stewart 2005). See especially Table 1 in the linked article. The images below show the bilateral nature of these structures.
An earlier study of (language) reading found no difference between monocular and binocular speed. See Knehr, C. A. 1941. "The effects of monocular vision on measures of reading efficiency and perceptual span". Journal of Experimental Psychology 29/2: 133–54.
Fusiform gyrus (shown in red)

(Image source: Wikipedia)
Superior parietal cortex (lobule) (shown in blue)

(Image Source)

Stewart L. 2005. "A neurocognitive approach to music reading."
Ann N Y Acad Sci 1060:377-86.


How to prove $|z_1-z_2| \geq |z_1|-|z_2|$ in other way than this?

Question: How to prove $|z_1-z_2| \geq |z_1|-|z_2|$ in other way than this? I mean I tried to find on the internet but could not find. I ask for more straighforward way than the proof that is presented for item 3.
Comment: @AdamRubinson: when $z_1,z_2\in \Bbb C$, there is no such thing as $z_1\gt z_2$ when their imaginary parts are non-zero.
Comment: the quickest way I know to solve this is to consider the two cases z1 < z2 and z2< z1 seperately. Edit: and when z2=z1 it's obvious
Comment: whoops, didn't see this was in complex analysis. not very observant of me...
Answer: Use the triangle inequality on $|z_1| = |(z_1 - z_2) + (z_2)|$.
Comment: @CaptainGiraffe: The triangle inequality involves three values. The parentheses are there to make clear what those three values are supposed to be (namely $z_1$, $z_1 - z_2$, and $z_2$). From a mathematical standpoint, m. k.'s answer is equivalent to "Use the triangle inequality on $|z_1|$"; but that would have been a confusing and almost-useless answer, whereas this one is clear and useful.
Comment: I think this is the most straightforward proof we could get
Comment: My cursory glance makes me curious what difference the parentheses makes?
Comment: @ruakh Thank you. Your well written comment helped my intuition get back to normal.
Answer: Let $z_1=r_1(\cos A+i\sin A)$  and $z_2=r_2(\cos B+i\sin B)$
So, $|z_1|=r_1$ and $|z_2|=r_2$
$|z_1-z_2|$
$=\sqrt{(r_1\cos A-r_2\cos B)^2+(r_1\sin A-r_2\sin B)^2}$
$=\sqrt{r_1^2+r_2^2-2r_1r_2\cos(A-B)}$
$≥\sqrt{r_1^2+r_2^2-2r_1r_2}$ as $\cos(A-B)≤1$
$=r_1-r_2$
So, $|z_1-z_2|≥|z_1|-|z_2|$, the equality occurs when  $\cos(A-B)=1$ i.e., when $A=B$
Answer: You can use multiplication by conjugate.
$|Z_1 + Z_2 |^2 = (Z_1 + Z_2)\overline{(Z_1 + Z_2)}$.
By expansion you will get
$| Z_1 + Z_2 |^2 = |Z_1|^2 + |Z_2|^2$ + 2 Real part of $(Z_1 \overline{Z_2})$ $\leq (|Z_1| + |Z_2|)^2$.
Then use this result, and prove remaining.
Comment: $2$ Real part of $(Z_1 \bar{Z_2})$ is not so but I got from $|Z_1 +Z_2 |^2 =(Z_1 +Z_2 )\overline{(Z_1 +Z_2 )}=|Z_1 |^2 +|Z_2 |^2 - ix_1y_2 + iy_1x_2$, where $Z_1=x_1+iy_1 $ and $Z_2=x_2+iy_2 $?
Comment: Look at Z1Z2* + Z2Z1* in expansion on right side; where  Z1Z2* = (Z1*Z2)* so, both are conjugates, what happens if you add 2 conjugates? imaginary parts will get cancelled, only real parts will remain.
Comment: No. I forgot to include $Z_1 \overline{Z_2}$ to it.
Comment: It could be said also $2$ Real part of $(Z_2 \overline{Z_1})$ instead of $2$ Real part of $(Z_1 \overline{Z_2})$
Comment: Yes, take Z3 = Z2Z1* and Z3*; see it in Z3 = x + iy form, Re(Z3) = Re(Z3*) = x.
Comment: I choose this answer, because this answer I understood in the time that I have on this problem.


Inherit sublayouts created inside sitecore CMS in Visual Studio 2012

Question: Is there any way I can use the layouts and sublayouts I have created inside the Sitecore CMS, in Visual Studio to write the c# codes assuming that I have Sitecore Rocks plug in installed on my VS? Also while setting a new connection I am not able to get physical access of my Sitecore instance.
I checked for the same over the internet but could not find any reference. Help required.
Thanking everyone in advance
Comment: I don't think this is possible, as you need to compile your code behind code.
Comment: Created through developer center I assume?
Answer: solved the issue!!  Brad Christie assumed it right!! I created it using developer center without any dependency from VS. you can create a sublayout from developer center which gives you an option to include .cs page too if you would like to and you can write your codes directly in your .cs page.


Scanner NoSuchElementException when calling .next() method

Question: In Java, I'm getting this Exception:
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at com.reading.text.Activity3.readFile(Activity3.java:22)
    at com.reading.text.Activity3.main(Activity3.java:10)

From this Java code:
public static void main(String args[])
{
    readFile("C:/Users/forsakendoll/Desktop/boom.txt");
}

public static void readFile(String path) {
    Scanner file = null;
    try {
        file = new Scanner(new File (path));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        while (file.hasNext()) {
            for(int counter = 0 ; counter < file.next().length(); counter ++) {
                System.out.println(file.next().charAt(counter));
            }
        }
    }
}

The Exception is thrown on

System.out.println(file.next().charAt(counter));

What does the Exception mean?
Comment: In addition to the below answers, you shouldn't have the code to read the file in the finally block, currently even if the file is not found the program will still attempt to read it. You should move code from the finally inside the try block.
Comment: @BruteForce thanks really bro. I did really stupid. I didn't realize that.
Answer: You are calling .next() twice on every iteration of the loop, so when you are near the end, you jump off the end of the list and the compilter tells you there is nothing there.
Instead of this:
for(int counter = 0 ; counter < file.next().length(); counter ++) {
    System.out.println(`file.next()`.charAt(counter));
}

Do this instead:
String temp = file.next();
for(int counter = 0 ; counter < next.length(); counter ++) {
    System.out.println(temp .charAt(counter));
}

SEE HERE
Comment: @user1708134 `file.next().length()`
Comment: Hey bro how come i call the `.next()` twice?
Answer: Don't call next() so much times! It actually go to the next element when you call it. If you need to use it more than once, put it inside a variable and use it.
        String next = file.next();
        for(int counter = 0 ; counter < next.length(); counter ++) {
            System.out.println(next.charAt(counter));
        }

Answer: The Scanner.next() method will move the internal iterator along one. Your code should be:
public static void readFile(String path) {
    Scanner file = null;
    try {
        file = new Scanner(new File (path));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        while (file.hasNext()) {
            String next = file.next();
            for(int counter = 0 ; counter < next.length(); counter ++) {
                System.out.println(next.charAt(counter));
            }
        }
    }
}

Comment: Meant to include the doc link: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next() Although the doc doesn't specifically mention this behaviour


C++ Automatic constructor call on template operator overload?

Question: I have the following in my header file:
template<typename T>
class rational {
private:
    T num;
    T denom;
    T gcd(T x, T y);

public:
    rational(T num, T denom);
    rational(T wholeNumber);

    template<typename U>
    friend inline rational operator *(const rational &lhs, const rational &rhs);
}

template<typename T>
rational<T>::rational(T whole) {
    this->num = whole;
    this->denom = 1;
}

template<typename T>
rational<T> operator *(const rational<T> &lhs, const rational<T> &rhs) {
    return rational<T>(lhs.num * rhs.num, lhs.denom * rhs.denom);
}

And the following in my main:
rational<int> x(6), y(2);
rational<int> product = y * x;   // this works
rational<int> product2 = 2 * x;  // this doesn't

The first product works, but the second one gives me "error: no match for 'operator*' in '2 * x'". Why? Since there is a constructor available that takes only the 2 as an argument, shouldn't that be automatically called? If not, how else would I overload the operator to have both of these work?
Thanks.
Comment: The reason why the conversion does not work, as well as a fix, is explained in [this answer](http://stackoverflow.com/a/3888237/160206).
Comment: possible duplicate of [Implicit conversion not happening](http://stackoverflow.com/questions/3888082/implicit-conversion-not-happening)
Answer: I'm not sure why the compiler will not invoke the single-argument constructor implicitly on 2 in order to produce a rational, but my guess is that the inference mechanism is simply broken when templates are involved.
One workaround (if no one knows how to fix the implicit constructor issue) is to define an additional multiply operators like thus:
template<typename T>
rational<T> operator *(const T &lhs, const rational<T> &rhs) {
    return rational<T>(lhs * rhs.num, rhs.denom);
}
template<typename T>
rational<T> operator *(const rational<T> &lhs, const T &rhs) {
    return rational<T>(lhs.num * rhs, lhs.denom);
}

This will also perform better, if you are writing high-performance code using rationals in an inner loop somewhere.
Comment: Thanks. I also had this in mind as a fallback, but I really hope there's a way to avoid this and rely on the constructor. Otherwise I have to do this for ALL the binary operators, which feels unnecessarily verbose.
Comment: @Foober Stackoverflow is a QA site. As such, answers are encouraged over opinions. 'my guess' and 'is simply broken' aren't really constructive. C++ is a welldefined language, and you'd do better to just explain how it works.
Comment: Part of the question was "how else would I overload the operator to have both of these work?" and I believe I have provided a working answer to that one.  Sorry to bother.
Comment: @sehe `Stackoverflow is a QA site.`  Does that mean we get to ask questions of the form:  "Here is my code.  Find the bugs in it for me"
Comment: @SamIam I don't know. I've seen the strangest things. For example, I've been asked completely inane rhetorical questions, out of the blue, in comments on ancient answers by others. Fortunately, like you, I have the option to completely ignore this at my leisure. Ah. Freedom!
Answer: 2 * x;

is analogical equivalent to calling of,
int::operator*(const rantional<int>&)

2 is an int and it doesn't have operator * overloaded for const rational<int>&; thus you get compiler errors.
The correct way is to have:
rational<int> product2 = rational<int>(2) * x; // ok

Comment: I understand that, but I thought that the compiler should be able to infer the constructor rational(int) from the argument. My question is more about why that inference isn't happening.
Comment: @DavidThielke, I have already explained the reason in my answer. Such implicit conversion don't happen.


Função do suspend no Firebird

Question: Qual a função do suspend numa procedure no Firebird?
Answer: Ao que me parece, com uma pesquisa bem rápida no Google, o suspend suspende a execução de uma procedure que está trazendo uma tabela de resultados (result set) até que quem a está chamado peça para trazer o resto dos resultados.
Fontes:

"Only for SELECT procedures which return tables: Waits for the client to request the next line. Returns the next line to the client."
  http://www.destructor.de/firebird/storedproc.htm
"O Comando SUSPEND informa a Stored Procedure para suspender a execução até que seja solicitado dados pelo cliente."
  http://www.devmedia.com.br/while-e-for-no-firebird/16734
Answer: Em uma stored procedure, a função do suspend é enviar uma linha de resultados atuais dos parâmetros de saída (returns). A cada suspend, uma nova linha é enviada como resultado.
Answer: A função do suspend numa SP (Stored Procedure) é suspender o código naquela linha anterior ao suspend e imprimir na tela o resultado daquele código, basicamente o mesmo que dizer "imprima". Em uma alusão a programação básica (C++) seria o equivalente ao printf.

Função do suspend no Firebird


Ray intersecting a quad mesh

Question: I am trying to solve the math behind rendering a quad-mesh surface. MatLab for instance can take a regularly spaced (x,y) grid with arbitrary third-dimension (z) values, treat each four neighbouring coordinates as 3d quadrilaterals, and render each of them as a facet of the surface.

I'm trying to do this with ray tracing which would be easy if the quads were planar (all corners on the same plane), but since every coordinate can be arbitrary most quads will likely not be on the same plane, a so-called "skew-quadrilateral" (you can see how most quads in the above MatLab image "twist and turn"). Does anyone know the steps or pseudocode to intersect a ray with a skew quadrilateral, I've tried looking around but couldn't find it?
I don't even know if such a thing could be possible since you could have three corners of a quadrilateral with z-coordinates of 0 and suddenly the last corner with a very high z-coordinate, implying some sort of bending or breaking of the surface. I mean what would the following grid even look like, perhaps four quadrilaterals that start on the same level and bend towards a high point in the middle?
<code>(0,0,0) (0,0,0) (0,0,0)
(0,0,0) (0,0,5) (0,0,0)   ===>    ?
(0,0,0) (0,0,0) (0,0,0)
</code>
I suppose the main difference could be that MatLab does not use ray tracing to render each quadrilateral, but rather some type of 3d to 2d reprojection. If so, does anyone know the usual non-raytracing way of rendering a quad mesh surface?
On the other hand I have read somewhere that quadrilateral surface meshes are indeed used in 3d movie or game developing where ray tracing is certainly used, so it should be possible.
Links
Here are some relevant quotes and links that describe how MatLab treats the surface:
http://se.mathworks.com/help/matlab/visualize/representing-a-matrix-as-a-surface.html
"The plot is formed by joining adjacent points with straight lines."
"Mesh plots are wire-frame surfaces that color only the lines connecting the defining points. Surface plots display both the connecting lines and the faces of the surface in color."
"...generates a colored, faceted view of the surface and displays it in a 3-D view. Ordinarily, the facets are quadrilaterals, each of which is a constant color..."
http://se.mathworks.com/help/matlab/ref/surf.html
"Each point in the rectangular grid can be thought of as connected to its four nearest neighbors."
"This defines a mesh of quadrilaterals or a quad-mesh."
Comment: Most commonly in the same direction. Yes, it does look bad, but the idea is to use so many triangles you do not notice. Matlab does not do raytracing, it just draws polygons (with a surface normal calculated as the average of vertex normals, or as the average of the triangle normals if the quad were to split into triangles, I think) with flat shading. You could split each quad into four triangles, computing a new center vertex (at center of the four quad vertices), if you dislike the quads-to-two-triangles look.
Comment: Typically in raytracing, quads (as well as other surface meshes like [Bézier patches](https://en.wikipedia.org/wiki/B%C3%A9zier_surface) are converted to triangular meshes first. You can compute the intersection between a ray and any quadrilateral, but the equation is nasty (slow to calculate), whereas the intersection between [a ray and a triangle](http://www.lighthouse3d.com/tutorials/maths/ray-triangle-intersection/) is easy. Parametric patches like [Bézier surfaces](https://en.wikipedia.org/wiki/B%C3%A9zier_surface) are even worse.
Comment: When your world has millions of triangles, there are many options how to limit to intersection tests to a smaller set of triangles. Typically, you "bound" each triangle by a box or a sphere (to minimize the effort needed to discard surely-not-intersecting triangles), and sort these spatially. There are many ways to do that, but [octrees](https://en.wikipedia.org/wiki/Octree), [binary space partitioning](https://en.wikipedia.org/wiki/Binary_space_partitioning), and nested bounding volumes are the most typical approaches taken.
Comment: Thats also what i heard, so i also made a version that divides each four neighbouring points into two triangles and intersects the triangles as you said, but its sort of arbitrary in which direction the quad is split. How are the quads typically converted to triangles? Also, the results look like quads broken into two triangles instead of the preferred whole quads shown in the matlab example image, and matlab claim they use a quadmesh instead of a triangle mesh, so im sure there must be something im missing here. I will optimize with spatial indexing in the end.
Answer: In practice, raytracers tend to decompose surfaces into triangular meshes first, because the math needed is so much simpler.
However, you asked how to calculate the intersection between a line and a quadrilateral in 3D, so here goes.
Let's define your ray using an unit vector $\hat{n}$ (unit referring to unit length, $\lvert\hat{n}\rvert=1$) that passes through some point $\vec{p}_0$,
$$\vec{p}_{RAY}(t) = \vec{p}_0 + t\,\hat{n}$$
The quadrilateral is a bit more complicated. Let's say the four corners are $\vec{p}_1$, $\vec{p}_2$, $\vec{p}_3$, and $\vec{p}_1$, with $\vec{p}_1$ and $\vec{p}_4$ diagonally across from each others. We can trace the surface using two variables, $0 \le u, v \le 1$, where $u=0,v=0$ refers to $\vec{p}_1$, $u=1,v=0$ to $\vec{p}_2$, $u=0,v=1$ to $\vec{p}_3$, and $u=1,v=1$ to $\vec{p}_4$, using bilinear interpolation of the coordinates:
$$\vec{p}_{QUAD}(u,v) = \left ( \vec{p}_1 (1-u) + u \vec{p}_2 \right ) (1-v) + v \left ( \vec{p}_3 (1-u) + u \vec{p}_4 \right )$$
which is, after rearranging the terms, the same as
$$\vec{p}_{QUAD}(u,v) = \vec{p}_1 + u \; v \; ( \vec{p}_4 - \vec{p}_3 - \vec{p}_2 + \vec{p}_1 ) + u \; ( \vec{p}_2 - \vec{p}_1 ) + v \; ( \vec{p}_3 - \vec{p}_1 )$$
The intersection is, of course,
$$\vec{p}_{RAY}(t) = \vec{p}_{QUAD}(u,v)$$
In three dimensions, that is actually three equations with three unknowns,
$$\begin{cases}
x_0 + t n_x = x_1 + u \; v \; ( x_4 - x_3 - x_2 + x_1 ) + u \; ( x_2 - x_1 ) + v \; ( x_3 - x_1 ) \\
y_0 + t n_y = y_1 + u \; v \; ( y_4 - y_3 - y_2 + y_1 ) + u \; ( y_2 - y_1 ) + v \; ( y_3 - y_1 ) \\
z_0 + t n_z = z_1 + u \; v \; ( z_4 - z_3 - z_2 + z_1 ) + u \; ( z_2 - z_1 ) + v \; ( z_3 - z_1 )
\end{cases}$$
This can be solved, but the solution contains dozens of terms, and is therefore terribly slow to compute. (I asked Maple for the exact solution. There are two (i.e., $(t_1,u_1,v_1)$ and $(t_2,u_2,v_2)$, but as they don't fit in one screenful, I decided they are way too long to reproduce here.)
Biquadratic and bicubic Bézier surfaces can be solved the exact same way, it's just that there are more terms (up to $u^3$ and $v^3$, and 9 (biquadratic) 16 (bicubic) coordinates per dimension), and thus the result is even more complicated and slow to compute.
Comment: Makes sense now. I guess i was simply asking the wrong question, based on your demonstration that calculating the intersection with a skew quad is so expensive/complicated.
Answer: There are many questions, here. I'll take stab at a few of them.
The easiest way to render a set of triangles is a z-buffer algorithm. You paint each triangle into a pixel array, and you keep track of z-depth at each pixel. Pixels that are in front over-write pixels that are behind. Most graphics packages (like OpenGL or DirectX) will do this for you; all you have to do is give them the list of triangles.
Another option is the so-called "painter's algorithm". You sort the triangles by z-depth, and then paint them in order. Again, the front triangles over-write the back ones.
Ray-tracing is typically the slowest algorithm, and most people don't use it unless they want some very sophisticated graphical effects, like inter-object reflection, or refraction through a translucent material. Ray tracing is not typically used in games. It's used in movie animation, where image quality is more important than speed of computation.
How to break a quadrilateral into a triangle: there are two choices. Choose the one that produces the least deviation between the triangles and the original quad.
Intersecting  a ray with a "skew" quadrilateral. The quadrilateral is actually a hyperbolic paraboloid, which is a quadric surface (of degree 2). So, in general, any ray will intersect the quad in two places. The points of intersection can be found by solving a quadratic equation where the variable is the parameter value on the ray. That's what's described in the other answer. I'm surprised that it's so complicated. I would expect that you can eliminate the surface parameter values, leaving just a quadratic in the ray parameter. But, I haven't tried to do this, so maybe it's harder than I think.
I think decomposing into triangles is the right approach. If you want the graph to look more smooth and less "tesselated", you can vary the shade across each triangle. Instead of the color being constant on the triangle, you can linearly vary the color (Gouraud shading) or linearly vary the surface normal (Phong shading). Or if you want a "quad" appearance as opposed to a "triangulated" appearance, just make sure you use the same color to paint the two triangles that came from one original quad.
Comment: I think that was what i was missing. I thought raytracing was the only way and didnt know about the z buffer algorithm. So was then able to know what to search for, and found eg this great tutorial: http://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation

Ray intersecting a quad mesh


How can you make an HTML link?

Question: I need a link with another render array around it. More specifically I need a link around an image.
In the D7 days I'd just use a render array of type link and then set HTML to true and set the text as the image.
I was hoping to put it in a preprocess function.
Comment: Did you try to just pass in a render array? Not everywhere but often, that just works.
Comment: If it doesn't, then rendering it and passing that in should work as that's then a Markup object and will not be further escaped.
Answer: The HTML attribute removal was documented in change record #2932803, but the example uses the now deprecated SafeMarkup::format function. The FormattableMarkup class allows a non-deprecated way to do this. The API page has some good examples such as below:
Remember that this is has security implications, and to only use FormattableMarkup when you absolutely need it with strict placeholders.
$value = FormattableMarkup::placeholderFormat('@variable', [':url' => $url, @variable => $variable]);

There's probably a better way to do this without printing the anchor element and href attribute yourself.
Comment: Looks like this will be the solution. I was hoping to pass a render array inside the link though. I'll give it a go and feedback.
Comment: I recently discovered [PlaceholderGenerator::createPlaceholder](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!PlaceholderGenerator.php/function/PlaceholderGenerator%3A%3AcreatePlaceholder/8), which might allow that. I have not been able to get it to work inside an Input Filter. However it may actually work outside of an Input Filter as the tests suggest that it should.
Answer: That's what worked for me.
https://stackoverflow.com/a/44163527/1151303
    <?php
    use Drupal\Core\Render\Markup;
    use Drupal\Core\Url;

    $form['actions']['reset_password'] = [
      '#type' => 'link',
      '#title' => Markup::create(
        ' Forgot / Reset Password'
      ), '#url' => Url::fromRoute('user.pass'),
    ];

How can you make an HTML link?


Why can we re-express the sum of group elements $g\in G$ to the sum of elements of $s\in S$ in Burnside's Lemma?

Question: Question:
In the proof of Burnside's Lemma, after assuming there are $r$ orbits, we can show that
$$ \frac{1}{|G|}\sum_{g\in G} = \frac{1}{|G|}\sum_{g\in G}\sum_{i=1}^r |S_i^g| = \sum_{i=1}^r \frac{1}{|G|}\sum_{g\in G}|S_i^g|. $$
We then wish to show that $\frac{1}{|G|}\sum_{g\in G}|S_i^g| = 1$ for each $i$ and so,
\begin{align*} \frac{1}{|G|}\sum_{g\in G} |S^g| &= \frac{1}{|G|}\sum_{g\in G}|\{s\in S:g.s = s\}| \\ &= \frac{1}{|G|}|\{(g,s)\in G\times S:g.s=s\}| \\ &= \frac{1}{|G|}\sum_{s\in S} |\{g\in G:g.s = s\}| \\ &= \frac{1}{|G|}\sum_{s\in S} |\mathrm{stab}_G(s)|. \end{align*}
However I can't seem to convince myself of the step: $$ \boxed{\frac{1}{|G|}\sum_{g\in G}|\{s\in S:g.s = s\}| = \frac{1}{|G|}|\{(g,s)\in G\times S:g.s=s\}| = \frac{1}{|G|}\sum_{s\in S} |\{g\in G:g.s = s\}| .}$$ Why can we do this? How does a sum over $g\in G$ become equivalent to counting all pairs and then become a sum over $s\in S$? Does this imply that the cardinality of the stabiliser and the fixed point set is always the same? This seems like some very slight notation trickery that I just can't intuitively see.
Any illumination would be greatly appreicated. Thank you.
As a side note, I hope my question has been worded adequately, as there is a lot of context which would have been difficult to leave out.
Answer: I think that the thing that is happening is very similar to what happens in the following scenario.
Let $G$ be a bipartite part with sides $X,Y$ where $X=\{x_1,\dots,x_{n_1}\}$ and $Y=\{y_1,\dots,y_{n_2}\}$. Then the number of edges of $G$ can be obtained with the following expressions:
$m= \sum\limits_{i=1}^{n_1} d(x_i)$.
$m= \sum\limits_{i=1}^{n_2} d(y_i)$.
They are basically doing this step twice, to get:
$\sum\limits_{i=1}^{n_1} d(x_i)=m= \sum\limits_{i=1}^{n_2} d(y_i)$
In fact we can turn your problem into the previous setting by letting $X=G$ and $Y=S$, and making the edges the pairs $\{x,s\}$ with $x.s=s$
Comment: Ok wow this is a great analogy. For the sake of ultimate clarity, $|\{(g,s)\in G\times S:g.s=s\}|$ is analogous to counting the number of edges 'directly' by just observing pairs that have an edge?
Comment: Yes exactly. ${}{}$
Answer: In general:
\begin{alignat}{1}
\lbrace \operatorname{stab}_G(s) \times \lbrace s \rbrace, s \in S \rbrace &= \{\{g\in G\mid g\cdot s=s\}\times\{s\},s\in S\}\\
&= \lbrace (g,s) \in G \times S \mid g\cdot s=s \rbrace \\
&= \lbrace \lbrace g \rbrace \times \{s\in S\mid g\cdot s =s\}, g \in G \rbrace \\
&= \lbrace \lbrace g \rbrace \times S^g, g \in G \rbrace \\
\tag 1
\end{alignat}
If both $G$ and $S$ are finite, then from $(1)$ follows:
\begin{alignat}{1}
\sum_{s\in S}|\operatorname{stab}_G(s)| &= |\lbrace \operatorname{stab}_G(s) \times \lbrace s \rbrace, s \in S \rbrace| \\
&= |\lbrace \lbrace g \rbrace \times S^g, g \in G \rbrace| \\
&= \sum_{g\in G}|S^g|
\end{alignat}


I can't install django-tracking in Django 1.5.4 and Ubuntu 13.04 EC2

Question: I'm having trouble installing the package django-tracking using Django 1.5.4 and Ubuntu 13.04. I've tried pip, easy_install and python setup.py install with no results. I get the following error message:
ubuntu@ip-10-164-30-68:~/django-tracking$ sudo python setup.py install
Traceback (most recent call last):
  File "setup.py", line 6, in <module>
    import tracking
  File "/home/ubuntu/django-tracking/tracking/__init__.py", line 1, in <module>
    import listeners
  File "/home/ubuntu/django-tracking/tracking/listeners.py", line 6, in <module>
    from django.core.cache import cache
  File "/usr/lib/python2.7/dist-packages/django/core/cache/__init__.py", line 70, in <module>
    if DEFAULT_CACHE_ALIAS not in settings.CACHES:
  File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 46, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not     configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call     settings.configure() before accessing settings.

I think it may be something simple that I'm just not seeing... Django-tracking is available here: https://bitbucket.org/codekoala/django-tracking
Please help! Thank you!
Comment: Refer following link:
http://stackoverflow.com/questions/18930640/facing-errors-in-installing-django-tracking/36773299#36773299
Answer: I finally installed it using the Bitbucket repo instead of the Github one. I don't know what's the difference but it seems it is more up to date. By the way, the otter methods (pip and easy_install) didn't work either.
Answer: Try following:
pip install git+https://github.com/bashu/django-tracking.git


Scrape webpage that requires md5 hash as a parameter

Question: I am trying to scrape the data from the below link, in a c# console app:
https://www.eex-transparency.com/homepage/power/germany/production/availability/non-usability
Using the developer tools in chrome I can see that its possible to get a json response, the url to get this is:
https://www.eex-transparency.com/dsp/tem-12?country=de&expires=1454345128&md5=TRhtJei_go4ueLeekBc8yw
the website uses this js file (https://www.eex-transparency.com/assets/js/tpe-website.js) to generate the expires and md5 hash key. I think I've figured out that the expires value is a unix datetime. I have never used javascript before so finding it hard to figure out how they construct the md5.
The Javascript that generates these code is:
<code>generateCryptedParams=function(url,clientIP)
{
    var cryptedParams,md5,md5Encoded,md5WithoutSpeciaChars,parser,timePoint,urlPath;

return timePoint=moment().tz("Europe/Berlin").add(1,"minute").unix(),
                 parser=document.createElement("a"),
                 parser.href=url,
                 urlPath=parser.pathname,
                 "/"!==urlPath[0]&&(urlPath="/"+urlPath),
                 md5=CryptoJS.MD5(urlPath+timePoint+clientIP+" zYeHzBomGdgV"),
                 md5Encoded=md5.toString(CryptoJS.enc.Base64),
                 md5WithoutSpeciaChars=replaceSpecialChars(md5Encoded),
                 cryptedParams={"expires":timePoint,"md5":md5WithoutSpeciaChars}
}

replaceSpecialChars=function(str)
{
var key,specialChars,value;
specialChars={"=":"","\\+":"-","/":"_","%":"_"};
for(key in specialChars)
    value=specialChars[key],
     str=str.replace(new RegExp(key,"g"),value);

return str
}
</code>
As i said I think I'm comfortable with the timepoint part but the md5 is confusing me. Below is my C# code to replicate their but when I pass the md5 hash their site returns a 403 Forbidden error.
<code>    public Tuple<string, Int32> GenerateCrypto(string url, string ipAddress)
    {
        string cetId = "Central European Standard Time";
        TimeZoneInfo cetZone = TimeZoneInfo.FindSystemTimeZoneById(cetId);
        var CETDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetZone);
        //Int32 unixTimestamp = (Int32)(CETDateTime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        Int32 unixTimestamp = (Int32)(DateTime.UtcNow.AddMinutes(1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

        url = url.Split('/')[3];
        var md5 = CipherUtility.GenerateMd5(url + unixTimestamp + ipAddress + " zYeHzBomGdgV");
        var md5Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(md5));
        var md5withoutSpecialCharts = replaceSpecialChars(md5Encoded);
        md5withoutSpecialCharts = md5withoutSpecialCharts.Substring(0, 22);
        return new Tuple<string, Int32>(md5withoutSpecialCharts, unixTimestamp);
    }
</code>
Comment: Just pay someone to reverse engineer the code for you (such work is generally gray zone at best from laws point of view, but)... Not sure why you expect SO to to that for you. If you have some more specific question - please edit your post to clarify.
Comment: Why you want to know how they construct MD5 hash?? What code are you using to scrape webpage? show us the code where MD5 hash is required? Generally MD5 hash is generated against content of webpage and is generally used to verfiy the content of webpage \ any document.....In C# you can use Cyrptography namespace to generate MD5 hash
Comment: Are you able to provide the exact JavaScript used to generate the MD5?
Comment: @Elias Did you ever solve this?
Comment: @EnergyNumbers Yes I did. If I remember correctly the reason I couldn't match the MD5 hash was because they concatenate a number to the unit date time before they produce the hash. If you are having the same issue I can look at my source code. I should change this post to answered.
Comment: @Elias nice one, cheers. I had a go at it myself, shortly after commenting here, and got some useful data: http://energynumbers.info/germanys-offshore-wind-capacity-factors . I'd be interested to see what you did.
Answer: The solution was that I needed to concatenate a const string to all the elements before hashing it.


Proof of ABCD Lemma

Question: A standard result in bifurcation theory due to Keller, known as ABCD Lemma, asserts that if $V$ is a Banach space, $M\,:\,V\times \mathbb{R} \to V\times \mathbb{R}$ is such that
$$
M:=\begin{pmatrix}
A & b \\
\langle c , \cdot \rangle & d
\end{pmatrix},
$$
where $A\,:\,V \to V$, $b \in V\setminus\{0\}$, $c\in V'\setminus\{0\}$ and $d \in \mathbb{R}$, then in particular
(1) if $A$ is an ismorphism on $V$, then $M$ is an isomorphism $V\times \mathbb{R}$ if and only if $d - \langle c, A^{-1}b\rangle \neq 0$.
All references to this result point to a paper by Keller from 1977, in which he doesn't actual provide proof, merely stating it will be provided elsewhere and giving a reference to some unpublished lecture notes.
How does one prove this result in the case of an infinite-dimensional space?
The part '$\impliedby$' is easy, one can look at $\|M(u,k)\|$ when $u = -kA^{-1}b$ to see that $d - \langle c,A^{-1}b\rangle \neq 0$ is a necessary condition. Can somebody provide me with a hint as to how to prove the part '$\implies'$? It seems like it shouldn't be too hard, we should establish existence of some constant $C>0$ such that
$$
\|M(u,k)\| \geq C(\|u\| + |k|)
$$
and I suppose, especially when $V$ is a Hilbert space, the trick is to decompose $u = \alpha A^{-1}b + v$, where $v \in \{v' \in H\,|\,(v',A^{-1}b)_V = 0\}$, where $(\cdot,\cdot)_V$ is the inner product? Although I do not quite see how this would work. If it is not a Hilbert space, then it is even less clear to me. Any hints will be greatly appreciated!
Comment: It should be said that this property generalizes **Schur's complement** properties (https://chrisyeh96.github.io/2021/05/19/schur-complement.html)
Answer: We solve the system $M(u,k)=(f,g)$ explicitly:
$$
Au + b k = f, \ cu + dk = g.
$$
Now, $A$ is invertible, hence $u=A^{-1}(f-bk)$.
Plugging this into the second equation yields
$$
cA^{-1}(f-bk) + dk = (d-cA^{-1}b)k + cA^{-1}f
$$
which should equal $g$.
This is an equivalence transformation: $M(u,k)=(f,g)$ if and only if $k$ solves
$$
(d-cA^{-1}b)k = g- cA^{-1}f.
$$
This shows that the equivalence in the desired statement: the system is solvable if and only if $d-cA^{-1}b\ne0$.

Proof of ABCD Lemma


CQRS Eventual Consistency Event Dependencies

Question: I'm new to the CQRS and eventual consistency models, so forgive me if this is a stupid question.
Given that I'm just getting started, I have a local in memory CommandBus and EventPublisher. My events are persisted to a RavenDB database for replay purposes, but events are published and handlers are invoked in locally (not queued externally via NServiceBus et al). The EventPublisher does publish events asynchronously (a la Task.Factory.StartNew).
Sometimes my events have dependencies (eg. the OrderReceived event must be processed into the ReadModel before the OrderShipmentStatusUpdated event can be correctly processed into the ReadModel).
How can I handle this kind of scenario? Using Sagas? How would one use Sagas in a simple in memory model like described above? Is it considered acceptable to "defer" an event (perhaps mark it as deferred and simply try to reprocess all deferred events "once in a while")?
What are some strategies for dealing with this?
Thank you.
Comment: any reason you publishing events asynchronously? if the events are published synchronously you will have no issues with the order of the events and you shouldn't have a problem with eventual consistency, because they will run in the same thread as the command.
Comment: Performance. And I would still have issues unless I synchronize across all web requests and only have 1 server, no?
Comment: @Jeff: I think that Sarmaad meant that OrderReceived and OrderShipmentStatusUpdated should be processed synchronously.
Comment: How would you suggest doing that with an in memory event publisher? Create a single threaded queue processed in the background?
Answer: A queue with retries most of the time solves such issues. If your handler/aggregate/denormalizer can't process a message, because preconditions are not met - fail it hard. Then you'll process some more messages from the queue until this one becomes visible again. If message fails more than 3 times - discard it into error queue for further analysis.
If it's an expected workflow and you actually have to wait - create Saga if not modeling with DDD/Event Sourcing. If modeling with DDD/Event Sourcing - Aggregates will cover such functionality most of the time.
Answer: I agree with ILICH.
Events happened and the read model should just report on that.  The read model should not be in a position to validate events.
It may be easier to have the shipping logic in the domain model rather then create a new saga.
Another way to 'cheat' on a smaller project is to use the event as a trigger to read from the eventstore.  So when your read model gets an event notification it should load all the "new" events from the eventstore.  This ensures that nothing is lost in transit and simplifies what you use the bus for.
In the prototyping stage it also lets you blow away your read models at will and have them automatically rebuild.
I keep a little table of "job history" that reflects the most recent event consumed to process a particular read model.  If I want to change the schema of the read model I just delete the appropriate record.
Answer: The question is why the events are arriving out of order?
If it's because of "technical forces" you can look at your infrastructure addressing this but this normally would require a full-blown message queue.
If messages/events are out of sync because of "business processes" then you can look at Sagas/ProcessManager. Have a look at Greg Young's approach of using the event store as queue.
To get to your question about deferring events: What you can consider is to use a simplified approach by modeling the required ordering using Aggregates. It will consume events and notify the read side only when conditions are met.  The view will only project events that have been "validated" by the aggregate. You have the benefit of making implicit concepts explicit in your model. The down side is that you'll have more events generated. (Yes, nothing is for free)
Have a look at Rinat Abdullin's approach on this. It's an old but interesting post and perhaps refer to the Being The Worst podcast which also covers some of this.
Answer: It's better to use data from Events Store instead of data from Read Model for processing OrderShipmentStatusUpdated event, this will solve the issues connected with eventual consistency.
Events store is the only source of truth.
Comment: How do I ensure events are processed synchronously when only using an in memory even tpublisher?
Comment: And are you saying my read model event handlers (denormalizers) should use my EventSource as a means of updating the read model?
Answer: On the problems of sync/async event publishing:
By wrapping the given DomainEvents with an EventCommit object having an own commit id persisted into the event store, we could asynchronously process the EventCommit objects, while the DomainEvents within the EventCommit were synchronously published. The wrapping happens in our UnitOfWork which tracks our in-memory aggregates when the changes to a given aggregate are requested.
On the read side the commit-id can be used to verify correct ordering directly in the dequeing process before dispatching the events to the handlers.


You must include at least one positive keyword with 3 characters or more

Question: Drupal 6.20 according to the changelog file.
We took over a site from another company who built the site in Drupal, and we'll be converting it over to Wordpress eventually but we need to resolve the search issue first.
I get the "You must include at least one positive keyword with 3 characters or more." error message whether I use the search bar (search module) which leads you to "search/node/KEYWORD" with KEYWORD being your search parameter or if I just go to /search after the URL.
I've read about this and have tried all the suggestions that I saw and none have resolved the issue. I re-indexed the site, and ran cron.php. After I ran cron.php I looked at the settings again and it shows that 100% of the site has been indexed.
I also manually changed the search module status in the database, but it only made the search bar disappear and after I changed the status back to active I got the same result. I tried that because it worked for another module that wasn't working on startup.
The entire site and DB was copied over, and the site that is on the other company server the search functions properly. I don't think it's php version related because I ran a script to revert back to PHP 5.3. Does anyone have any suggestions on what else I might try to possibly get the search working?
Comment: Could it simply be related to the URL not matching?  The domain name hasn't transferred to us yet, and the URL on our side where the search doesn't work is of course different from the main URL.
Answer: The search module is a little weird in Drupal, and can take some time to wrap your brain around.  If you start reading from node_search(), you will see a call to do_search() which is the function that links the search indexes to the things you are searching over.
If you read that function, you will see that there is a variable minimum_word_size, that defaults to 3.  If you need to be able to search on smaller words, you need to set this smaller.  I believe you can set this on 'admin/settings/search', but I don't have any Drupal 6 sites to check against.
Change this value, then wipe the search index and rebuild it.  These last two steps are most easily accomplished with Drush.
Comment: Thank you for taking the time to reply.  You're exactly right on the directory to change the search settings. I changed the "Minimum word length to index" from 3 to 2, saved the configuration, wiped, and re-indexed.  In the indexing status I'm showing 100% of the site has been indexed.  I previously tried this but did not change the Minimum word length but I'm getting the same result.  The file where you reference the functions you mentioned could you give me an idea of where to look for it, and what the file name is?  I had luck re-uploading files on modules that were acting funny.
Comment: I found the directory modules/search and re-uploaded everything again, but it didn't change anything.


Symphony deconstructed by instruments

Question: does anyone know if this has been done before? I'm interested in listening to a symphony deconstructed by the instruments. Preferably if I can turn them on or off to listen to the whole piece without 1 specific instrument!
Thanks!
Answer: You can get quite decent Standard Midi Files of famous classical pieces!
So you can listen to any combination of instruments you like. The better your sound module the better the result will be - provided some decent programming of the file itself...
Comment: It would be helpful to include links to good sources of full-orchestra midi files.
Comment: @CarlWitthoft For example, is [The Mutopia Project](http://www.mutopiaproject.org/) any good?
Comment: @tepples, I'd say yes.

Symphony deconstructed by instruments


NO ACTIVATE window style

Question: I need a window that does not activate when I click on it but is should elsewhere react normal. By  normal I mean if there is a button on it and I click on the button it should execute the  click and call the click function ( or event handle or what so ever). So it should be a normal window except that it shouldn't get activated when you interact with it.
I know you can do this with a message filter or hooks but is there any window style that does this automatically?
this is for windows.
thanks!
Comment: I would show you some sample code, but I'm not sure if you're trying to do this in C++ or C#. Which is your target language?
Comment: I can do it in c / C++ , C# it doesn't mater
Comment: Yes, you can do it in any of the languages. You're saying that you don't care which your program is written in? Do you know how to set extended window styles and process Windows messages?
Comment: i've just tried  WS_EX_NOACTIVATE and it won't activate the window as expected but it also won't execute click on buttons and other stuff. I'll try WM_MOUSEACTIVATE message and came back with some feedback.  Thanks!
Answer: Have you tried the WS_EX_NOACTIVATE extended window style?

A top-level window created with this style does not become the foreground window when the user clicks it. The system does not bring this window to the foreground when the user minimizes or closes the foreground window.
To activate the window, use the SetActiveWindow or SetForegroundWindow function.

Otherwise, if that doesn't do what you want, you will need to handle the WM_MOUSEACTIVATE message and return MA_NOACTIVATE.

NO ACTIVATE window style


Finding elements of $\mathbb{Z}_3[x] /\langle x^2+2\rangle$ and writing the multiplication table

Question: I want to list elements of $\mathbb{Z}_3[x] /\langle x^2+2\rangle$ and write a multiplication table. Here is my attempt to finding the elements:
Let $A =\langle x^2+2\rangle= \{(x^2+2)f(x): f(x) \in \mathbb{Z}_3[x]\}$ and $\mathbb{Z}_3[x] / A = \{f(x) + A: f(x) \in \mathbb{Z}_3[x]\}$ by definition.
Let $f(x) \in \mathbb{Z}_3[x]$. By division algorithm, $f(x) = (x^2+2)q(x) + a + bx$ for some $q(x) \in \mathbb{Z}_3[x]$ and $a,b \in \mathbb{Z}_3$. Hence, $f(x) + A = (x^2+2)q(x) + a + bx + A = a + bx + (x^2+2)q(x) + A$. Since $(x^2+2)q(x) \in A$, $(x^2+2)q(x) + A = A$. Thus, $f(x) + A = a + bx + A$. So we have $\mathbb{Z_3}[x] / A = \{a + bx + A: a,b \in \mathbb{Z_3}\}$. Hence, the elements are the following:

$A$
$1 + A$
$x + A$
$2 + A$
$2x + A$
$1 + x + A$
$2 + x + A$
$2 + 2x + A$
$1 + 2x + A$

My question is:
1) Is this the right derivation?
2) How does multiplication table work in $\mathbb{Z}_3[x] / A$? For example, if I have $(x+A)(1+2x+A) = x(1+2x) + A = x+2x^2 + A$ which is not in the same form as $ax+b+A$.
Answer:
Yes, that is the right derivation.
Now, divide $2x^2+x$ by $x^2+2$. That is easy:$$2x^2+x=2\times(x^2+2).$$So, the remainder is $0$, wich means that, in your ring, $(x+A)(1+2x+A)=0+A=0$. In particular, your ring is not a field (not a surprise, since $x^2+2=(x+1)(x+2)$ in $\mathbb{Z}_3[x]$).
Answer: Using mod notation, in the quotient ring we have $\,\color{#c00}{x^2}\equiv -2\equiv\color{#c00}1\,$ which implies every polynomial is congruent to one of degree $\le 1,\,$ because $\,x^{\large 2q+r}\! =  (\color{#c00}{x^{\large 2}})^{\large q}\,x^{\large r} \equiv \color{#c00}{1}^{\large q}\,x^{\large r}\equiv x^{\large r}\, $ for $\,r\in \{0,1\}$
Alternatively breaking into even+odd parts $\,f(x) = g(\color{#c00}{x^2}) + x\, h(\color{#c00}{x^2})$ $\Rightarrow\, f(x)\equiv g(\color{#c00}{1}) + x\, h(\color{#c00}{1})$
Or we can apply Division with Remainder: $\,f(x) = q(x) (\color{#c00}{x^2}\!-\!\color{#c00}1) + ax+b\,\Rightarrow\, f(x)\equiv ax+b$
So every $f(x)$ is congruent to $\,(f\,\bmod x^2\!-\!1)\bmod 3\,$ having degree $\le 1$, and these linear reps $\,f,g\,$ are incongruent else $\,x^2-1\,$ divides a lower degree polynomial $\,f - g \not\equiv 0\pmod{\!3}.\,$ Therefore they comprise a complete set of representatives of the quotient ring classes (cosets). In particular, there are $\,3^2 = 9$ such linear reps $\,ax+b$ corresponding to the $3$ choices for the coef's $\,a,b\bmod 3$. Your table correctly lists these $9$ reps.
To multiply these linear normal-form reps compute the polynomial product then replace $\,\color{#c00}{x^2}\,$ by $\,\color{#c00}{1}\,$
$$ (a_1x + a_0)(b_1 x + b_0)\, \equiv\, (a_0 b_1 + a_1 b_0)\, x + a_0 b_0 \color{#c00}{+1}\,a_1 b_1$$
while performing coefficient arithmetic $\!\bmod 3.\,$ The coefficient arithmetic will be slightly simpler if we use $\,-1\,$ vs. $\,2\,$ as our rep for $\,2+3\Bbb Z,\,$ which  also serves to clarify innate algebraic structure,  e.g. $\,(x+1)(x-1) = \color{#c00}{x^2}-\color{#c00}1\equiv 0\,$ vs. $\,(x+1)(x+2)\equiv \color{#c00}{x^2}+3x+\color{#c00}2\equiv 0$


How to find Part of a String and echo it out?

Question: $string = "David Smith (Local/202@from-queue/n from SIP/202) (ringinuse enabled) (Not in      use) has taken 1 calls (last was 843 secs ago)";
I need to echo out the calls taken (1).
I have tried:
$taken_calls = substr($string, 'taken ', 4 );

How do I do that? Thankyou.
Comment: Read the chapter on regular expressions
Answer: Use regular expressions:
<?php
$string = "David Smith (Local/202@from-queue/n from SIP/202) (ringinuse enabled) (Not in use) has taken 1 calls (last was 843 secs ago)";
$matches = array();

if (1 === preg_match('/taken (\d+) calls/', $string, $matches)) {
    echo $matches[1];
}

Answer: $string = "David Smith (Local/202@from-queue/n from SIP/202) (ringinuse enabled) (Not in use) has taken 1 calls (last was 843 secs ago)";
$result= array();
preg_match("/taken\s(\d+)/", $string, $result);

var_dump($result);

Result:
array(2) {
           [0]=> string(7) "taken 1"
           [1]=> string(1) "1"    // this is your number
}

Edit: Now, the number could have more than 1 digit
Comment: whats the preg_match if the number is more than one, sometimes the number could be 2 digits or 3 digits long. At the moment if the number is 12 I only get 1 in the array string.


Print_r and foreach giving different results

Question: I have a pdo function that fetches usernames and user ids from the database. When I run the function i get different results.
print_r gives
Array ( [ID] => 58 [username] => abdullatif )
and foreach gives me
5-5a-a
There is one row that matches the pdo query in the database.
public function getUserCredentials($userName, $password){
$this->db   = new Dbpdo_Database();
$this->db->connect();
try{
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $dbh->prepare("SELECT
            ID
          FROM
            administrators
          WHERE
            username = :username
          AND
            user_password = :password
          LIMIT 1");

    $stmt->bindParam(':username', $userName, PDO::PARAM_STR);
    $stmt->bindParam(':password', $password, PDO::PARAM_STR);
    }

    $stmt->execute();

    /*** fetch the results ***/
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $results;

    /*** close the database connection ***/
    //$dbh = null;
}
catch(PDOException $e){
    echo $e->getMessage();
  }
}

$results = $mydb->getUserCredentials($userName, $password);

foreach ($results as $row){
echo $row['ID'].'-'.$row['username'];
}

print_r($results);

Any hints as to whats wrong would be much appreciated. Thanks in advance.
Answer: Your $results array is one-dimensional - it has an ID and a username. Your foreach is looking for a two-dimensional array, with each row containing an ID and a username. Change it to:
foreach($results as $key => $value) {
    echo $key . '-' . $value;
}

and you should get:
ID-58
username-abdullatif

Comment: if i wanted just the result of the id how would i do that?
Comment: `$results['ID']` (this may change if more than one matching row is returned, depending on your script)


Add html5 input types using drupal form api

Question: I want to add HTML5 number type textfield in the form programmatically. I am building the form using hook_form().
I tried adding the code:-
$form['field_price']['#attributes']['type'] = 'number';

But it isnt working.
Is there any other work around for the same?
Answer: Try Element module. it adds advance html5 elements to your form.
Similar question is asked here
Answer: An alternative to using Element, and since theme_textfield() has a hardcoded value of type 'text', you may want to override theme_textfield() in your template.php. You can copy theme_textfield(), paste it in your theme's template.php and rename it, then make necessary changes. For example
(NB: I HAVEN'T tested this, so there may be some bugs):
function MYTHEME_textfield($variables) {
  $element = $variables['element'];
  if (isset($element['#attributes']['type'][0]) && $element['#attributes']['type'][0] == 'number'){
    $element['#attributes']['type'] = 'number';
  } else {
    $element['#attributes']['type'] = 'text';
  };
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-text'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input'])) {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

This will hardcode as type text any element that does not specifically have a key $form['field_name']['#attributes']['type'] = array('number');


A condition that balls have finite measure

Question: Let $(X,d)$ be a metric space and let $\mu$ be a positive measure on $X$. I want to require that $(X,d)$ and $\mu$ have either of the following properties:

$\forall y \in X$, $\forall r \geq 0$, $\{x : d(x,y) = r\}$ has finite measure (according to $\mu$).
$\forall y \in X$, $\forall r \geq 0$, $\{x: d(x,y) \leq r\}$ has finite measure (according to $\mu$).

(That is, I am interested in the case where I impose #1 and in the case where I impose #2.)
My questions are:

Are the requirements equivalent? (Answered below: no.)
Has either requirement been made before, and if so, what is it called and where can I learn about it?
Is either condition equivalent to or implied by some nicer or well-known condition on measure spaces?

Thanks very much!
Comment: Do you have an example of $\mu$ so that $\mu\left(\left\{x : d(x,y) = r\right\}\right)\not=0$?
Comment: @xavierm02: I could think of a discrete space, like the lattice of points in $\mathbb{R}^n$ with integer coordinates, where $\mu(A) = |A|$.
Comment: The only "bad" case I could think of would be something like the completely discrete metric, $d(x,y) = 1$ for all $y \neq x$. It seems like many reasonable conditions could rule such things out, but I'm wondering what the most general could be....
Comment: Maybe assuming the measure is regular makes the conditions equivalent? I haven't checked this, but it's something to look into.
Comment: @Suugaku: Note that Michael Greinecker's counterexample is a $\sigma$-finite regular measure.
Comment: Oh, indeed... Duh.
Answer: Take the plane with the usual metric, and take $\mu$ to be Hausdorff $s$-dimensional measure, where $1<s<2$.  The disks have Hausdorff dimension $2$, so their $\mu$-measure is $\infty$.  The circles have Hausdorff dimension $1$, so their $\mu$-measure is $0$.
Answer: Just take $\mathbb{R}$ endowed with Lebesgue measure and the metric given by $$d(x,y)=\frac{|x-y|}{1+|x-y|}.$$ Then $\{x:d(x,y)=r\}$ has always finite measure, but $\{x:d(x,y)<1\}$ has infinite measure. So the conditions are not equivalent.
Answer: For the first question:
Let $X = \mathbb{R}$ (with $d(x,y) = |x-y|$) and $\mu$ be the counting measure (ie, $\mu(A) = |A|$, and $\mu(A) = +\infty$ when $|A|$ not finite). Then the spheres will have measure 2, but the balls will have infinite measure.


Matrix multiplication - How to make a planet spin on it's own axis, and orbit it's parent?

Question: I've got two planets, the sun and the earth. I want them to spin on their own axis, and orbit the planet at the same time.
I can get these two behaviors to work individually, but I'm stumped as to how to combine them.
void planet::render() {
    mat4 axisPos = mat4(1.0f);
    axialRotation = rotate(axisPos, axisRotationSpeedConstant, vec3(0.0f, 1.0f, 0.0f));

    if (hostPlanet != NULL) {
        mat4 hostTransformPosition = mat4(1.0f);
        hostTransformPosition[3] = hostPlanet->getTransform()[3];
        orbitalSpeed += orbitalSpeedConstant;

        orbitRotation = rotate(hostTransformPosition, orbitalSpeed, vec3(0.0f, 1.0f, 0.0f));
        orbitRotation = translate(orbitRotation, vec3(distanceFromParent, 0.0f, 0.0f));

        //rotTransform will make them spin on their axis, but not orbit their parent planet
        mat4 rotTransform = transform * axialRotation;

        //transform *= rotTransform;

        //orbitRotation will make the planet orbit, but it won't spin on it's own axis.
        transform = orbitRotation;
    }
    else {
        transform *= axialRotation;
    }

    glUniform4fv(gColLoc, 1, &color[0]);
    glUniformMatrix4fv(gModelToWorldTransformLoc, 1, GL_FALSE, &getTransform()[0][0]);
    glDrawArrays(GL_LINES, 0, NUMVERTS);
};

Answer: Woohoo! As usual, asking the question lead me to being able to answer it. After the last line, knowing that transform[0 to 2] represents the rotation in the 4x4 matrix (with transform[3] representing the position in 3D space), I thought to replace the rotation from the previous matrix calculation with the current one.
Badabing, I got my answer.
    transform = orbitRotation;
    transform[0] = rotTransform[0];
    transform[1] = rotTransform[1];
    transform[2] = rotTransform[2];


Notes grouped under a number

Question: I have been trying out various questions on music theory to prepare for my grade 5 exam on Wednesday and I have come across many pieces with grouped notes but with a number above for example six grouped notes with a 6 written above. What does it mean?
Answer: Tuplets.   The most common sort is a triplet - three notes played in the time of two.   Sometimes a pair of tuplets are written as a sextuplet.
All of the bars in this example add up correctly in 4/4 time.
Answer: These are "tuplets." The usual simple examples are

"3" means "play 3 notes in the time of two" (called "triplets")
"2" means "play 2 notes in the time of three" (e.g. two 8th-notes in 6/8 time)
"6" means "6 notes in the time of 4".

For more complicated examples, often the ratio is written, e.g. "5:3" means "play 5 notes in the time of 3".
And in really complicated examples, tuplets can be written inside other tuplets - but this example is a bit more advanced than a grade 5 theory exam! (Click on the image to enlarge it.)

Notes grouped under a number


force a created file or folder to have a specific stat struct

Question: I have a stat struct and I want to create a folder or a file and want to force it to have the same information as in the stat struct.
For instance:
create file: test.txt
The file's last modification date is today 16.01.2014
change file's stat so that it shows:
last modified on 01.01.2050

How can I do that?
Answer: If you want to set the mtime/atime fields, you can use the utime() function. Use it after creating the file/directory.
The mode field is set with chmod()
The uid/gid, if you are root, are set with chown().
The fields size and nlinks will have the correct value if you set the information they refer to (the data of the file and the directory structure that contains the file).
But the ino, dev and ctime fields are set internally by the system and cannot be changed. No reason you would like to set them, anyway.
Comment: I actually want to create a file with a specific stat struct! To be specific, I'm restoring a file that I have backep up before. The stat information must also be set accordingly.
Comment: On a second note, I just checked tar. Tar reserves ino and dev of the file. So it should be possible to do so!
Comment: @hhachem: Have you a reference/experiment for this? I find it hard to believe... what if you decompress the same tar file twice? The dev/ino pair must be unique!
Comment: I believe you are right. I just moved the .tar file somewhere else, extracted it and it gave me a different inode number. But when I was extracting it in the same directory as the original, it was replacing the original and returning the same inode number.
Comment: @hhachem: Well, when a file is deleted, its inode is marked as free and may be reused for later. So if you restore right after deleting, chances are that you get the same inode numbers (the `dev` is the device (volume) identifier so that is out of the question).
Answer: I don't think you can, but that's OK.
Much of the information in the struct stat is implementation details for the file system; the file "is the same" even if (for instance) it has a different inode.
You need to look at individual file-related library calls to make all the fields that are actually relevant match, though:

st_mode can be set by chmod()
st_uid and st_gid can be set by chown()
st_atime and st_mtime can be set by utime()

There's no single "set all the stat fields" function, since that wouldn't make sense.
Comment: interesting. I guess that should help me further. Thank you. I will have to accept rodrigo's answer though since he was faster to answer.


How to collect I/O Bandwidth statistics on ubuntu 14.

Question: I want to write script/service to collect I/O bandwidth consumption on daily basis. I know nload tool which will show total I/O data transfer from the time we executed the command. I want script to generate data for this bandwidth and save in some file on day to day or per hours basic. Please suggest if I can use any other tool.
Thanks in advance.
Answer: Check out a tool like Munin, Zabbix, Icinga.
If you really want to collect data by hand check out <code>/proc/net/dev</code> which gives you the current transmitted/received byte and packet count among others since system boot (or driver start). Subtract the current value from a previously captured and you get how many bytes or packets have been transmitted/received since then.


Drupal commerce: Save into a customer profile field

Question: im trying to save into a customer profile field. Reading it out is no problem:
<code>if(!empty($order_wrapper->commerce_customer_billing->field_shop_annotations)) {
$annotations = $order_wrapper->commerce_customer_billing->field_shop_annotations->value();
}
</code>
But saving into gives me an error message. Here's my code:
<code>// Save annotations
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$annotations = $form_state['values']['annotations'];

$profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

$profile = commerce_customer_profile_load($profile_id);

if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {
   // This gives me the error message:
   $profile_wrapper->commerce_customer_billing->field_shop_annotations->set('muh');
}
</code>
Everthing works fine except the set method inside the if clause. I also tried:
<code>$profile_wrapper->commerce_customer_billing->field_shop_annotations->value = $annotations;
</code>
Answer: ok i got it:
<code>$annotations = $form_state['values']['annotations'];
global $user;

// load oder
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

// get profile id
$profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

// load customer profile
$profile = commerce_customer_profile_load($profile_id);
if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {

       // set the value of the field and save the profile
       $profile_wrapper->field_shop_annotations->set($annotations);
       $profile_wrapper->save();

}
</code>