Diff HEAD and merge-branch against parent for merge conflicts in VS Code

Question: For better or worse, I regularly encounter in my Git workflow scenarios with fairly large merge conflicts. I find the best way to resolve these is typically to get the diffs of a) the HEAD branch against the parent branch, and b) the merge-branch against the parent branch, in order to manually inspect the changes and incorporate bits of both. However, Git and Visual Studio Code does not at all make this easy. Is there any solution, ideally specifically for VS Code, that allows me to inspect these two diffs for each merge conflict?
Comment: Other editors have really effective merge tools. If nobody's implemented one for VS Code, either nobody's bothered or it's not possible.  Looking at its extension docs, it's possible, kinda, but it's not an api I'd like working with, it doesn't surprise me.
Comment: @jthill I suspect you might be right; thanks for looking.
Answer: git mergetool is what Git provides as a building block here.  It is by no means perfect, but it provides the three key inputs: the merge tool that git mergetool runs, which you may construct yourself, gets as its arguments your own expansion(s) of these variables that hold file names:
$BASE
$LOCAL
$REMOTE
$MERGED
$BACKUP

Not all files will always be present.  In particular, $BACKUP is omitted if you tell git mergetool that it can trust the merge tool's exit status.  Tools should generally ignore the $BACKUP variable, but see below.
Your tool's job is to produce, in $MERGED, the correct resolved file data.  You may read the text of the merge base input from $BASE.  The HEAD or --ours version of the file is in $LOCAL, and the other or --theirs version of the file is in $REMOTE.  Your tool can use any code you can think of and write, including running diff commands from $BASE to $LOCAL and/or from $BASE to $REMOTE, if you wish.
How this all works
Note that git mergetool operates on one file at a time.  That is, git merge has already made its best attempt at doing the merge on its own.  This attempt has failed (otherwise you would not be running git mergetool).
At git merge time, Git read (past tense) three sets of files from three commits:

a merge base commit, containing whatever files are in that snapshot;
an "ours" commit (HEAD), containing whatever files—or in some cases, such as with git stash apply, the files in the working tree were copied into the index and those were used as the "ours" commit; and
a "theirs" commit (the other commit, --theirs or "remote" here).

Let's assume for illustration that in the merge base commit we had a file foo.txt, in the --ours commit we had foo.txt, and in the other commit we had foo.txt, and there was a merge conflict at lines 100–120 or so, plus non-conflicting changes on earlier and later lines.
Because Git did its best to combine our changes with their changes, there is a foo.txt file in the working tree right now that contains Git's attempt.  This has Git's decision as to what the right result was for the earlier and later lines, and, in place of the original lines 100–120 or so, conflict markers and the "ours" and "theirs" sections of the corresponding files (plus the corresponding "base" section if using diff3 or the new zdiff3 format).
Because Git failed to fully resolve the file, though, Git's index now contains all three input files: :1:foo.txt has the base version, :2:foo.txt has the --ours version, and :3:foo.txt has the --theirs version in it.  The git mergetool command copies these three versions of foo.txt out of the index—the index copies are in Git's internal read-only compressed-and-de-duplicated format, unreadable by anything other than Git itself—into ordinary files with peculiar temp-file names.
Now that these four versions of the file exist (base, local, "remote"/theirs, and merged), the git mergetool command sets up four shell variables, $BASE, $LOCAL, $REMOTE, and $MERGED to hold the four file names that hold these contents.  Since $MERGED is the simple file name (foo.txt) it doesn't have any funny dots or pids or /tmp or whatever squeezed into its name, but your program should just use $MERGED to find the file's name.  Again, this is where your program—your merge tool—should write its final result.
If you don't tell Git to trust your command's exit status, Git will copy the initial (pre-tool-run) copy of $MERGED to a temporary file named $BACKUP.  After your tool exits, regardless of its exit code, Git will compare the contents in $BACKUP against the contents in $MERGED.  If the two files match, Git will assume the tool failed and the file is not resolved yet.  If the two files differ, Git will assume the tool succeeded and the file is resolved correctly.
If you do tell Git to trust your command's exit status, Git doesn't bother with this, and just looks for zero (succeeded) or nonzero (failed) as the exit status.
In either case, having run your command to completion, Git now uses the success/failure indicator to decide whether to run git add on $MERGED.  If Git believes the tool has succeeded, git mergetool will run the git add command, which will mark the file resolved (knocking out the three nonzero-stage index entries and putting in a single stage-zero entry).  If Git believes the tool has failed, git mergetool does nothing, leaving the three nonzero-stage index entries that mark the file as unresolved, enabling later resolution and keeping the three inputs available.
The mergetool code then cleans up its temporary files, and goes on to the next unresolved file.  It simply iterates through all unresolved files, one at a time, running your chosen merge tool as described above.  Or, you can run git mergetool f1.ext f2.ext to limit it to resolving just those two files, for instance.
Since you can provide a shell script, binary executable, or whatever you like as the merge tool, you can get it to behave any way you like: it's just a Small Matter of Programming.  The painful part here is that it's always run one file at a time, so it never gets a "global view" of the diffs across all files.  (Also, for tree-level conflicts, such as rename/rename or modify/delete, git mergetool falls back on rather primitive prompting.)
Comment: Thank you for this detailed background on on merge conflicts and `git mergetool`. It's good to know, though I'm not sure it answers the question directly, in particular with regards to VS Code tools.


ler dados de uma url e fazer download

Question: olá, preciso fazer o download de varias urls, executo o código abaixo dentro de um for, mas só funciona para o último url.
var anchor = document.createElement('a');
anchor.href = 'http://e-gov.betha.com.br/e-nota/teste';
anchor.download = 'http://e-gov.betha.com.br/e-nota/teste';
document.body.appendChild(anchor);
anchor.click();

Alguém tem alguma outra sugestão? Agradeço
Comment: Você vai executar isso no browser ou node?
Comment: no browser, mas caso não seja possível, executo no servidor
Answer: Para fazer download de um arquivo utilizando o Node.js você pode usar um módulo de requisição http e utilizar o stream de resposta para gerar um arquivo. No meu exemplo utilizarei o módulo request. Para instalá-lo utilize o comando:
npm i request

A seguinte função irá realizar o download do arquivo de uma URL para a pasta de destino:
const { createWriteStream } = require('fs');
const request = require('request');

const baixar = (url) => {
  return new Promise((resolver) => {
    const partes = url.split('/');
    const arquivo = createWriteStream(partes[partes.length - 1]);

    request(url).on('response', (resposta) => {
      const stream = resposta.pipe(arquivo);

      stream.on('finish', resolver);
    });
  });
};

Para realizar o download de vários arquivos você pode criar uma função que divida um array em segmentos menores para realizar em paralelo e executar a chamada dentro de um laço de repetição:
const dividir = (origem, tamanho) => {
  const segmentos = [];

  for (let i = 0; i < origem.length; i += tamanho) {
    segmentos.push(origem.slice(i, i + tamanho));
  }

  return segmentos;
};

(async () => {
  const links = [
    "http://localhost/arquivos/arquivo1.png",
    "http://localhost/arquivos/arquivo2.png",
    "http://localhost/arquivos/arquivo3.png",
    "http://localhost/arquivos/arquivo4.png",
    "http://localhost/arquivos/arquivo5.png",
    "http://localhost/arquivos/arquivo6.png",
    "http://localhost/arquivos/arquivo7.png",
    "http://localhost/arquivos/arquivo8.png",
  ];

  const partes = dividir(links, 3);

  for (parte of partes) {
    const promessas = parte.map(link => baixar(link));

    await Promise.all(promessas);
  }
})();

ler dados de uma url e fazer download


Drupal 7 Views, paths, node associations via taxonomy

Question: After many hours I still cannot wrap my head around what is needed to make my situation work. Here it is:
I current am using clean URLS like so /artists/name-of-artist routes content type Artist. I have content types: Arists, Album Releases, Tour Dates, and Media. I would like to tie everything together using vocabulary Artist Tags (yes, even Artist content type would get tagged). So, say for example I have "Test Artist" in Artist content. I tag it with "Test Artist" Artist Tag. I also create an Album Release tagged "Test Artist". My question now is when visiting /artist/test-artist how do I have a view that shows not only the dat from that artist node but also from the Album Release node tagged "Test Artist".
I have already tried Node Reference. This is not an ideal solution for me as I want the flexibility of library categorization via taxonomy. I just can't understand how I can pull in another node's content based on  /artist/test-artist Artist Tag field.
I forgot to mention that I am using the latest version of Drupal 7, and Views 3.
Comment: its seams you talk about panels where you can show related contents in separated blocks based on taxonomy in one page
Answer: Sorry for a general answer, but it may get you in the right direction anyway.
What you seem to need is to establish relationships in views. By adding a relationship, you just add an object you would like to refer to. Once you add a relationship (on the right hand side, in Advanced panel), additional fields appear in the Add Field and Filter dialogs. Note the dropdown list that appears in field-related dialogs that contains relevant relationships that you have defined. You may also have a cascaded relationship (a relationship that uses another relationship).
All that translates later into the WHERE clause of the final query which filters what you want to show/hide.
To use the elements of the path, you want to use Contextual filter where you specify which part of the URL means what.
One thing to remember is that, even though you have clean URLs turned on, there is an "unclean" URL query behind the scenes which contains stuff like term IDs or node IDs. Perhaps it'd be useful for you to turn the clean URLs off for a moment, and play for a while just to see what kind of URLs will be used by views contextual filter. Or put <?php print $_GET['q'] ?> somewhere in the page.tpl.php for testing convenience.


How to set the input control of type datetime-local to the current time

Question: I am straggling to set the date and time of my input field of type datetime-local in Angular to the current time.
Below is the section of my template html file.
<form [formGroup]="form" (ngSubmit)="onSubmit()" *ngIf="isLoaded && !isAdmin">

            Date
            <input type="datetime-local" formControlName="scheduledDate" class="form-control" />

</form>

I have tried the suggestion given on stackblitz Here but it gives me strange error ERROR Error: NodeInjector: NOT_FOUND [NgControl]
Answer: according to docs the thing that you are looking for is a HTML property called value, the ngModel should work as well.
<input type="datetime-local" [value]="today"/>

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  today = new Date();
}

You may find the working example here
Comment: Thanks. Somehow it does not work for me. The stackblitz example doesn't seem to be working either - it displays just the template for date time (dd/mm/yyyy --;-- --)
Comment: Maciej any suggestions? I am trying to desperately solve this problem.
Comment: hmm sorry, I don't know, it is odd tho :/
Answer: I do not know angular but a vanilla js solution is
 <input type="datetime-local" data-name="dateStart" id="dateTimeStart"

const now = new Date();
now.setMinutes(now.getMinutes()-now.getTimeZoneOffset());
document.getElementById('dateTimeStart').value = now.toISOString().slice(0, 16);

I guess this can be adapted for Angular !?


Macro e VBA que apague os registros mais antigos, se forem o mesmo valor

Question: Fala galera, sou novo aqui e estou desesperado por uma ajuda.
Preciso que apague os registros mais antigos de uma lista de várias viagens, mantendo apenas o mais recente deles. O print abaixo deixa mais claro.

Neste caso eu precisaria que os do dia 21/09 e 23/09 fossem apagados, restando apenas os do dia 26/09.
O problema é que tem repetições nas placas e que, se forem do mais recentes, precisam ser mantidas.
Ajudem um universitário desesperadoooo :(
Comment: Leia o [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas) e leia também [Que erro eu cometi fazendo minha pergunta?](https://pt.meta.stackoverflow.com/questions/8388/que-erro-eu-cometi-fazendo-minha-pergunta?cb=1)
Comment: Obrigado pela dica, irei reformular mais tardar
Answer: <code>Sub removerAntigo()

Dim UltimaLinha As Long
UltimaLinha = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Dim i As Long
For i = 2 To UltimaLinha

If Cells(i, 1).Value = "" Then Exit Sub

If Cells(i, 3) = Cells(i + 1, 3) Then

    If Cells(i, 1) <= Cells(i + 1, 1) Then

    Rows(i).Delete
    If i = 2 Then i = 1

    End If

End If

Next i

End Sub
</code>
Eu acabei fazendo um escopo aqui mas ainda não tive sucesso, minha macro exclui valores, mas não mantem as placas iguais com a mesma data, como mostra na imagem da pergunta. Também, não se resume a uma placa apenas, esta foi um exemplo, não me atentei em falar isto antes . Resumindo: vou colar um relatório de determinado intervalo de datas (1 semana por exemplo) e quero me certificar de que não terei duplicidade no momento que eu usá-lo para analisar os dados. Sendo um relatório de transporte, em que posso ter mais de um conhecimento por placa (como é o caso do dia 26/09 na imagem), e diferentes placas no relatório, sempre mantendo os mais recentes.


Tabuada interativa - Deseja continuar? (S/N)

Question: Em um dos exercícios do curso que estou fazendo, adaptei o código de uma tabuada interativa onde, depois do usuário digitar um número para a tabuada e o programa executar, é oferecida a opção "Deseja continuar? (S/N)". Segue o código abaixo:

num = int(input('Digite o numero para a tabuada'))
for mult in range(1,11):
    print(f'{num} x {mult} = {num*mult}')

cont = str(input('Deseja ver a tabuada de outro número? (S/N) \n')).strip().lower()
s = 's' in cont
n = 'n' in cont

if s == True:
    num = int(input('Digite o numero para a tabuada'))
    print()
    for mult in range(1,11):
        print(f'{num} x {mult} = {num*mult}')

elif n == True:
    print()
    print('Um abraço e até logo! :)')

O problema que tive foi de não conseguir deixar ele dinâmico como, por exemplo, executar a opção "sim" até que o usuário digite a opção "não" e encerre o programa.
O que consegui escrever foi um looping correto de apenas duas vezes, mas a ideia seria encaixar um while para não deixar o código com muitas linhas.
Pergunta: Como faço para deixar a repetição ativa até que o usuário digite, por exemplo, 10 vezes a opção "sim" até que ele decida encerrar e, ao mesmo tempo, fazer isso com o menor número de linhas no código?
Comment: @AugustoVasques, vou deixar apenas a tua referência. Eu tinha aprendido que era má prática usar o `while true`. Boa sacada.
Comment: @AugustoVasques, obrigado!
Answer: Uma maneira de conseguir o resultado desejado é colocando o código que deseja dentro de um loop. E enquanto o usuário continuar respondendo que deseja continuar, manter o loop em execução.
Uma implementação possível seria declarar um bloco de repetição while true, executar o seu código e após a execução perguntar se deseja executar novamente,  caso o usuário responder que não, colocar uma condição de parada (condição de saída) para que o programa pare a execução. Finalizando a execução do código.
Veja o exemplo:
while True: #<-- bloco de repetição while true

    # seu código

    cont = str(input('Deseja continuar? (S/N)')).strip().lower() #<-- pergunta
    if cont == 'n': #<-- condição de parada
        break

print('Um abraço e até logo! :)')

Essa solução respeita o princípio DRY.

Se deseja uma solução que possui um pouco de redundância então pode executar pelo menos uma vez e após a primeira execução a gente mantém o usuário em um loop.
Da seguinte forma:
# seu código

cont = input('Deseja ver a tabuada de outro número? (S/N)') #pergunta
while not cont.lower() == 'n':

     # seu código

     cont = input('Deseja continuar? (S/N)')

print('Um abraço e até logo! :)')

Repare que na implementação acima, a regra do while está invertida em relação à regra do if (quando comparado com a primeira implementação). Que é evidenciado pela palavra chave not.
Para a implementação em Python, respeite sempre as indentações de escopo do código, pois em Python os espaços são significativos.
Comment: Só uma correção, o DRY não é uma boa ou má pratica, o Dry é um principio de programação ou seja, um proposição fundamental que serve de base para o cadeia de raciocínio de desenvolvimento de Software.. Classificar conceitos de  desenvolvimento com boas ou más práticas em geral é uma incoerência não evidenciada pois ao assumir que algo é uma boa prática você está assumindo que esse algo é válido para todos os casos. Quando ler ou ouvir que uma maneira específica de fazer as coisas é uma boa prática, pergunte-se quais os critérios e fontes de concessão do status de melhor prática?
Comment: `if 'n' in cont` não é uma boa forma de verificar, porque se vc digitar qualquer coisa que tenha um "n" no meio, vai entrar nesse `if` - digite, por exemplo, "banana" ou "123n456". Isso porque `a in b` verifica se a string `a` é uma substring de `b`. Neste caso, o melhor seria ver se é igual: `if cont == 'n'`. Quanto a essa história de "boa prática", reforço o que o @AugustoVasques disse. Infelizmente "boa prática" virou sinônimo de fanatismo religioso, que as pessoas seguem cegamente sem pensar. O melhor é entender o mecanismo, os prós e contras, e então analisar se faz sentido em cada caso.
Comment: @Luix78 Neste caso poderia ser algo assim: https://ideone.com/89sYiZ - Desta forma fica bem flexível, se quiser mais opções, basta adicionar em `opcoes_sim` e `opcoes_nao`. E complementando, `input` já retorna uma string, então fazer `str(input(...))` é redundante e desnecessário, não precisa de `str` neste caso.
Comment: @hkotsubo, deixei consistente nas duas implementações.
Comment: A resposta foi de @Danizavtz ou @augustovasquez? Estou me acostumando aqui com o SO.
Comment: eu copiei a do @augustovasquez a versão DRY da resposta, depois eu deixei uma outra maneira de resolver o problema, que não usa o DRY. Mais parecida com a sua pergunta original.
Comment: @hkotsubo no caso que você mencionou da letra "n", não ficaria intuitivo a pessoa digitar "sim", "não", "nao", "s",  S", "n" ou "N" e as funções built-in ".strip()" e ".lower()" não seriam suficientes para resolver esse problema? Pergunta honesta de iniciante mesmo. Abraços
Comment: Ok, entendido @Danizavtz
Comment: Excelente @hkotsubo


How is the proof that the Quartimax/Varimax-rotation converges?

Question: Empirically the quartimax-/varimax-rotation has proven useful and it was always converging in my applications. But from my readings years ago (most prominent S.Mulaik and K.Überla monographies on factor nanalysis)  I have a vague remembering, that the fact of a proof of convergence has been mentioned but I've never seen the actual proof.
Perhaps this is not difficult and may be done here, or does someone have a reference?
What I'm really after is the proof for the "inverse" of the quartimax: where the rotation is defined for the minimizing (instead of the maximizing) of the criterion; I hope I can use the quartimax-convergence-proof directly or at least have a path how to proceed with such a proof on my own...

[update] Hmm, I've got some hint to articles of ten Berge(1995, 60(3)) and of Jennrich(2001, 66(2)) (both appeared in "Psychometrika" that couple of years ago), which both seem to deal with problems of the convergence of that rotation - so this seems not to be trivial (or as easy as I hoped it would possibly be)...
(Unfortunately, I shall not have access to our library before monday)
[late update]: I should have added, that I've also tried to get more references in mathoverflow and gave a bit more discussion in this question, however also without conclusive result.
Comment: Mulaik (2010, p. 304) said, for Quartimax algorithm, "No proof has ever been offered that such an iterative procedure will always converge, but with empirical structure matrices it always has".
Comment: FYI: Somebody once mentioned me Suitbert Ertel, Factor Analysis: Healing an Ailing Model; and a "varimin" criterion to obtain "complex structure" found in GPArotation R-package. Maybe you find it interesting for your problem, but I've not read the stuff.
Comment: @ttnphns : ahh, very nice. I'll try to get that text, thank you!
Comment: @ttnphns : so my rememberings were roughly correct so far... Possibly such a proof were identical/had identical difficulty as the proof in the Hadamard-matrix question. So something is still there in the orthogonal (FA-) rotations, where some bright mind could involve himself... :-)  Thank you very much for looking for the reference! - Ah, and if you make this an answer I could "accept" that.
Comment: Just asking question of vanity (as from me a practicioner, not mathematician)... Why do you need a proof? If you are going to write your own factor-rotation procedure and in many many realistic simulations it then show convergence - why require a proof?
Comment: @ttnphns : As a practicioner myself I'll be happy to have a nicely working function, provided by some mathematician, to work with and possibly even to be able optimize its use. But I would hate it if that mathematicians gave me some instruments and they didn't make sure that I can safely rely on them. *At least* it should be made ***explicite*** whether or not the desired properties are existent or not or under what circumstances they are usable - and I found this declaration only at S.Mulaik so far. (...)
Comment: (...) (Maybe I'm also infected by my hobby from the last 10 years doing number theory... but that may be another story... :-) )
Answer: Working with othogonal eigenvector matrices M (created as random rotation matrices) a sequence of experiments suggested, that "varimin"-rotation (which is just minimizing the same criterion which "varimax" maximizes)  can run into local extrema and miss the global minimum, and does this more often as the matrix-size is increased.
I used 4x4 up to 22x22 matrices M and produced 1000 and more randomly created examples of the same size, trying to rotate them to "minimal variance of the squared matrix-entries".

For sizes n=4k the "varimin" rotation found always the "Hadamard"-matrix versions.
For sizes n=4k+2 that rotation found sometimes the "Weighing-matrices" with entries from $(1,0,-1)$ (when appropriately rescaled). However, when the dimension went to 18x18 I got that ideal solutions only in roughly 2 percent of the random examples; and for 22x22 matrices that was even less frequent.
Here I checked the improvement of the rotation-criteria for each single iteration and stopped, when the improvement became just marginal but the distance from the optimal versions was still far away.
For sizes n x n with n=2k+1 the rotations found sometimes versions which reminded of Hadamard- resp. Weighing- matrices, however had 4,5 or more different entries. For instance for n=13 I got in 80 percent of all examples rotated matrices with only 4 siginificantly different entries in the form $(1,a,-a,-1)$ but for n=11 that result occured only in 1 to 2 percent of examples.

Well, I considered then, that possibly such examples, which did not rotate to the "simple" structure of Hadamard or Weighing matrix having $(1,-1)$ or $(1,0,-1)$ or at least having few-categories-solutions like $(1,a,-a,-1)$ , just are incompatible with suchoptimal solutions. But for the matrix-sizes ( n=4k+2 ) for which I got both types of results, also the bad results could be transformed to an ideal solution by just (the correct) rotation.
The last observation let's me thus conjecture, that indeed "varimin" is not guaranteed to find the solution with the smallest variance in the squared matrix-entries, and the same should then be valid for the "varimax"-rotation in their intention to find the maximal variance.
Well, this experiments were done on orthogonal random-matrices, which are also eigenvector matrices for correlation-matrices. Rotation in factor-/component-analysis is usually done on loadings, which are rescaled entries of the eigenvectors - but there are also software packets which indeed rotate on the eigenvectors.


Show that the sum of the products in pairs of the number 1,2,3...p-1 is divisible by p, where p is prime

Question: If $p ≥ 5$ is prime, show that the sum of the products in pairs of the
numbers $1, 2, . . . , p−1$ is divisble by p. We do not count $1×1$, and
$1 × 2$ precludes $2 × 1$.
Answer: HINT:
If the sum of of the products in pairs $=P,$
as $(a+b+c+\cdots)^2=(a^2+b^2+c^2+\cdots)+2(ab+bc+ca+\cdots)$
$$2P=(\sum_{r=1}^{p-1}r)^2-\sum_{r=1}^{p-1}(r^2)$$
$$=\left(\dfrac{p(p-1)}2\right)^2-\dfrac{(p-1)p\{2(p-1)+1\}}6$$
As prime $p\ge5,(p,6)=(p,2)=1$  so $\dfrac{p-1}2$ and $\dfrac{(p-1)(2p-1)}6$ are integers
Do we really need $p$ to be a prime, will $(p,6)=1$ not suffice?
Comment: This actually follows from Newton's Identities.
Comment: Thats pertty clever! $$\sum\limits_{r=1}^{p-1}\sum\limits_{r'=1}^{p-1}rr' = \left(\sum\limits_{r=1}^{p-1}r\right)\left(\sum\limits_{r'=1}^{p-1}r'\right)$$
Answer: $1,2,\ldots,p-1$ are the $p-1$ roots of the polynomial $x^{p-1}-1$ modulo $p$. By Vieta's formulae, the mentioned sum is congruent (modulo $p$) to the coefficient of $x^{p-3}$ in $x^{p-1}-1$, which is $0$.
Note that this relies on the fact that $\mathbb Z/p\mathbb Z$ is a field.


Does the integral converge

Question: How to prove that the following integral doesn't converge?
$$\int_0^\infty \frac{1}{(\ln^4x + \ln^2x)\ln^2(1-x^{1/3})^2(x + \sqrt{x} + 1)}dx$$
I suppose it doesn't converge because of quick growth rate of function at $x = 0$, but I can't prove that.
Answer: Hint: $0$ is not the problem for convergence. Consider what's happening at $1$ instead.

Does the integral converge


Qual é a diferença das continuações do Scheme para as de outras linguagens?

Question: Já ouvi dizer que o Scheme possui "continuações de primeira classe", enquanto outros Lisps (e outras linguagens) não têm. Eu pesquisei sobre isso, mas o material que encontrei não era específico.
O que eu entendi é que continuações são como as funções de callback no Node.js, mas com um propósito diferente. Por exemplo, sem continuação:
(define (ao-quadrado x)
  (* x x))

E com continuação:
(define (ao-quadrado x cont)
  (cont (* x x)))

Existe mais alguma diferença? Eu perdi algo no caminho?
Answer: As continuações em Scheme são como que closures aumentadas que capturam a pilha de retorno, o ambiente e o ponto de execução actual.  Noutras linguagens, como JavaScript, continuações são "meras" funções ou closures que capturam o ambiente à volta.
Desta forma, é possível, por exemplo, pegar numa função de mapeamento, que tipicamente chama uma função para cada elemento, e fazer um iterador, que é chamado para retornar o elemento seguinte:
(define (my-hash-iterator a-hash)
  (let ((return-values #f)
        (read-value #f))
    (lambda ()
      (let/cc iteration
        (set! return-values iteration)
        (if read-value
            (read-value)
            (begin
              (hash-table-for-each a-hash
                                   (lambda (key value)
                                     (let/cc cont
                                       (set! read-value cont)
                                       (return-values #t key value))))
              (set! read-value #f)    ; iterador volta ao início se chamado novamente
              (return-values #f #f #f)))))))

A ideia é entrar na função dada à hash-table-for-each e apanhar uma continuação lá dentro, (set! read-value cont), que quando invocada, a fará retornar para hash-table-for-each.  A continuação de fora é para retornar cada um dos valores à vez.
Answer: As funções callback do nodejs não um caso particular de continuações. "Continuação" é um termo mais genérico que isso.
Traduzindo da wikipedia:

Uma continuação é uma representação abstrata do estado do fluxo de execução de um programa. Uma continuação reifica o controle de fluxo implícito em uma função explícita

Por exemplo, suponha que eu esteja fazendo a seguinte conta:
(define (conta)
  (* (+ 1 2) 4))

Existe uma ordem implícita do controle de fluxo quando eu executo essas operações. Eu pósso explicitá-la convertendo o programa pra single assignment form:
a <- 1 + 2
b <- a * 4

Continuações são uma maneira de representar essa ordem de execução implícita. Dado um ponto no código, a continuação desse ponto é uma função que representa o que vai acontecer no futuro. Por exemplo, a continuação do ponto da operação de soma na terceira linha é uma função (lambda (a) (a * 4))
Uma coisa que podemos fazer com continuações é escrever nosso programa de forma que as continuações aparecem explicitamente. Isso se chama Continuation Passing Style e é o que as pessoas fazem no Nodejs. No nosso exemplo, isso seria usar operações como +-cps e *-cps ao invés de + e * que retornam valores:
(define (conta-cps cont)
  (+-cps 1 2 (lambda (a)
    (*-cps a 4 cont)))

Programar assim tem alguns benefícios. Por exemplo, com continuações você pode "pausar" a execução do código. Basta pegar a continuação e salvar ela em alguma estrutura de dados e chamar ele de volta depois. Continuações também permitem que você implemente alguns mecanismos de controle você mesmo, como "return" , "try-catch" e iteradores.
O problema é que é um saco converter todas as suas funções para CPS na mão. É aqui que entram as continuaçÕes de primeira classe, usando o call-with-current-continuation (call/cc) você pode escrever seu código sem continuações mas você tem acesso às continuações como se você tivesse escrito o código em CPS.
Não vou dar exemplos de call/cc porque eu acho que o código fica muito complicado. Na prática você pode usar outras ferramentas menos poderosas que te dão benf;icios similares (poder pausar e reiniciar a execução do programa, etc). Por exemplo, em Scheme existem continuaçÕes delimitadas, em Python você tem geradores e em Lua você tem corotinas.


What thread does after finishing sleeping? while thinking leetcode question: Print in Order

Question: I am doing leetcode question: https://leetcode.com/problems/print-in-order/ and try different solution here:
// Solution 1:
// 25 ms time
// The first solution is slower? Probably because waking up a thread is more costly. The second solution is more close to positive lock.
class Foo {

     int lockSecond = 0;
     int lockThird = 0;

    public Foo() {

    }

    public synchronized void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        this.lockSecond = 1;
        notifyAll();
    }

    public synchronized void second(Runnable printSecond) throws InterruptedException {

        for (;this.lockSecond == 0;) {
            wait();
        }

        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        this.lockThird = 1;
        notifyAll();
    }

    public synchronized void third(Runnable printThird) throws InterruptedException {
        for (;this.lockThird == 0;) {
             wait();
        }
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
        notifyAll();
    }
}
//Solution 2:
//10 ms there is no valotile, which means thread will retieve latest value when finishing sleeping
class Foo {

    int lockSecond = 0;
    int lockThird = 0;

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        this.lockSecond = 1;
    }

    public void second(Runnable printSecond) throws InterruptedException {

        for (;this.lockSecond == 0;) {
            Thread.sleep(1);
        }

        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        this.lockThird = 1;
    }

    public void third(Runnable printThird) throws InterruptedException {
        for (;this.lockThird==0;) {
           Thread.sleep(1);
        }
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}
// same as second solution,
//Solution 3:
class Foo {

    volatile int lockSecond = 0;
    volatile int lockThird = 0;

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        this.lockSecond = 1;
    }

    public void second(Runnable printSecond) throws InterruptedException {

        for (;this.lockSecond == 0;) {
        }

        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        this.lockThird = 1;
    }

    public void third(Runnable printThird) throws InterruptedException {
        for (;this.lockThird==0;) {
        }
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}

I can understand we use volatile to make the var shared across different thread in solution 3 to avoid the endless loop. If I remove volatile, Leetcode will say exceeding time limit.
But for solution 2, I can remove volatile if I use sleep.
Does this mean thread will always re-read value of variable after finishing sleep, which avoid the time limit issue?
Not familiar with multi-threading, there might be misleading comments in the code snippet. Welcome any correcting!
----------------------Update --------------------------------
It has nothing to do with sleep() actually. It is up to whether there is statement in the for loop body. If I replace sleep with println(), it still passes test cases. If it is empty, it will exceed time.
Actually in my opinion, if there is no valotile keyword. It will get into endless loop since different thread share no visibility but it doesn't. It just gets slower. When there is a statement, it can even pass the tests case of leetcode
Comment: Actually, it is nothing about sleep. If I put print line in the for loop body, it still passes. Without anything in the for loop, it succeeds at some test cases still but cannot pass all test cases
Answer: Thread.sleep(n) is not guaranteed to do anything except not return until either n milliseconds have elapsed, or the calling thread was interrupted. Anything else that happens when you call it either is a peculiarity of whatever JRE, JVM, and OS version you are using, or else it's a roll of the dice on whatever JRE, JVM, and OS version you are using.
If your code depends on sleep() for any kind of synchronization or coordination between different threads, then you are taking a risk that it won't work everywhere and/or it won't work every time.
Comment: @StanPeng, [Java's "memory model"](https://docs.oracle.com/javase/specs/jls/se14/html/jls-17.html#jls-17.4) makes no promises about what will happen if your program breaks the "happens before" rules. It only says what will happen if your program obeys them. If you have a program that breaks the rules, it might work today, but not tomorrow. Or, it might work 9999 times out of every 10000. Or, it might work before you accept some OS upgrade but not after. Or, it might work when it is the only program running on the box, but not when some other program is running, etc., etc., etc.
Comment: It has nothing to do with sleep() actually now. It is up to whether there is statement in the for loop body. Actually in my opinion, if there is no valotile keywor. It will get into endless loop but it doesn't. It just get slower. When there is a statement, it can even pass the tests case of leetcode


Subsets $S$ such that $7 \notin S $ or $2 \notin S $

Question:
How many subsets $S \subseteq\{1,2...10\}$ are there such that $7 \notin S $ or $2
 \notin S $?

I can't find the right way to write a formal response. I think that we should consider at least $18$ subsets, deleting once $2$ and once $7$ from the entire set. Then we should consider all the pairs and triples excluding the same two elements and so on. I'm really confused, any tips?
Answer: Another possible method:
How many subsets of $\{1,2,3,4,5,6,7,8,9,10\}$ are there in total? Call this number $n$.
How many subsets contain both 2 and 7? This is the same as the number of subsets of $\{1,3,4,5,6,8,9,10\}$. Call this number $m$.
Then your solution is $n - m$.
Answer: Hint:

How many subsets are there containing neither $2$ nor $7$?
How many subsets are there containing $2$ and not $7$?
How many subsets are there containing $7$ and not $2$?

For the second one, any subset must be a union of $\{2\}$ and any subset of $\{1,3,4,5,6,8,9,10\}$. Can you say something similar for the other two?
Comment: Check the edit, I changed symbol.
Comment: I've corrected the answer
Answer: Hint:
Let $S' = \lbrace 1,3,4,5,6,8,9,10\rbrace$. How many subsets does $S'$ have? Call $n$ that amount.
To any of those subsets, you can add $\lbrace 2\rbrace$ or $\lbrace 7\rbrace$ or neither to have any of the desired subsets. So you have $3n$ subsets of $S$ that don't contain $2$ or $7$.
Answer: Hint:
How many subsets has set $\{1,\dots,10\}$ in total?
How many of these subsets $S$ satisfy $2\in S$ and $7\in S$?
So how many do not?


Probability a coin is heads given 5 heads and distribution

Question:
A machine produces a weighted coin that lands on heads with an unkown
probability $p$, and we know that $P(p\le x) = x^4$.  You flip the
coin $5$ times, and every time it lands on heads.  What is the
probability that the next flip will also land on heads?

I am not exactly sure how to tackle this problem. I attempted going a conditional probability route, but was not sure what to put as the values for the numerator and denominator. It looks like the probability the coin is less than x is a cumulative distribution function, but I don't know if that intuition is correct or helpful. How should I go about solving this?
Answer: $F(x) = x^4, f(x) = 4x^3$, $P(N = 5 \mid p = x) =  x^5$.
Define $H(x) = P(p\leq x\mid N = 5) = \int_0^x h(t)\,dt$. Since
$
P(N = 5) = \int_0^1 P(N = 5 \mid p = t)f(t)\,dt
=\int_0^1 t^5 f(t)\,dt
= \frac{4}{9},
$ the density is
$$
h(x) = P(p=x\mid N = 5) = \frac{P(N=5\mid p = x) f(x)}{P(N=5)} = x^5 4 x^3\frac{9}{4} = 9 x^8.
$$
Therefore $
E[p \mid N = 5] = \int_0^1 x h(x) dx
= 9 \int_0^1 x^9 dx = \frac{9}{10}.
$
Perhaps its easier to calculate
$P(N^+ = 6) =\int_0^1 t^6 f(t)\,dt= \frac{2}{5}$
and
$$
P(N^+ = 6 \mid N = 5) = \frac{P(N^+ = 6 \cap N = 5)}{P(N=5)} = \frac{2/5}{4/9} =\frac{9}{10}
$$
but this does not give the distribution of $p$.
Comment: Why is $P(N = 5 | p = x) = 1 - (1 - x^5)$ instead of just $x^5$? Wouldn't what you put describe all cases where not all 5 flips were tails?
Comment: I agree! This perhaps explains why the calculations became so complicated.
Answer:
It looks like the probability the coin is less than x is a cumulative distribution function,

Indeed.
We have the CDF for $p$, which gives us the pdf.
$$\begin{align}
 F_p(x) &= x^4\,\mathbf 1_{0\leq x\lt 1}~+~\mathbf 1_{1\leq x}
\\[2ex]
 f_p(x) &= 4x^3\,\mathbf 1_{0\leq x\leq 1}
\end{align}$$

I attempted going a conditional probability route, but was not sure what to put as the values for the numerator and denominator.

You have the evidence, and the prediction.
Let $E$ be the event of the evidence ($5$ flips that result in $5$ heads).   Now the conditional distribution for this given a $p$ is binomial: $(E\mid p\,{=}\,x)\sim\mathcal{Bin}(5,x)$ .
$$\mathsf P(E\mid p=x) = \binom 55 x^5 \,\mathbf 1_{x\in[0,1]}$$
  Thus the marginal probability for $E$ is the exponential:
$$\mathsf P(E) = \int_0^1 \binom 55\, x^5\cdot f_p(x)\,\mathrm d x$$
Let $N$ be the event that the next flip is also heads.   Likewise we find:
$$\begin{align}\mathsf P(N\cap E\mid p=x) ~&=~ \binom 66 x^6 \,\mathbf 1_{x\in[0,1]}
\\
\mathsf P(N\cap E) ~&=~ \int_0^1 \binom 66\, x^6\cdot f_p(x)\,\mathrm d x\end{align}$$
So...
We seek the probability for the next coin toss being heads given that the prior five were heads, which is to say $\mathsf P(N\mid E)$.   This is, by definition:
$$\mathsf P(N\mid E)=\dfrac{\mathsf P(N\cap E)}{\mathsf P(E)}$$


Finding the volume of solid bounded by planes $x-2y+z=12$, $z=0$, $x=0$, and $y=x$. Trouble setting up double integral.

Question: I want to find the volume of the solid bounded by the planes $x-2y+z=12$, $z=0$, $x=0$, and $y=x$, but I'm having a hard time setting up the double integral that will be evaluated to find the volume. I'll show my work up until I get stuck.
Step #1)
Describe what is known:

$x-2y+z=12 \rightarrow z=-x+2y+12$ which is what the solid is
"under."
$z=0$ is the $xy$-plane, meaning the solid will not go past/below that.
$x=0$ is the $yz$-plane, meaning the solid will stop there/not go past
that.
$y=x$ is a line in $2D$ but this will be a plane in $3D$, obviously, it also bounds the solid.

Step #2)
Graph everything to get an idea of what is going on (sorry for non-digital):
Graph of $z=0,\;\;\;x=0,\;\;\;y=x$ all together

The one above is of the plane $x-2y+z=12$.
This is about where I get stuck. I don't know how to get my region $D$, but I do know what I will be integrating just not the limits of it:
$$V=\iint_D(12-x+2y)\,dA$$
where the stuff being integrated is the equation/plane that the solid is under. This might be too abstract, but when I set the $-x+2y+12$ equal to zero and solve for $y$, and then graph both that and $y=x$ they intersect in a different quadrant than the one that I drew $x-2y+z=12$ in.
I wish I could show more work, but this is where I'm stuck. I'm sure that when I figure out how to get the limits I will be able to integrate it easily.
Thanks for any help!
EDIT: Will this be my region D? [$y={x\over 2}-6$ and $y=x$] The whole thing? Nothing intersects it so I would assume so.
Answer: First of all, your depiction of the plane $x=0$ is wrong. In the two-dimensional $xy$-plane, $x=0$ is the equation of the $y$-axis, not the $x$-axis. So in the three-dimensional space, $x=0$ is the vertical plane containing the $y$-axis, not the $x$-axis. Because of that, the correct region $D$ will be the third-quadrant part of what's on your last picture (in the edit).
Comment: Great catch! Thank you! That means my dy limits will be from $y={x\over 2}-6$ to $y=x$. My dx limits will be from $x={x\over 2}-6 \rightarrow 2x=x-12 \rightarrow x=-12$ to $x=0$.
Comment: @JustHeavy: Yep, that sounds right.


What is a BPMS?

Question: What is BPMS? and when to go for BPMS? is there any free tools for .net or java? is there any plug-in available for eclipse?
Comment: What is a BMPS? http://www.google.com/search?q=bpms
Comment: Homework indeed. Very tempted to put in a "let me google that for you" link - but to be helpful - https://tallyfy.com/guides/business-process-management-bpm/
Answer: It is short for Business Process Management System or Software and basically is a tool for very high level modelling how the business will do whatever they do and how automation tools are integrated.
These things are typically huge and composed of a big collection of tools and infrastructure stuff. Eclipse based tooling may be a part of that, but it is much larger than just a plugin.
If you want to dip your toe in these waters you might look at JBoss Tools which has support for JBPM and Webservices which is a workflow package and the infrastructure which is usually core to these systems.
Good Luck!
Answer: As Peter said, BPMS is a huge topic. To get an idea of its scope, check out IBM's home page on it here: http://www-142.ibm.com/software/products/us/en/category/bpm-software
Answer: Have a look at the Activiti BPMN 2.0 engine. It is still in beta but a project everybody interested in BPM software should know about. It is implemented in Java and an Eclipse plugin also will be part of the set of tools.
Answer: Stardust, the Eclipse Process Manager,is a comprehensive and mature BPMS which is part of the  Eclipse release train since the Kepler release. With over 2.5M lines of code and 726 person years Stardust is the largest Open Source BPMS.
As opposed to many Java-centric BPMS, Stardust also provides proven .NET integration capabilities on servcie and UI level.
The process modeler is avalibe for Eclipse or purely browser-based. The runtime environment can be used from inside Eclipse (WTP integration) or standalone (maven build).
Please see http://www.eclipse.org/stardust/ for more details.
Best regards
Rob
Answer: BPM - Business Process Management is a systematic approach to streamline an organization's process to make it efficient and  effective, to suit the changing environment around.

What is a BPMS?


Como organizar um array por tamanho automaticamente?

Question: Eu estava querendo criar um sistema de ranking. Para isso eu pensei em colocar todos os valores dentro de um Array e depois por meio de uma função organizá-lo do maior para o menor. Porém, cada vez que faço cada posição, eu sempre tenho que fazer um código maior (e eu não sei quantos registros terão). O código seria semelhante a isso :
<?php
  // essa função recebe um array como parâmetro
  function ordenaArray($array){
     $arrayOrdenado = array();
     $indice = 0;
     $maior = 0;
     for($i = 0; $i <= count($array); $i++){
       if($array[$i] >= $maior){
           $maior = $array[$i];
       }
     }
   $arrayOrdenado[$indice] = $maior;
   $indice++;
  }
?>

Eu consigo fazer isso para todos os registros, mas como eu nunca vou saber quantos registros terão, vou continuar fazendo isso para vários outros registros.
Tem alguma maneira de fazer isso mais dinamicamente?

Para quem ainda não entendeu, eu quero que um array x=(1,4,3,2,5,6,9,8,7,0) vire um array y=(9,8,7,6,5,4,3,2,1,0)
Comment: função [`sort`](http://php.net/manual/pt_BR/function.sort.php)
Answer: Existe uma função que inverte o array em PHP, que se chama array_reverse:
<?php
$input  = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>

Pelo que entendi ela te atende.
Caso precise ordenar primeiro use desta forma:
<?php
 $array = array('d', '1', 'b', '3', 'a', '0', 'c', '2');

 sort($array); // Classifica o Array em ordem Crescente.

 print_r($array); // Resultado: Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => a [5] => b [6] => c [7] => d )

 echo '
';

 rsort($array); // Classifica o Array em ordem Decrescente.

 print_r($array); // Resultado: Array ( [0] => d [1] => c [2] => b [3] => a [4] => 3 [5] => 2 [6] => 1 [7] => 0 )
?>

O comando sort() fará o trabalho.
Ou seja:

Se quiser ordenar use sort
Se quiser inverter use rsort
Comment: a problema não é nem inverter o array, e sim ordená-lo  na sequencia correta
Comment: Acrescente mais detalhes, o comando sort ordena o array
Comment: cara, é exatamente isso que eu precisava, muito obrigado!
Comment: nada precisando tamos aê. :)
Comment: se puder marcar como certa e dar upvote :)


Why is $f^{(n)}(z)$ real when z is real for all $n$, if this is true for $n=0$?

Question: In order to prove the Schwarz Reflection Principle using the Taylor expansion, we need the information that $f^{(n)}(z)$ is real if $z$ is real for all $n$. We have $f(z)$ real if $z$ is real, and that $f(z)$ is analytic over a region including the real axis. How do these imply that the $n^{th}$ derivative is also real?
Answer: If $z_0 \in \mathbb{R}$
$f'(z_0) = \lim_{h \to 0} \frac{f(z_0 + h) - f(z_0)}{h}$
If $f'$ exists, this limit must be the same if $h$ approaches from the real or imaginary axis, that said:
$f'(z_0) = \lim_{h\to 0\ h \in \mathbb{R}}  \frac{f(z_0+h)-f(z_0)}{h} \in \mathbb{R}$
$f^{(n)}$ follows the same reasoning.


Java Timestamp e MySQL Timestamp

Question: Problema:
Estou armazenando um timestamp no MYSQL, porém quando resgato esse timestamp estou perdendo os milésimos.
Timestamp do Java com milésimos.

Timestamp do MYSQL sem milésimos.

Por que isso ocorrer?
Como resolver isso?
Preciso do retorno com esses milésimos.
editado:
Acredito que o mysql 5.1.62, não guarde os milesegundos, então parte pra minha solução seria capturar o timeStamp e remover os milliseconds, qual forma eficiente para fazer isso?
Comment: Acredito que o date time do MySQL não chegue a esse nível de precisão. Sei que no SQL Server existe o tipo `datetime2` com esse nível de precisão
Comment: Por curiosidade: que aplicação você está desenvolvendo que precisa desse nível de precisão (milisegundos)?
Comment: Posso ficar sem os milsegundos do timestamp, mas como desenvolvedor seria interessante entender esse comportamento.
Outra questão é que de todas as formas que tentei obter o timestamp no Java ele vem com milisegundos.
`System.currentTimeMillis()`, `Calendar.getInstance().getTimeInMillis()`, `new Date().getTime();` e `new Timestamp().getTime();` não queria ter que remover os milisegundos na marra.
Comment: Versão do MySQL ? Segundos fracionados é uma feature nova no MySQL: http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-4.html
Comment: A versão do meu MySQL é 5.1.62, qual a melhor forma de pegar um timestamp no Java onde consiga sempre zerar os milesegundos, assim parte do meu problema acaba.
Answer: Respondendo sua pergunta:

qual a melhor forma de pegar um timestamp no Java onde consiga sempre zerar os milesegundos?

Para os casos:

System.currentTimeMillis(), Calendar.getInstance().getTimeInMillis(), new Date().getTime(); e new Timestamp().getTime();

Você diz não querer remover na marra, não sei bem o jeito que você usou, mas a forma mais simples que imagino fazer isso é dividindo por 1000 e em seguida multiplicando por 1000. Assim você desconsidera os últimos três dígitos da sua data, que correspondem ao milisegundos. Assim:
new Timestamp((System.currentTimeMillis()/1000)*1000);

Exemplo:
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

public class TesteTimestamp {
    public static void main(String[] args) {
        timestampComMili(System.currentTimeMillis());
        timestampSemMili(System.currentTimeMillis());

        timestampComMili(Calendar.getInstance().getTimeInMillis());
        timestampSemMili(Calendar.getInstance().getTimeInMillis());

        timestampComMili(new Date().getTime());
        timestampSemMili(new Date().getTime());

        //timestampComMili(new Timestamp().getTime());
        //timestampSemMili(new Timestamp().getTime());
        /* O código acima não é possível, pois não existe um
         * construtor padrão a classe Timestamp. Veja em:
         * http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html
         */
    }
    public static void timestampComMili(long l) {
        System.out.println("Com mili: " + new Timestamp(l));
    }
    public static void timestampSemMili(long l) {
        System.out.println("Sem mili: " + new Timestamp((l/1000)*1000));
    }
}

Resultado:

Com mili: 2014-09-16 09:48:41.186
  Sem mili: 2014-09-16 09:48:41.0
  Com mili: 2014-09-16 09:48:41.198
  Sem mili: 2014-09-16 09:48:41.0
  Com mili: 2014-09-16 09:48:41.198
  Sem mili: 2014-09-16 09:48:41.0
Comment: Ajudou bastante, a ideia de não ter os "mili" é por que sempre dava diferença em comparação de datas por causa dos "mili", mas já está resolvido.

Exemplo populava um objeto, o timestamp do objeto tinha os "mili", passava para o banco e depois fazia uma consulta para saber se tudo foi cadastrado com sucesso. Quando ia comparar os objetos com o equals ou de qualquer outra forma, justamente os "mili" do primeiro objeto eram diferente do retorno do banco. Então acabava ignorando as "datas", mas com isso posso comparar os "timestamp". O banco guarda os "mili". Meio bobo, mas aconteceu. haha
Answer: No MySQL 5.6 você já conseguiria precisão de milisegundos.
tente
select sysdate(6) vai retornar 2013-04-16 13:47:56.273434
e
select sysdate(3) vai retornar 2013-04-16 13:47:56.273

Mas caso não queira migrar para o MySQL 5.6, você pode usar a função DATE_FORMAT().
Segue um exemplo:
DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p') resultado: Aug 19 2014 12:45 PM
DATE_FORMAT(NOW(),'%m-%d-%Y')          resultado: 08-19-2014
DATE_FORMAT(NOW(),'%d %b %y')          resultado: 19 Aug 14
DATE_FORMAT(NOW(),'%d %b %Y %T:%f')    resultado: 19 Aug 2014 12:47:10:214

Comment: Perco os milesegundos quando cadastro o timestamp, por tanto mesmo que consiga usar o `DATE_FORMAT(create_in,'%d %b %Y %T:%f') ` não daria certo. Nesse caso pode até funcionar por que usa o NOW() é uma DATA completa.

Java Timestamp e MySQL Timestamp


como mudar uma coluna que e chave primaria para identity?

Question: Bom eu fiz uma tabela no sqlserver e coloquei a chave primaria como int normal porem preciso alterar ela pra identity. como faço??
Comment: precisa excluir a coluna atual e incluir uma nova, como `identity`
Comment: valeu me ajudo dms !
Answer: Você pode alterar via comando ou via Management Studio.
Via comando você terá que remover a coluna e adiciona-lá novamente:
<code>ALTER TABLE Cliente
DROP COLUMN Id

ALTER TABLE Cliente
ADD ID INT NOT NULL Identity(1,1)
</code>
via Management Studio:
Comment: Obrigado ajudou muito!!


JsonResult not returned even after OnResultExecuted called successfully

Question: I have a 'Session-Less' Controller with an action that returns JsonResult. My client side Javascript uses Jquery ajax to call this action via HTTP GET
[HttpGet]
public JsonResult Index()
{
    ....
    // myResult has three properties of type bool, int and a string

    var jsonResult = Json(myResult, "application/json", JsonRequestBehavior.AllowGet);
    return jsonResult;
}

This code gets executed and I have verified that OnResultExecuted is called without any exception.
Client side JS
xhrNotification = $.ajax({
            url: '/MyController/', // default action
            type: 'get',
            dataType: 'json',
            cache: false,
            async: true,
            success: function (n, timeout, message) {

            },
            error: function (data) {

            }
        });

But the jsonResult only occasionally gets to the client side. I have been observing the request/response using Fiddler. The HTTP request has no response even after my action is executed. I am developing this under Visual Studio 2010.
Any help is appreciated.
EDIT: On further debugging I found an exception is raised after my Action is executed
System.Net.Sockets.SocketException occurred
  Message=An established connection was aborted by the software in your host machine
  Source=System
  ErrorCode=10053
  NativeErrorCode=10053
  StackTrace:
       at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)

Partial stack trace is as below
System.dll!System.Net.Sockets.Socket.Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) + 0x5a bytes
    WebDev.WebHost40.dll!Microsoft.VisualStudio.WebHost.Connection.WriteBody(byte[] data, int offset, int length) + 0x40 bytes
    [Appdomain Transition]
>   WebDev.WebHost40.dll!Microsoft.VisualStudio.WebHost.Request.FlushResponse(bool finalFlush) + 0x128 bytes
    System.Web.dll!System.Web.HttpResponse.Flush(bool finalFlush) + 0x4cb bytes
    System.Web.dll!System.Web.HttpRuntime.FinishRequest(System.Web.HttpWorkerRequest wr, System.Web.HttpContext context, System.Exception e) + 0x80 bytes
    System.Web.dll!System.Web.HttpRuntime.OnHandlerCompletion(System.IAsyncResult ar) + 0xa6 bytes
    System.Web.dll!System.Web.HttpAsyncResult.Complete(bool synchronous, object result, System.Exception error, System.Web.RequestNotificationStatus status) + 0x3e bytes
    System.Web.dll!System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(System.Exception error) + 0x25e bytes
    System.Web.dll!System.Web.HttpApplication.ResumeStepsFromThreadPoolThread(System.Exception error) + 0x28 bytes
    System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.OnAsyncHandlerCompletion(System.IAsyncResult ar) + 0x183 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncUtil.WrapCallbackForSynchronizedExecution.AnonymousMethod__1() + 0x14 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.SynchronizationContextUtil.Sync.AnonymousMethod__3() + 0x16 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.SynchronizationContextUtil.Sync<System.Web.Mvc.Async.AsyncVoid>.AnonymousMethod__0(object o) + 0x32 bytes
    System.Web.dll!System.Web.AspNetSynchronizationContext.CallCallbackPossiblyUnderLock(System.Threading.SendOrPostCallback callback, object state) + 0x4a bytes
    System.Web.dll!System.Web.AspNetSynchronizationContext.CallCallback(System.Threading.SendOrPostCallback callback, object state) + 0x5f bytes
    System.Web.dll!System.Web.AspNetSynchronizationContext.Send(System.Threading.SendOrPostCallback callback, object state) + 0x9 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.SynchronizationContextUtil.Sync<System.Web.Mvc.Async.AsyncVoid>(System.Threading.SynchronizationContext syncContext, System.Func<System.Web.Mvc.Async.AsyncVoid> func) + 0x58 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.SynchronizationContextUtil.Sync(System.Threading.SynchronizationContext syncContext, System.Action action) + 0x46 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncUtil.WrapCallbackForSynchronizedExecution.AnonymousMethod__0(System.IAsyncResult asyncResult) + 0x6f bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<System.Web.Mvc.Async.AsyncVoid>.ExecuteAsynchronousCallback(bool timedOut) + 0x37 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<System.Web.Mvc.Async.AsyncVoid>.HandleAsynchronousCompletion(System.IAsyncResult asyncResult) + 0x1e bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<System.Web.Mvc.Async.AsyncVoid>.ExecuteAsynchronousCallback(bool timedOut) + 0x37 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<System.Web.Mvc.Async.AsyncVoid>.HandleAsynchronousCompletion(System.IAsyncResult asyncResult) + 0x1e bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<System.Web.Mvc.Async.AsyncVoid>.ExecuteAsynchronousCallback(bool timedOut) + 0x37 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<System.Web.Mvc.Async.AsyncVoid>.HandleAsynchronousCompletion(System.IAsyncResult asyncResult) + 0x1e bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<bool>.ExecuteAsynchronousCallback(bool timedOut) + 0x37 bytes
    System.Web.Mvc.dll!System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult<bool>.HandleAsynchronousCompletion(System.IAsyncResult asyncResult) + 0x1e bytes

Comment: the stack trace seems to indicate a spotty connection...  perhaps an issue with your dev environment setup and not the posted code?
Comment: @b1naryj. nope, he has to allow get. `return Json(myResult, JsonRequestBehavior.AllowGet)`
Comment: Nothing obviously wrong so far... What happens if request fails? Does client get at least an error message?
Comment: @SergeyKudriavtsev thanks. No, in Fiddler the request would never seem to receive a response. But occasionally it would work. I spent quite a while trying to resolve this before asking a question on SO. This problem is now resolved. Please see my answer. Appreciate your time.
Comment: @SergeyKudriavtsev Updated my post with the Jquery Ajax code.
Comment: @SergeyKudriavtsev Unfortunately this is not resolved. I have added the exception and stacktrace now to the question. Any help is appreciated...
Comment: @DmactheDestroyer I was wondering if it could be Firewall/Antivirus fiddling with the socket... I am looking in to this at the moment.
Answer: Try using this call and see what happens: (might want to make sure you set type to 'GET', not 'get')
$.ajax({
        type: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: '/MyController/',
        success: function (data) {

        },
        error: function(e) {
        },
        complete: function () {

        }
    });

Also, you may just want to do this in your controller:
return Json(myResult, JsonRequestBehavior.AllowGet);


red5 server-side sharedObject

Question: I'm trying to store all the users inside a sharedObject thats created on the server-side, so all the users get a synchronized list of all the online users.
I think I create the sharedObject correct on the server-side but I cant "find" the sharedObject in the flash application.
Inside the Java Red5 Application class:
ISharedObject userList;

public boolean connect(IConnection conn, IScope scope, Object[] params)
{
    if(userList == null)
    {
        createSharedObject(scope, "userList", false);
        userList = getSharedObject(scope, "userList");
    }

    userList.setAttribute( "user", "some name" );

    return true;
}

The Flash sharedObject looks like this:
private var _userSO:SharedObject;

private function initUserSO() // I call this function when I get a netConnection
{
    _userSO = SharedObject.getRemote("userList", this.uri, false);
    _userSO.addEventListener(SyncEvent.SYNC,syncUsers);
    _userSO.connect(this); // this = netconnection
}

private function syncUsers(e:SyncEvent):void
{
    MonsterDebugger.trace('userManager',_userSO.data);
}

But the _userSO doesn't seem to find the sharedObject on the server.
Answer: I found out that you could use the below line to execute as3 script instead of storing the data inside a sharedObject:
ServiceUtils.invokeOnAllConnections(room, "my_as3_function", userList);

Comment: It of course depends on your situation but in a lot of cases the SO approach is more efficient than calling a method on each connection.

red5 server-side sharedObject


Determine whether following series converge or diverge. If converges find its sum.

Question: $$\sum_{n=1}^{\infty}{\frac{(-1)^n n^2}{1 + 2 n^2}}$$
here is what I have done.
so when:

$n=1$ [for this term] it gives = - 1/3 or - 0.3333
$n=2$ gives 0.4444
$n=3$ gives -0.2923977
$n=4$ gives 0.484848

we values are alternating between +ves and -ves is this enough to say series is divergent?
and also as we are progressing some values are actually increasing eg 0.444 to 0.4848 which also gives a hint that it is divergent.
Answer: The terms of the series don't tend to $0$, so the series cannot converge.
Answer: The series is divergent because the sequence of its summands is not converging towards $0$ (which is a necessary condition for a series to converge). In fact it does not converge at all. The sequence of summands is given by $(-1)^n\frac{n^2}{2n^2+1}$. The $\frac{n^2}{2n^2+1}$ part converges towards $\frac{1}{2}$ because $\frac{n^2}{2n^2+1}=\frac{\frac{n^2}{n^2}}{2\frac{n^2}{n^2}+\frac{1}{n^2}}=\frac{1}{2+\frac{1}{n^2}}\to\frac{1}{2}$. Thus the original sequence $(-1)^n\frac{n^2}{2n^2+1}$ has two cluster points that is $\frac{1}{2}$ and $-\frac{1}{2}$ corresponding to the limits of the subsequences $(-1)^{2n}\frac{(2n)^2}{2(2n)^2+1}=\frac{(2n)^2}{2(2n)^2+1}\to\frac{1}{2}$ and $(-1)^{2n+1}\frac{(2n+1)^2}{2(2n+1)^2+1}=-\frac{(2n+1)^2}{2(2n+1)^2+1}\to-\frac{1}{2}$


Vertica timeseries seemingly starts on a random day

Question: I have a question concerning the TIMESERIES clause in Vertica. Suppose I have the following query:
SELECT ts
FROM
(
    SELECT '2011-10-01'::TIMESTAMP as tm
    UNION
    SELECT '2018-12-31'::TIMESTAMP as tm
) as t
TIMESERIES ts as '1 MONTH' OVER (ORDER BY tm)

This gives me the following results:
2011-09-30 00:00:00
2011-10-30 00:00:00
2011-11-29 00:00:00
2011-12-29 00:00:00
...

Then, if I put 2012-10-01 as the starting date, I end up with the following results:
2012-09-24 00:00:00
2012-10-24 00:00:00
2012-11-23 00:00:00
2012-12-23 00:00:00
...

As you can see, the first resultset starts on september 30th and the second starts at september 24th. Now I don't really have a problem with it starting in september. I do, however, have a problem with it starting on what seems to be a completely random day depending on what date I decide to start my interval with. This causes problems when the interval decides to start on the 30th or worse the 31st. Basically, all I want is to have my interval start on whatever date I specify like so:
2012-10-01 00:00:00
2012-10-31 00:00:00
...

Is such a thing possible without doing some ridiculously complex calculations?
Comment: How is this question different from [your earlier question](http://stackoverflow.com/q/33673887/679449)?
Comment: @Kermit I realize my two questions are similar. However, they address two different topics nonetheless. You see, in my earlier question, I merely wanted to know why there was an extra entry in my timeseries. Here it's more specific than that. I don't care about the extra entry at all. I want to know why, when I say "start on 2011-10-01" (as in the first day of the month), the series says "screw it, I'll start on the 30th instead". And then, if I say, start on 2012-10-01 (still the first day of the month, but one year later), the series says "screw it, I'll start on the 24th".
Answer:
Then, if I put 2012-10-01 as the starting date, I end up with the following results

Note that both time series (starting at 2012-10-01 and 2011-10-01) produce the same dates. The point of TIMESERIES is to provide consistent intervals between points, which is not possible with Gregorian months.

Though it makes me wonder why timeseries bothers with interpolating something that's been given outright.

TIMESERIES is not concerned with using the start/stop boundaries you supply it. This particularly would be infeasible when you're expecting jumps by different intervals (actual months).
As I noted in your last question, '1 MONTH' is really 30 days, which leads to problems like this:
 2017-01-31 00:00:00
 2017-03-02 00:00:00

Where there won't be an entry for February.
Answer: From the docs:
'length_and_time_unit_expression'
Is INTERVAL (DAY TO SECOND) that represents the length of time unit of time
slice computation; for example, TIMESERIES slice_time AS '3 seconds' ...

So INTERVAL (YEAR TO MONTH) is not supported which is probably why you see funky gaps (my bet is that there is some kind of modulo bucketing going on at the unix epoch value of the date bringing the start date back in time).
You could do something dirty like abuse the timeseries by day to generate a sequence that you add back to the original date.  Cleaner would be to create some kind of date dimension table. Maybe someone has a more clever way than this.
select add_months('2012-10-01'::timestamp,timestampdiff('dd',to_timestamp(0),ts))
from (
  select to_timestamp(0) as tm
  union all
  select to_timestamp(0) + timestampdiff('mm','2012-10-01'::timestamp,'2018-12-31'::timestamp)
) as t
timeseries ts as interval '1 DAY' over (order by tm)

Comment: Yeah, we did end up using a day interval for our query. It proved to be way more stable than using a month interval. You can check it out at [my other question](http://stackoverflow.com/questions/33673887/vertica-date-series-is-starting-one-month-before-specified-date) . Though it makes me wonder why timeseries bothers with interpolating something that's been given outright.
Comment: @Osuwariboy This will give you monthly buckets starting on the day you put in by using `1 DAY` timeseries to generate a sequence that we add back as a month. As for why using `MONTH` doesn't work, the docs say it expects a `DAY TO SECOND` so simply `MONTH` is not supported and I'm surprised it didn't just error out.


log4net issue when F# script calls C# exe

Question: I got an C# exe which writes log4net logs. If I run this exe directly, the logging works ok.
However, if I call the exe from a F# script (with extension fsx), I have the error
log4net:ERROR Failed to find configuration section 'log4net' in the application'
s .config file. Check your .config file for the <log4net> and <configSections> e
lements. The configuration section should look like:

anyone can help? thanks a lot
Comment: Can you include the F# code that is calling the C# exe in your question?
Answer: You should insert configuration of this exe file to configuration file of your f# application or initialize logger in code. I am not sure that when you run f# script there are config file.
You can try to set config to configfile of your c# exe with code:
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "c:/test.config);

Comment: F# scripts are run by F# Interactive (fsi.exe).
Comment: thanks, i know. You can try to set config to config file of your c# app with AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "c:/test.config");
Comment: I just meant that the relevant config file for an F# script will be fsi.exe.config.
Comment: I'm not sure that this will work... Try to setup in code config as i wrote.
Comment: found out that you just cannot rely on default or current directory when invoking a piece of code from another piece of code.
Answer: When you call your C# .exe from F# Interactive, the current working directory -- which is where .NET will try to load the .config file from -- is the directory where F# Interactive is installed.
In your F# interactive script, do something like this:
// Change the current directory to the directory where the
// C# assembly was loaded from.
System.Environment.CurrentDirectory <-
    // TODO : Change 'MyType' to any public type from your C# assembly
    typeof<FSharpx.Text.Lexing.Position>.Assembly.Location

EDIT : On second thought, I don't know if the above code will work -- it assumes the .config file will be lazily loaded (i.e., on-demand). If the CLR loads the .config file at the same time the .exe is loaded, you'll need to do something like this instead:
// Change the current directory *before* referencing the C# assembly.
System.Environment.CurrentDirectory <- @"C:\blah";;

// Reference the C# assembly
#r @"C:\blah\foobar.exe";;


Another proof for complex solutions and solutions in finite fields

Question:
Let $S = \{f_1 , ... , f_r\} \subset \mathbb{Z}[x_1,...,x_n]$
Prove that there exists $x \in \mathbb{C}$ such that $\forall i, f_i(x) = 0 \iff $ for infinitely many $p$, $\exists x_p \in F_p$ such that   $\forall i, f_i(x_p) = 0$ where $F_p$ is some field of characteristic $p$.

I have been stuck on this question for a while now. I was looking for a proof and I found a SE post here
Relationship between a solution in $\mathbb{C}$ to a finite set of polynomials over $\mathbb{Z}$ and solutions in finite fields
but I wanted to know if there was a purely algebraic way to prove this?
Any help would be appreciated!
Answer: The purely algebraic way to prove this is by using Nullstellensatz.
If $f_1, \dotsc, f_r$ don't have a common zero in $\mathbb C$, then by Nullstellensatz, the ideal generated by these polynomials over $\mathbb C[x_1, \dotsc, x_n]$ contains the constant polynomial $1$. Hence there exist polynomials $g_1, \dotsc, g_r \in \mathbb C[x_1, \dotsc, x_n]$ such that $f_1g_1 + \dotsc + f_rg_r = 1$ as an identity of polynomials.
Now you should convince yourself that, by replacing the coefficients of the $g_i$'s with indeterminates, the identity $f_1g_1 + \dotsc + f_rg_r = 1$ becomes a system of linear equations in these indeterminates, with integral coefficients.
The existence of $g_1, \dotsc, g_r$ then means that this system of linear equations has a solution in $\mathbb C$. But since all the coefficients are in $\mathbb Z$, hence in $\mathbb Q$, we know that there must already be a solution in $\mathbb Q$.
Therefore, there exist polynomials $g_1, \dotsc, g_r\in \mathbb Q[x_1, \dots, x_n]$, such that $f_1g_1 + \dotsc + f_rg_r = 1$. Clearing the denominators, we get polynomials $h_1, \dotsc, h_r\in\mathbb Z[x_1, \dots, x_n]$, such that $f_1h_1 + \dotsc + f_rh_r = d$ for some non-zero integer $d$. Hence for any $p$ coprime to $d$, the polynomials $f_1, \dotsc, f_r$ cannot have a common zero in any field of characteristic $p$.

The other direction is similar. Assume that $f_1, \dotsc, f_r$ have a common zero in $\mathbb C$.
Let $\overline{\mathbb Q}$ be the algebraic closure of $\mathbb Q$. By Nullstellensatz, they already have a common zero $(y_1, \dotsc, y_n)$ in $\overline{\mathbb Q}$ (otherwise the ideal they generate in $\overline{\mathbb Q}[x_1, \dotsc, x_n]$ would contain the constant polynomial $1$, hence no common zero in $\mathbb C$).
Let $E$ be the number field generated by the algebraic numbers $y_1, \dotsc, y_n$ and let $\mathcal{O}_E$ be the ring of integers of $E$. Choose a non-zero integer $d$ such that each $dy_i$ are algebraic integers.
Now for any prime number $p \nmid d$, choose a prime ideal $\mathcal P$ of $\mathcal{O}_E$ above $p$, so that the quotient $F_p = \mathcal{O}_E/\mathcal P$ is a finite field of characteristic $p$.
It is then clear that, if we put $z_i = d^{-1}((dy_i)\mod {\mathcal P}) \in F_p$, then $(z_1, \dotsc, z_n)$ is a common zero of $f_1, \dotsc, f_r$ in $F_p$.
Comment: I just have a couple of follow-up questions: 1) if we take each coefficient of the $g_i$ to be a unique indeterminate, does't the identity $f_1g_1 + ... + f_rg_r = 1$ become a single linear equation, not a system? (Unless you meant a trivial 'system')  2) Why does the existence of the $g_i$ imply the existence of a solution (to the identity in the indeterminates) in $\mathbb{Q}$? 3) What is $d_{y_i}$ here and how does it relate to $d$? I don't understand the notation. 4) What do you mean by choose a prime ideal 'above' $p$? Thanks!
Comment: @User095746 Think of the identity $f_1g_1+\cdots+f_rg_r=1$ as an identity of polynomials in $n$ variables with the (finitely many) coefficients of the polynomials $g_i$ as unknowns. There are finitely many monomials appearing in that polynomial identity. Equating the coefficients of all those monomials gives you a linear system in the unknown coefficients of $g_i$s.
Comment: And, $dy_i$ is just the product $d\cdot y_i$. The discussion about prime ideals above $p$ is just basic algebraic number theory jargon. $\mathcal{P}$ is simply one of the maximal ideals of $\mathcal{O}_E$ with the property that $\mathcal{P}\cap\Bbb{Z}=p\Bbb{Z}$. Such ideals exist for all finite extension fields $E$ of $\Bbb{Q}$ and all prime numbers $p$.
Comment: 1) it's an identity of polynomials, so considered as linear equations over $\mathbb C$, there is one equation for every monomial, although on the right hand side only the constant term is non-zero. 2) it's an exercise in linear algebra: if $K/L$ is any field extension, then a system of linear equations with coefficients in $L$ has a solution over $K$ iff it has a solution over $L$. ...After typing these (on my smartphone), I see that @JyrkiLahtonen answered 3) and 4).
Comment: I see. Thank you both very much!


How to change the title of a modal window?

Question: I have a link that displays a modal window.
The link redirects to a page view.
When I click on it, it is marked in the title of the modal window Array.
How to customize the title ?
<?php

namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => auto,
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('the general terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @cgv.', ['@cgv' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

Comment: The `array` is a known Drupal Core bug, applying the latest proposed patch, as of this writting [#50](https://www.drupal.org/project/drupal/issues/2663316#comment-12677728), should fix it.
Answer: mmmm if the above did not work
LINK

Comment: Or just use single quotes at first: `data-dialog-options='{"width":700, "title":"YOURTITLE"}'`
Comment: This should be marked as accepted!


Efficient schema for fast access and retrieval of fanship data in DynamoDB

Question: I need some help with designing a DynamoDB Hash+Range key scheme for fast single item write access as well as fast parallel read access to groups of items.
Background:
Currently, each fanning link is stored as an item in the following format:
<code>{
     user_id : NUMBER
     fanned_id : NUMBER
     timestamp: NUMBER
},
</code>
where user_id is the hash key and fanned_id is the range key. This scheme allows for fast access to a single fanship item (via user_id + fanned_id), but when the complete fanship is read from DynamoDB, it takes long for the data to be transferred  if the user has fanned thousands of other users.
Here is how I query DynamoDB using the boto python library:
<code>table = Table("fanship_data", connection=conn)
fanship  = []
uid = 10
for fanned in table.query_2(user_id__eq=uid):
    fanship.append((fanned["fanned_id"],fanned["timestamp"]))
</code>
Clearly the throughput bottleneck is in the boto query, because the whole fanship of a user must be transferred at 25 items per second, even I have specified high throughput capacity for DynamoDB.
My question to you:
Assume that there is large read throughput capacity, and that all the data is present in DynamoDB.  I do not mind resorting to multiprocessing, since that will be necessary for transferring the data in parallel. What scheme for the Hash+Range key will allow me to transfer the complete fanship of a user quickly?
Answer: I think that your hash/range key schema is the right one for what you're trying to accomplish. I have implemented similar schemas on several of my tables.
According to the docs, "Query performance depends on the amount of data retrieved", and there doesn't seem to be a way to parallelize the read. The only way to do a parallel read is via a Scan, but I'm not sure if that is going to be a better approach for you.


How do you calculate the expected value of mixed lognormal distribution?

Question: Suppose $X=\log(Y)$ can be modeled by a mixture of two normal distributions with proportion $p$ of $X_1$ and proportion $1-p$ of $X_2$, where $X_1\sim\mathcal N(U_1, \sigma^2_1)$ and $X_2\sim\mathcal N(U_2, \sigma^2_2)$.
How do you calculate $E(Y)$; i.e., $E(\exp(X))$ where $X$ is a mixture of two normals?
Comment: Are you asking about a *linear combination* of normals or a *mixture*? The notation you've used is a little ambiguous in this regard and a correct answer will depend on which you are interested in.
Comment: @Cardinal Given that the OP has twice used the word "mixture" and did not equate "$p * X_1 + (1-p) * X_2$" with a $\mathcal{N}(p U_1 + (1-p)U_2, p^2 \sigma_1^2 + (1-p)^2 \sigma_2^2)$ distribution, it would be erroneous to interpret this as a linear combination, don't you think?
Comment: @whuber: I think that's very highly likely; on the other hand, both answers here have done their calculations assuming (intentionally or inadvertently) the latter rather than the former; and, there was a very recent question where this confusion popped up. So, my response was, shall we say, conservative rather than speculative. :-)
Comment: @Cardinal Thanks. And, to be perfectly clear--because I think you're holding back a little out of politeness--the answer to the mixture interpretation differs substantially from the answer to the linear combination interpretation.
Comment: I am sorry not getting back earlier. I mean mixture of normals, not linear combination of two normals.
Comment: I was thinking mixture with my answer but I wrote it like a linear combination.
Answer: I'll try to give an answer for the mixture case. Let's formalize the set-up. We consider a random variable $X$ and an indicator random variable $I$, with $P[I=1] = 1-P[I=2] = p$, independent of $X$. Furthermore, for the mixture we have that the law of $X$ given that $I=1$ is the law of $X_1$, which is Gaussian with mean $U_1$ and variance $\sigma^2_1$; and, if $I=2$, the law is that of $X_2$ with law $N(U_2,\sigma^2_2)$.
Then, for $Y=\exp(X)$ we can calculate the expectation as
$$
\begin{align}
E[Y] &= E[\exp(X)] = p E[\exp(X)|I=1] + (1-p) E[\exp(X)|I=2] \\
     &= p E[\exp(X_1)] + (1-p) E[\exp(X_2)] \\
     &= p \exp(U_1+ \sigma^2_1/2) + (1-p) \exp(U_2+ \sigma^2_2/2)
\end{align}
$$
by using the expectation of a log-normal.
Comment: @Richard: Sorry guys, my complete story: I need to estimate mean revenue (the population is very heavy tailed). Sample mean is a natural unbiased estimator but has a  wide confidence interval.  I hope to find an estimator with smaller MSE.  I fitted normal mixture to log transformed data. The fit seems good visually. But the point estimator I got (as what Richard suggested before) seems to be different from sample mean. I wonder whether I calculated it correctly and therefore raised the original question. If right, how to reduce the bias?  Thanks for your suggestions!
Comment: (+1) There are a couple (inconsequential) typos in the first paragraph.
Comment: **Follow up exercise** (*for the interested reader*): Imitate this approach to (easily) generalize to *arbitrary* finite mixture distributions *and* arbitrary (Borel measurable) function $g(x)$ in place of $\exp(x)$.
Comment: @cardinal I have corrected some ... don't see any anymore ... but it's 11pm here in Europe ...
Comment: I used this initially, but started to doubt whether it is correct. If X ~ mixed normal of X1 and X2 with mixing probability p, does that mean exp(X) ~ mixed lognormal with same mixing probability p? I started to doubt this because this estimator seems to be biased (different from sample mean) for my data. Any suggestions on how to reduce the bias?
Comment: @qqq, What estimator are you using? Up until now, all discussion has been about random variables, not data, so the idea of bias is not even applicable.
Comment: I used E[Y]=pexp(U1+σ2^1/2)+(1−p)exp(U2+σ2^2/2) as the estimator for the overall mean like what Richard suggested initially. Then I think this way we are treating p as fixed but indeed p is a random variable, therefore sth is missing there...  Please ignore my bias claim, I will try some simulation study to verify that.
Comment: @whuber: In the question it is asked how to **calculate** the mean and not how to estimate the model. I anwered how to calculate the mean which is useful if the parameters are known, which could be the case. On the other hand I will google something about the **estimation** of mixed Gaussian distribution. I am quite sure that I will find something. First thing that comes to my mind is maximum-likelihood or the EM algorithm. Later today I can probably provide more.
Comment: Google 'estimation of mixed gaussian distribution' and you find many hits .. add 'R project' and you find packages, I would try [nor1mix](http://cran.r-project.org/web/packages/nor1mix/nor1mix.pdf) or [mixtools](http://cran.r-project.org/web/packages/mixtools/mixtools.pdf).
Comment: qqq, Your estimator is indeed biased (as is well known). Also, $p$ is fixed: if it is a random variable, you have a more complex mixture than you first described. It sounds to me that you are not sufficiently distinguishing a model from data, which is a concern because it's leading you to keep changing your question. Please consider posting a new question in which you describe what you're really doing in terms of data collection and analysis. @Richard, I believe you intended to address your last two comments to qqq, not me.
Comment: @qqq You see that a lot of speculation is going on here how your question is meant. Can you please clarify. Is $p$ some percentage of a population on which you do statistics or is it a probability in a pure probabilistic sense. Is your question about probability theory or about statistics?
Comment: @qqq Thanks. This is a completely different question at this point (and it's interesting and deserves a good answer). May I suggest you accept Richard's answer and post a new question asking how to reduce the bias in your estimator? I should point out it has an obvious answer: use the arithmetic mean of the data. But there could be reasons for trying to adjust your estimator, anyway, depending on how you wish to balance the tradeoff between estimation bias and estimation variance.
Comment: @Whuber Sure, thanks whuber. I will think about it more and post a separate question once I get it clear. Do I need to close the thread or anything? Many thanks to Richard and you and others who gave feedbacks!
Comment: On the contrary, qqq: instead of closing the thread, please mark the best answer as accepted (by clicking on the gray checkmark). (I think only one currently remains undeleted, but if it works for you, then it's helpful to accept it.) That helps guide future readers to the most useful information.
Comment: @Whuber, thanks Whuber, just checked Richard's answer...
Comment: @qqq Thank you and Whuber. I am looking forward for the real problem.
Answer: For instance, if you are dealing with a two component mixture, the first moment is calculated as follows:
$\mu_{\rm mixture}=\pi_{1} \cdot \mu_{1} +  \pi_{2} \cdot \mu_{2}$,
where $\pi_{i}\ (i=1,2)$ stands for the components' weights and $\mu_{i}\ (i=1,2)$ for the means.
Comment: This is true, as far as it goes, but it ignores the non-linear transform (exp) in the problem statement.