Como Reiniciar Um Programa Python?

Question: Tenho que fazer um programa que calcule a soma finita de uma progressão geométrica, então fiz:
a_1 = float(input('Primeiro Termo: '))
a_2 = float(input('Segundo Termo: '))
n = int(input('Número do Termo: '))
q = a_2 / a_1
a_n = (a_1) * (q) ** (n - 1)
S_n = a_1 * (q ** n - 1) / (q - 1)
print('a{} é igual à \033[1;31m{:.0f}\033[m'.format(n, a_n))
print('A soma dos {} primeiros termos da P.G. é igual à \033[1;31m{:.0f}\033[m'.format(n, S_n))

O problema é que eu gostaria de transformar ele em um executável, e toda vez que o programa acaba de rodar, ele simplesmente fecha, e isso é bem chato quando tenho que fazer mais de uma conta.
Então gostaria de dar uma opção ao usuário: 1 Realizar outra conta, 2 Fechar o programa.
Quando o usuário quisesse realizar outra conta, o programa reiniciaria e ele poderia fazer outra conta. Tentei com:
import sys
import os
def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

E Então:
print('[ 1 ] Realizar outra conta\n[ 2 ] Sair do Programa')
cu = int(input('Sua escolha: '))
if cu == 2:
    exit()
elif cu == 1:
    restart_program()
#Sim, com uma variável muito madura

Porém não funcionou :(
Poderiam me ajudar?
Comment: Isso não faz sentido, faça um `while`https://pt.stackoverflow.com/q/352398/10 ou https://pt.stackoverflow.com/q/385771/101.
Comment: Achei engraçado o nome da sua variável.
Comment: @Danizavtz será que CU = Choose User, ou Command User?
Answer: Você precisa implementar um laço de repetição. Neste caso, a melhor forma é utilizar o while.
Para esta questão implementei o seguinte algoritmo...
while True:
    a_1 = float(input('Primeiro Termo: '))
    a_2 = float(input('Segundo Termo: '))
    n = int(input('Número do Termo: '))
    q = (a_2 / a_1)
    a_n = (a_1 * q ** (n - 1))
    S_n = (a_1 * (q ** n - 1)) / (q - 1)
    print('O {}º termo é igual à \033[1;31m{:.0f}\033[m'.format(n, a_n))
    print('A soma dos {} primeiros termos da P.G. é igual à \033[1;31m{:.0f}\033[m'.format(n, S_n))

    resp = input('Desejas continuar? [S/N] ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('\033[31mValor INVÁLIDO! Digite apenas "S" ou "N"!\033[m')
        resp = input('Desejas continuar? [S/N] ').upper()
    if resp == 'N':
        break

Observe neste algoritmo que quem controla o fluxo da digitação dos valores é o primeiro while. O segundo while serve para tratar a resposta do usuário. Se a resposta do usuário for S o algoritmo será novamente executado. Caso contrário o algoritmo será encerrado.
Answer: Se quer que algo se repita várias vezes, não invente, use um loop. Uma versão bem simples seria:
while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if input('Quer continuar? (S/N) ') == 'N':
        break

As outras respostas usam uma variável para controlar a condição do loop, mas nesse caso eu acho desnecessário. O valor digitado no último input só vai ser usado ali, para saber se deve continuar ou não, e depois não será usado para mais nada. Se digitar N, o break interrompe o loop.
Claro que você poderia fazer algo como:
condicao = True
while condicao:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if input('Quer continuar? (S/N) ') == 'N':
        condicao = False

Mas eu acho mais simples fazer o break, que deixa claro que naquele ponto o loop deve ser interrompido.

Outro detalhe é que se digitar qualquer coisa que não seja "N", o while continua. Se quiser ser mais específico e só aceitar determinados valores, pode fazer isso separadamente:
while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    while True: # outro loop só para validar a opção
        opcao = input('Quer continuar? (S/N) ')
        if opcao not in ('S', 'N'):
            print('Digite apenas S ou N')
        else:
            break # sai do while interno
    if opcao == 'N':
        break # sai do while externo

Ou seja, outro loop só para ficar pedindo para digitar de novo, caso não seja uma das opções válidas. Repare que agora faz sentido ter uma variável para guardar a opção, pois vou usá-la mais de uma vez (para testar se é um dos valores válidos, e depois para ver se é a opção que encerra o programa).

Claro que aí dá pra sofisticar o quanto quiser/precisar. Se pesquisar por aí, vai ver que "muita gente" chama upper() para transformar a string em maiúscula (assim poderia ser digitado "n" ou "N", por exemplo), ou ainda input(...)[0] para pegar somente o primeiro caractere (isso tem uma falha, que é no caso do usuário digitar apenas ENTER, pois aí input retorna a string vazia e ao tentar acessar o primeiro caractere dará erro).
Se quiser, separe a leitura da opção em uma função específica:
def ler_opcao(mensagem, valores_validos = ['S', 'N']):
    validos = "/".join(valores_validos)
    while True:
        opcao = input(f'{mensagem} ({validos}) ')
        if opcao not in valores_validos:
            print(f'Digite apenas um dos valores válidos: {validos}')
        else:
            return opcao

while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if ler_opcao('Quer continuar?') == 'N':
        break

Assim, a função ler_opcao recebe a mensagem e a lista de valores válidos (e a mensagem já mostrará esses valores com base na lista). Desta forma, você pode customizar à vontade. Por exemplo, se quiser que as opções sejam 1, 2 ou 3:
while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    opcao = ler_opcao('Digite 1 para fazer X, 2 para fazer Y, 3 para sair', ['1', '2', '3'])
    if opcao == '1':
        print('fazer X')
    elif opcao == '2':
        print('fazer Y')
    elif opcao == '3':
        break

Repare que nesse caso eu não preciso usar int para transformar a opção em número, pois se não for digitado um número, ele não estará entre as opções válidas. E nesse caso também faz sentido ter uma variável porque ela é usada várias vezes depois, para testar qual dos valores foi digitado.

No seu caso específico, então seria:
while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if ler_opcao('[ 1 ] Realizar outra conta\n[ 2 ] Sair do Programa', ['1', '2']) == '2':
        break

Answer: Uma alternativa para resolver este problema é colocar seu código dentro da função restart_program, segue um exemplo:
def restart_program():
    a_1 = float(input('Primeiro Termo: '))
    a_2 = float(input('Segundo Termo: '))
    n = int(input('Número do Termo: '))
    q = a_2 / a_1
    a_n = (a_1) * (q) ** (n - 1)
    S_n = a_1 * (q ** n - 1) / (q - 1)
    print('a{} é igual à \033[1;31m{:.0f}\033[m'.format(n, a_n))
    print('A soma dos {} primeiros termos da P.G. é igual à \033[1;31m{:.0f}\033[m'.format(n, S_n))

cu = ''
while cu != '2':
    restart_program()
    print('[ qualquer tecla ] Realizar outra conta\n[ 2 ] Sair do Programa')
    cu = input('Sua escolha: ')

Nesta solução reaproveitei o seu código para efetuar o comportamento esperado. ùnica coisa é que agora eu leio uma string ao inves de fazer um cast para o número 2, e eu leio qualquer valor para o cara poder reiniciar, caso queira utilizar os valores da pergunta, basta modificar o código.
Observe que nesta solução não é necessário utilizar as funções sys e os, pois caso o usuário selecione a opção '2' (string) , então já ocorre a condição para saída do laço.

Como Reiniciar Um Programa Python?


What does the sequence #' mean in Python source code

Question: In os.py there is a strange marker #' under the docstring and just before the imports
>>> import os
>>> os??
File:        /usr/local/lib/python3.11/os.py
Source:
r"""OS routines for NT or Posix depending on what system we're on.

This exports:
  - all functions from posix or nt, e.g. unlink, stat, etc.
  - os.path is either posixpath or ntpath
  - os.name is either 'posix' or 'nt'
  - os.curdir is a string representing the current directory (always '.')
  - os.pardir is a string representing the parent directory (always '..')
  - os.sep is the (or a most common) pathname separator ('/' or '\\')
  - os.extsep is the extension separator (always '.')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""

#'
import abc
import sys
import stat as st

from _collections_abc import _check_methods

GenericAlias = type(list[int])
...

Does the #' have some special meaning there? I assume if nobody removed that in over 20 years of eyes on this file that it must be there for a good reason (some macro, or some kind of marker for a text processor, but I could not find what). And, like the #!, it is difficult to search for information about.
What is the point of those #' comment?
Comment: No it's a simple comment, it doesn't mean anything except if you have an external tool that use it. If you have a french keyboard this 2 keys are side by side. A typo?
Comment: PEP8 defines "Each line of a block comment starts with a # and a single space"
Answer: Looking through the Cpython git history, this was added to os.py under this commit: "added several more __all__ lists".
Interestingly, another #' was added under the same commit but was later removed without any specific reasoning here.
#' does not have any special significance in Python. It is used in other languages like LISP. This is probably just a typo.


Erro na execução do Eclipse

Question: Baixei o Eclipse, instalei e realizei todo o procedimento corretamente. Assim que terminei de instalar e reiniciar o PC, fui executar o programa e apareceu este erro:

O Eclipse não abriu.
Comment: Você tem o *JRE* e *SDK* instalado?
Comment: Algumas destas respostas lhe atenderam?
Answer: Você deve instalar o JDKdo java disponivel aqui fique atento na arquitetura (x86, x64), ela deve ser igual a do seu sistema operacional e igual a do eclipse, esta instalação irá altomaticamente adicionar o caminho do JDK e JRE ao PATH, o eclipse não terá problemas em encontrar e usar ambos.

Erro na execução do Eclipse


Independence involving Multivariate Normal random vectors

Question: I am reading the book Introduction to Probability by Joe Blitzstein. The author defines Multinomial Normal distribution as follows.
A random vector $\mathbf{X}=(X_1,X_2,\cdots, X_k)$ is said to have a Multivariate Normal distribution if every linear combination of the $X_j$ has a Normal distribution. That is, we require $t_1X_1+\cdots +t_kX_k$ to have a Normal distribution for any choice of constants $t_1,\cdots, t_k$. If $t_1X_1+\cdots +t_kX_k$ is a constant, we consider it to a Normal distribution, albeit a degenerate Normal with variance $0$.
Theorem: If $\mathbf{X}=(X_1,X_2,\cdots, X_n)$ and $\mathbf{Y}=(Y_1,Y_2,\cdots, Y_m)$ are Multivariate Normal vectors with $\mathbf{X}$ independent of  $\mathbf{Y}$, then the concatenated random vector $\mathbf{W}=(X_1,\cdots,X_n,Y_1,\cdots,Y_m)$ is Multivariate Normal.
Proof: Any linear combination $s_1X_1+\cdots +s_nX_n+t_1Y_1+\cdots +t_mY_m$ is Normal since $s_1X_1+\cdots +s_nX_n$ and $t_1Y_1+\cdots +t_mY_m$ are Normal and are independent, so their sum is Normal. $\Box$
But I am having difficulty in understanding the above proof. I know that $s_1X_1+\cdots +s_nX_n$ and $t_1Y_1+\cdots +t_mY_m$ are Normal by the definition of Multivariate Normal distribution. I also know that sum of independent Normals is a Normal. But I do not understand why $s_1X_1+\cdots +s_nX_n$ and $t_1Y_1+\cdots +t_mY_m$ are independent. All I know is that since $\mathbf{X}$ and $\mathbf{Y}$ are independent, $X_i$ is independent of $Y_j$ for all $1\le i\le n$ and $1\le j \le m$.
Answer: We can use the tools in my answer to your previous question.
If $\mathbf{X}$ and $\mathbf{Y}$ are independent, then for functions $f$ and $g$, $f(\mathbf{X})$ and $g(\mathbf{Y})$ are independent. See discussion here for this statement.
Now, define $f(\mathbf{X}) = s_1X_1 + \dots + s_nX_n$ for arbitrary constants $s_1, s_2, \dots, s_n$. Similarly, define $g(\mathbf{Y}) = t_1Y_1 + \dots + t_mY_m$. Then $f(\mathbf{X})$ and $g(\mathbf{Y})$ being independent yields the result.
Comment: The proof [here](https://proofwiki.org/wiki/Functions_of_Independent_Random_Variables_are_Independent) is a tad less complicated.
Comment: Is there any less advanced proof/ intuitive argument to show that f(X) and g(Y) are independent? This is my introductory course, and I don't know Measure Theory and Borel measures.


How do you actually practice playing an electronic keyboard?

Question: Certain electronic keyboards look like pianos, but their keys are weighted totally differently.
For someone who has never learnt playing the piano, what would be the best method of taking the most out of a nice keyboard like the Novation UltraSound ? (light keys)
Any references to links, videos, books, welcome.
Answer: The full huge range of sounds available from synthesisers means that the subject is enormously broad. Typical keyboards behave differently depending on the virtual instrument you are playing.
For example, a piano patch isn't likely to respond to aftertouch, and might not respond to pitch bend; a strings patch will respond to pitch bend, and might swell if you press harder while sustaining the note.
Electronic keyboard use falls into three main camps:

standing in for a traditional keyboard instrument: piano, harpsichord, pipe organ, Hammond organ, electric piano, mellotron
standing in for other traditional instruments: flute, trumpet, string section
sounds with no traditional equivalent

For playing in the style of piano/organ, learning materials for those instruments will be perfectly transferable to the electronic keyboard. Practising piano pieces using the piano patch on your electronic keyboard will always be beneficial. Learning organ pieces with an organ patch will also be useful, and you'll be able to compare the different playing styles.
Many sounds naturally fit "piano style" playing, or "organ style" playing. For example, a glockenspiel sound is percussive and decays; so a piano style is more applicable. A flute sound is sustained, so an organ style fits better.
Note that some pianos have very light keys too.
I'm not aware of well-known teaching material for imitating other instruments. The skills learned playing piano/organ parts will be very transferable to this. But you'll also want to bring in aftertouch, pitch bend and modulation, for volume, vibrato, and bend effects. I suppose one way to practice is to find a score for (say) trumpet, along with a recording of a real trumpet playing it, and try to imitate that.
Music technology magazines like Sound on Sound sometimes have articles on imitating other instruments. There's an awful lot to know, if you want get it right -- for example, playing a guitar sound such that you never play two notes together which would be on the same string.
For purely electronic sounds, the sky's the limit. The skill of creating synthesised sounds is separate from the skill of playing them. A lot of the time, the parts you hear in records are not difficult to play -- or when they are, they're sequenced.
For the piano and organ pieces, at least, you should be able to follow structured courses intended for those instruments; so working through a series of piano exams (whether or not you actually get yourself graded) will work. For imitating other instruments, you may find that a piece that's easy on one instrument, is harder on a keyboard because of the key or the hand stretches. Wait until you can recognise whether a score is within your difficulty level by looking at it.
Answer: Piano and synth (organ) keyboards are really not very different at all.  Even across acoustic pianos the feel is QUITE different from one to the next (even moreso than between organ/synth keyboards).
The reason to learn on a fully weighted digital piano is so your playing can easily be moved to a real acoustic.  (Which is the king of all instruments, really:)
But you don't NEED to learn on one.  Start with what you got.  KEEPing in mind that I am -not- a piano teacher.
The overall process of becoming a musician is exactly the same across these keyboards.  (And VERY similar even across musical instruments).

find a teacher who can coach you and get you on the right track quickly
learn to read sheet music or SOME way of coming up with a song
keep finding good songs to play and the time to do it in
hone your craft - find how to "nudge" your playing with subtle velocity and rhythm changes to the song to make it really sing.

Good luck to ya!
Comment: But note:  A harpsichord feels VERY different and needs a delicate touch.  I don't know of any electronic keyboard that feels like a harpsichord.  If you want to learn to play one, you are going to have to find a real harpsichord.


An explicit construction of the "Veronese embedding".

Question: I am reading the text "An invitation to Algebraic geometry" by Karen Smith et. al. In the text there is a proposition on Veronese mappings:
Prop: The Veronese mapping $v_d$ defines an isomorphism of $\mathbb{P}^n$ onto its image.
In the proof, it is explicitly shown how $\mathbb{P}^n \rightarrow v_d(\mathbb{P}^n) \rightarrow \mathbb{P}^n$ is an identity map, but the other part of the proof is left for the reader. I am struggling to prove that $v_d(\mathbb{P}^n) \rightarrow \mathbb{P}^n \rightarrow v_d(\mathbb{P}^n)$ is an identity map too. Could someone please help me with this?
I am a beginner at Algebraic Geometry, so a detailed explanation would be appreciated. Thanks in advance!
Comment: 1: In order to get a detailed explanation which will be comprehensible to you, you need to supply more information about what you know and what your struggles are. Please make an [edit] to your post to add this information. 2: How does Smith prove the first direction? If the proof is by writing down the two maps $\Bbb P^n\to v_d(\Bbb P^n)$ and $v_d(\Bbb P^n)\to \Bbb P^n\$ and showing that they compose to the identity, then your job is just to show that the other composition is the identity, and you should be able to repurpose some of her proof.
Answer: Here is an "elementary" answer. Start with the projective line:
$$v:=v_2: \mathbb{P}^1:=C \rightarrow \mathbb{P}^2:=S$$
defined by
$$v(u:v):=(u^2: uv: v^2).$$
Let $S$ have coordinates $x,y,z$ and prove that $v(C) \cong Z(xz-y^2)$ is the zero set of the polynomial $F:=xz-y^2$. Let $D(x) \subseteq S$ denote the set of "points" in $S$ with non-zero $x$-coordinate (similar for $D(y),D(z)$). You may define maps
$$v_x: D(x) \rightarrow C$$
by
$$v_x(a:b:c):=(a:b).$$
Since $(a:b:c)\in D(x)$ it follows $a \neq 0$ and hence $(a:b)\in C$ is well defined.
$$v_y: D(y) \rightarrow C$$
by
$$v_y(a:b:c):=(a:b) \text{ or }(b:c)$$
Since $b^2=ac$ we have $(a,c \neq 0)$ and it follows
$$(a:b)\cong (ac:bc)  \cong (b^2:bc) \cong (b:c)$$
hence $v_y$ is a well defined point in $C$.
$$v_z: D(z) \rightarrow C$$
by
$$v_z(a:b:c):=(b:c)$$
Since $(a:b:c)\in D(z)$ it follows $c \neq 0$ and hence $(b:c)\in C$ is a point.
Then you may verify that $v_x,v_y,v_z$ are well defined maps and local inverses to the map $v_2$, hence $C \cong v(C):=S$ is an isomorphism of algebraic varieties.
Hence this exercise gives you an opportunity to work with local coordinates and to understand what it means for a morphism of algebraic varieties to have an inverse morphism. This method generalize to arbitrary Veronese embeddings and you should do this as an exercise.
Question: "In the proof, it is explicitly shown how $P^n→v_d(P^n)→P^n$ is an identity map, but the other part of the proof is left for the reader. I am struggling to prove that $v_d(P^n)→P^n→v_d(P^n)$ is an identity map too. Could someone please help me with this?"
Answer: In the above example I give an open cover $D(x),D(y),D(z)$ of the variety $v(C)$ and I construct morphisms
$v_x,v_y,v_z$ from $D(x) \rightarrow C$ (resp. $D(y),D(z)$) glueing to a global morphism
$$u: v(C) \rightarrow C$$
with the property that $v \circ u= u \circ v = id$ is the identity.
You should verify that the morphisms I define agree on overlaps. It follows $v: C \rightarrow v(C)$ is an isomorphism of varieties.
Note. If $T:=k[x,y,z]/(xz-y^2)$ and $v(C):=Proj(T)$, we have above constructed an isomorphism of varieties
$$ Proj(k[x_0,x_1]):=C \cong^v v(C):=Proj(T),$$
and we may ask for an "inverse ring isomorphism"
$$ f:T \rightarrow k[x_0,x_1]$$
inducing the map $v$ - which is an isomorphism of varieties. You will find there is a natural map $f$ defined by $f(x):=x_0^2, f(y):=x_0x_1, f(z):=x_1^2$ inducing an isomorphism
$$f: k[x,y,z]/(xz-y^2) \cong k[x_0^2,x_0x_1,x_1^2] \subseteq k[x_0,x_1].$$
Hence the "natural" map $f: T \rightarrow k[x_0,x_1]$ is not an isomorphism of $k$-algebras. The correspondence between maps of varieties and maps of coordinate rings is more complicated when studying projective varieties than in the case of affine varieties. In the case of affine varieties $V,W$ with coordinate rings $A(V), A(W)$, there is a 1-1 correspondence between maps $\phi: V \rightarrow W$ and maps of coordinate rings $\phi^*: A(W) \rightarrow A(V)$.  Hence there is an isomorphism $V \cong W$ of algebraic varieties (over $k$) iff there is an isomorphism $A(W) \cong A(V)$ of $k$-algebras. This result does not hold for projective varieties.
I'm not familiar with Smith's book, but you also find this explained in Hartshornes book, Chapter II.5, where a relation between maps of graded rings and the Proj construction is outlined.
Note. If you check Exercise II.2.14 in HH you will find a construction of a morphism of schemes
$$f:U \rightarrow Proj(S)$$
where $U \subseteq Proj(T)$ and $\phi: S \rightarrow T$ is a graded morphism of graded rings. In the case of the projective line $C$ there is for every $d\geq 2$ a "natural" sub ring
$$ i:T:=k[x_0^{d-j}x_1^j:j\in\{0,1,..,d\}] \subseteq k[x_0,x_1]$$
and I believe that in the case of $i$ you get an isomorphism
$$\phi_d: C \rightarrow \mathbb{P}^d$$
onto a curve $\phi_d(C)$ - the $d$-uple embedding of $C$. The construction of the Segre embedding and $d$-uple embedding is explained in the exercices in HH.
Note: There is an alternative approach using invertible sheaves. Let $V^*:=k\{y_0,y_1,y_2\}$ and let $S:=\mathbb{P}(V^*)$ and let $\pi: C \rightarrow Spec(k)$ be the structure map. There is a surjective map of sheaves
$$\phi_v: \pi^*(V^*) \rightarrow \mathcal{O}_C(2) \rightarrow 0$$
defined by
$$\phi_v(y_0):=x_0^2, \phi_v(y_1):=x_0x_1, \phi_v(y_2):=x_1^2.$$
By the universal property of $\mathbb{P}(V^*)$ you get a map $v: C \rightarrow \mathbb{P}(V^*)$ and it follows from HH.II.7.2 that $v$ is a closed immersion.
At $D(y_0)$ you get the map
$$v_0: k[\frac{y_1}{y_0}, \frac{y_2}{y_0}] \rightarrow k[\frac{x_1}{x_0}]$$
defined by
$$v_0(\frac{y_1}{y_0}):=\frac{x_1}{x_0}, v_0(\frac{y_2}{y_0}):=(\frac{x_1}{x_0})^2$$
and it follows $v_0$ is surjective.
Comment: Thank you very much for such a detailed answer. It all makes perfect sense to me.
Answer: I believe some items are missing in the proof of the Proposition on the Veronese imbedding in the book by Smith et. al. One needs to give the equations of $W$. To do this,
I try to answer to your question by an example:
Consider the Veronese map of degree $3$ on $\mathbb{P}^2$:
$$\nu_3 : \mathbb{P}^2 \longrightarrow \mathbb{P}^9,$$
$$[x_0 : x_1 : x_2] \mapsto [x_0^3: x_0^2x_1: x_0^2x_2: x_0x_1^2: x_0x_1x_2: x_0x_2^2: x_1^3: x_1^2x_2 : x_1x_2^2: x_2^3].$$
Let $z = [z_{300}, z_{210},z_{201},z_{120},z_{102},z_{030},z_{021},z_{012},z_{003},z_{300}]$ be the current coordinates in $\mathbb{P}^9.$
Let $Z\subset \mathbb{P}^m$ be the projective variety defined by the following equations
$$z_{i_0i_1i_2}z_{j_0j_1j_2}=z_{k_0k_1k_2}z_{l_0l_1l_2}, \ \ {\rm with}  \ \ i_0+j_0=k_0+l_0, i_1+j_1=k_1+l_1, i_2+j_2=k_2+l_0. \  (*)$$
We have  ${\rm Image}(\nu_3) \subset Z$ because the coordinates of  ${\rm Image}(\nu_3)$ satisfy the equations $(*)$. We show that $W=Z$.
Let $U_0, U_1, U_2 \subset Z$ be the open subset where $z_{300}\not=0, z_{030}\not=0, z_{003}\not=0$, respectively.
Define $\varphi_i : U_i \longrightarrow \mathbb{P}^2$, $i=0,1,2$ by
$$\varphi_0(z) = [z_{300}, z_{210},z_{201}],$$
$$\varphi_1(z) = [z_{120}, z_{030},z_{021}],$$
$$\varphi_2(z) = [z_{102}, z_{012},z_{003}].$$
Then $\varphi_i$ and  $\varphi_j$ agree on $U_i\cap U_j$. For example, let's check  $\varphi_0$ and  $\varphi_1$.
$[z_{300}, z_{210},z_{201}] = [z_{120}, z_{030},z_{021}],$ since $z_{300}/z_{120} = z_{210}/ z_{030} = z_{201}/z_{021}$ exactly by the equations $(*).$
Thus $\varphi_i$'s match together to give a map $\varphi : Z \longrightarrow \mathbb{P}^2.$
It is straightforward to see that $\varphi \circ \nu_d = {\rm id}_{\mathbb{P}^2}.$ Your question is almost the same as checking $\nu_d  \circ \varphi = {\rm id}_{\mathbb{P}^m}.$
To check this, one again needs to use equations $(*).$ Let's check $\nu_d  \circ \varphi_0(z)=z$.
Recall that $z = [z_{300}, z_{210},z_{201},z_{120},z_{102},z_{030},z_{021},z_{012},z_{003},z_{300}].$\
Thus $\varphi_0(z) = [z_{300}, z_{210},z_{201}],$ and
$$\nu_d (\varphi_0(z)) =$$ $$ [z_{300}^3: z_{300}^2z_{210}:z_{300}^2z_{201}: z_{300}z_{210}^2: z_{300}z_{210}z_{201}: z_{300}z_{201}^2: z_{210}^3: z_{210}^2z_{201}: z_{210}$$ $$z_{201}^2: z_{201}^3]. \ \ \ (**)$$
Using equations $(*)$ we show the the last element is equal to
$$z_{300}^2[z_{300}, z_{210},z_{201},z_{120},z_{102},z_{030},z_{021},z_{012},z_{003},z_{300}],$$
which is equal to $z$. The three entries in $(**)$ have the factor $z_{300}^2$. Consider the fourth entry. By $(*)$ we have $z_{210}^2 = z_{300}z_{120}$. Therefore,
$z_{300}z_{210}^2 = z_{300}^2z_{120}$. Consider the fifth entry. By $(*)$ we have $z_{210}z_{201}=z_{300}z_{111}$. For the sixth entry, we have $z_{201}^2 = z_{300}z_{102}$. For
$z_{210}^3$, we have $z_{210}^3= z_{210}z_{210}^2= z_{210}z_{120}z_{000} = z_{003}z_{300}^2$. And so on.
This means the ${\rm Image}(\nu_3) = Z$ and $\nu_3$ is an imbedding.


Menu Dropdown do bootstrap não está funcionando

Question: Meu menu dropdown não funciona.

  <button type="button" class="btn btn-warning">Menu Dropdowb</button>
  <button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-expanded="false">

    Toggle Dropdown
  </button>

Submenu1

Submenu2

Submenu3

Submenu4

Comment: Tem como colocar o HTML do drop down?
Comment: @PauloHDSousa.
O HTML não cabe.
O que eu coloquei foi o do dropdown e a ativação do javascipt.
Obrigado.
Comment: Por favor, crie um snippet de código, reproduzindo o problema, para que fique mais fácil ajudá-lo. Adicione também se puder um print da sua tela, caso o problema seja com a apresentação. Adicione informações sobre qual browser está usando, qual sistema, assim teremos mais contexto para poder dar uma resposta mais assertiva.
Comment: tente utilizar o https://jsfiddle.net/ para ter um exemplo real para que possamos te ajudar rapidamente.
Comment: eu coloquei o css, mas não os scripts javascript do bootstrap
Answer: O Bootstrap possui uma dependência: jQuery. Basta incluir o código da biblioteca antes de incluir o arquivo bootstrap.js (ou bootstrap.min.js).

<!doctype html>

<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'/>

  <button type="button" class="btn btn-warning">Menu Dropdown</button>
  <button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-expanded="false">

  Toggle Dropdown
  </button>

Submenu1

Submenu2

Submenu3

Submenu4

Comment: Obrigado @Renan.
Bastou incluir o ``.
Fiz as correções conforme o seu exemplo.
Comment: como faz com o jquery 3 ???
Answer: Veja se não está faltando o <!DOCTYPE html> no topo do documento HTML.
Se não tiver isso, vai ficar esquisito mesmo assim:

Ao colocar o DOCTYPE corretamente vai ficar assim:
Comment: Está com Doctype no inicio.
Estranho que ele esta preto.
Obrigado pela dica.
Mas eu copiei e colei e nada, ainda.
Comment: Você poderia adicionar um print da sua tela na questão, ou então criar um [fiddle](http://jsfiddle.net/) ou um snippet que reproduza o problema?


What statistical test should I use when finding the relationship between average time spent on social media and academic attention span?

Question: Any suggestions? Thank you in advance
Comment: Can you tell us how do you measure the variables mentioned in the title?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: It depends on how you operationalize the two variables the relationship of which you're trying to quantify, and whether you've identified one as your independent variable (IV) and the other as your dependent variable (DV).
If you have not yet assigned your IV and DV, and assuming both are quantitative continuous following the Gaussian distribution, then Pearson's correlation can be used.  Otherwise, use Spearman's rank correlation if the distribution is non-normal.
On the other hand, if you plan on categorizing both variables, then chi-square or Fisher's exact test can be used.
From reading your question, I'm assuming your hypothesis is that the average time on spends on social media (IV) affects the length of their academic attention span (DV).  If your DV is quantitative continuous (regardless of whether your IV is quantitative or categorical), you can perform linear regression analysis.  You may need to test for any assumption violations as well.  However, if your DV is categorical, you may need to use logistic regression analysis.


Script to List all Desktop and Laptop Model for Server 2008 Domain

Question: Is there any way I can list all the desktop and laptop model? There is no naming convention and I'm having difficulty differentiating laptop and desktop in our environment.
I have already tried to use wmic but in only one laptop.
c:\>wmic computersystem get model,name,manufacturer,systemtype
Manufacturer  Model    Name        SystemType
LENOVO        2236EG1  WINCMD-PC  x64-based PC

Need to run in a Domain Environment.
Answer: Probably something like this, using PowerShell. Note that depending on the size of your domain, this may hit your domain controller pretty hard; I'd highly suggest you put some sort of filter other than "*" on the "Get-ADComputer" at the top
$allComputer = Get-ADComputer -Filter "*"
foreach ($c in $allComputer) {
  $wmi = Get-WmiObject -Computer $c.Name -Class "Win32_ComputerSystem"
  Write-Output "$($c.Name) - $($wmi.Manufacturer) $($wmi.Model) $($wmi.Name) $($wmi.SystemType)"
}

Comment: Hello DarkMoon, thank you for your response, will try this after i upgrade the domain controller to 2012. right now we are using server 2008, thats why i cant use powershell with active directory module.
Comment: Why not? I thought 2008 and up supported the AD cmdlets (on my mobile atm so I can't check easily), but if they don't, use the Quest (Dell) AD cmdlets like everyone else. :-P You just need to import the module first, then use Get-QADComputer instead of Get-ADComputer; I believe the parameters are the same. I can try to check that later when I'm on my PC.


how to specify the target device (or emulator) on the command line with android maven plugin?

Question: The question is basically what are the arguments that I need to pass in the command line in order to specify the target device (or emulator) with android maven plugin.
Answer: You basically just need to pass the argument <code>-Dandroid.device=</code>
For the device argument, you can use:

"usb" (will target the device connected in your usb port)
"emulator" (will target the running emulator)
specificdeviceid (can be the port number or device name for the emulator or id of the device)

By the way, if you have more than one target that matches the argument (like 2 emulators running and you use "emulator", it will target all the running emulators). That's pretty handy if you want to deploy in multiple emulators =D
Just in case, here is an example of the usage of the argument:

mvn android:deploy  android:run  -Dandroid.device=emulator


Alternative proof of the reflection property

Question: I'd like to prove the reflection property for the hyperbola. That is, that S'PS is bisected by the tangent at P. Suppose the tangent intersects the x axis at T. The usual method would be to use the sine rule on triangles S'PT and SPT, then to use the fact thar TS/TS'=PS/PS' (can be shown quite quickly with an easy computation).

I'm trying to find an alternative proof by constructing perpendiculars from S and S' to the tangent at R and R' respectively. However from here, I don't have much other than...

Triangles TSR and TR'S' are similar.
I need to somehow show that triangles SPR and S'PR' are similar.

Would love to receive any pointers to get me going in the right direction to an alternative proof.
Comment: Can you find the curve for which *SPS'* is trisected by the tangent at *P* ? :-)
Answer: Well, you have $TSR$ and $TR'S'$ similar, hence $\dfrac{RS}{R'S'}=\dfrac{TS}{TS'}$
You have also, as you stated, $\dfrac{TS}{TS'}=\dfrac{PS}{PS'}$
Then you have $\dfrac{RS}{R'S'}=\dfrac{PS}{PS'}$
That is also $\dfrac{R'S'}{PS'}=\dfrac{RS}{PS}$.
Can you finish from here?
Comment: Cheers, I can see it from here.


Ao Invés de mostrar texto linha por linha mostrar o texto inteiro

Question: Ao Invés de mostrar texto linha por linha mostrar o texto inteiro. Visual Studio Community 2017.
Stream entrada = File.Open(varexe + "\\Score.txt", FileMode.Open);
StreamReader leitor = new StreamReader(entrada);
string linha = leitor.ReadLine();
while (linha != null)
{
    MessageBox.Show(linha);
    linha = leitor.ReadLine();
}
leitor.Close();
entrada.Close();

Comment: Meio confuso. Mas se eu entendi bem, pq não concatenar em uma variavel no loop e mostra só no final?
Comment: @MalysterSnur conseguiu resolver o seu problema?
Answer: Utilize o método ReadToEnd() e procure usar o using, quando estiver trabalhando com Stream e File, isso vai garantir o Dispose() do objeto assim que ele não estiver mais alocado
string texto = string.Empty;

using (Stream entrada = File.Open(varexe + "\\Score.txt", FileMode.Open))
{
    StreamReader leitor = new StreamReader(entrada);
    texto = leitor.ReadToEnd();
}

MessageBox.Show(texto);


How to open a Matlab function

Question: Here in matlab, the source code for latcfilt.m
It is from signal processing toolbox.
<code>error(nargchk(2,6,nargin,'struct'));

if nargin < 6
    [F,G,Zf] = latcfiltmex(varargin{:});
else
...
</code>
I want to have a look at the function latcfiltmex() , however, when I tried to rightclick->Open "latcfiltmex", it turned out that I cannot open it. It says the file latfiltmex.m doesn't exist.
Then how can I look into it?
Judging from its name, it appears to be a mex file. Then is it possible for me to get the c code for that? Or is it sealed by Mathworks?
Thanks
====
Edit
I found the mex file in the %MATLAB%/toolbox/signal/ folder.
Its name is latcfiltmex.mexw32, and no attached src.
Comment: The "mex" within the file name "latcfiltmex" suggests that the file in question is a `.mex` file, that is, a pre-compiled matlab file. If so, the full file name is probably `latcfiltmex.mex` and source code cannot be viewed.
Comment: Exactly as Muster said. You can not see all matlab functions, some of them are not open to see.
Comment: Yeah, no source is found. Do you have an idea where can I get the implementation for a signal process function?
Comment: This must have been asked many times before. Surely a duplicate.
Comment: @woodchips find the dup and vote to close...
Answer: For build-in functions and compiled mex  files Mathworks does not allow access to source code. All you have is the documentation published by mathworks.
Comment: Thanks. And @H.Muster has also brought out a answer in the comment.

How to open a Matlab function


A question about the gluing of Riemann surfaces

Question: Often, the definition of Riemann surfaces is motivated by the example of the multi-valued function $f(z)=\sqrt{z}$. Every point $z\in \Bbb{C}$ has two images. Hence, this function has two "branches"; $re^{i\theta}\to \sqrt{r}e^{i\theta/2}$ and $re^{i\theta}\to \sqrt{r}e^{i(\theta+ 2\pi)/2}$. Here, $0\leq\theta<2\pi$ and $r\geq 0$.
We choose one of these two branches.
Why do we then get two copies of the complex plane, and the consequent gluing, etc? Now that we have already chosen one branch, shouldn't we be satisfied with whatever images we get (all of which lie in the upper half plane, as in our case)?
Answer: The point is that we'd like to define a function "sorta like square root" with the following property:
If $\gamma: [a, b] \to \mathbb C - \{0\}$ is a curve, then

$F(\gamma(t))^2 = \gamma(t)$ (so $F(z)$ is a square root of $z$), and
$t \mapsto F(\gamma(t))$ is continuous as a function of $t$.

In other words, the proposed function $F$ would let us compute square roots "in a continuous way depending on position."
Alas, that's not possible for any function $F: \mathbb C \to \mathbb C$, for if $\gamma$ traverses the unit circle once, we find that $F(1)$ must be both $+1$ and $-1$.
On the other hand, we can build a surface $M$ with the property that

There's a function $p: M \to \mathbb C$ that's smooth and is 2-to-1 almost everywhere (i.e., for each point of $\mathbb C$, there are two points of $M$), the exception being that $p^{-1}(0)$ consists of a single point of $M$.
every continuous path in $\mathbb C - \{0]\}$ has exactly two "lifts" to $M$, i.e., for a such a path $\gamma$, there's a continuous path $\alpha: [a,b] \to M$ with $p(\alpha(t)) = \gamma(t)$ for every $t$. (And in fact there are two of these).

And on this "Riemann surface" $M$, there is a function like the one we were looking for, i.e., there's a continuous function
$$
F: M \to \mathbb C
$$
with the property that if $\alpha$ is a lift of a curve $\gamma$ that misses the origin, then
$$
F(\alpha(t))^2 = \gamma(t)
$$
for every $t$. So on this Riemann surface, "there are square roots".


Ring finger picking fingerstyle problems

Question: I'm a beginner…like I know absolutely nothing about fingerstyle. I can play somewhat beginner level flatpicking. Now when I tried to fingerpick for the first time ever by copying YouTube artists' right hand positions, I noticed that my right ring finger is absolutely unable to make a decent sound while plucking the high E string.
I can try picking a bit harder, but when picking other strings simultaneously, there is almost no sound from the high E. How do guitarists get such good sound quality for the high E? If you could list some useful exercises ( keep in mind: I haven't done absolutely anything in fingerstyle so please keep it basic) and also some YouTube videos for people who want to start fingerstyle, I would be really obliged.
Comment: Is it a "thin" / "weak" sound you are currently getting on string 1, or a "twangy" / "brittle" sound?
Comment: Extremely weak. I don't have nails, that may explain it I guess
Answer: The most obvious explanation is that your ring finger is weaker than your index and middle fingers.  You can strengthen your ring finger by using it more.  Play scales by picking with your ring finger and one other finger in alternation.  You should do this with all finger combos (index/middle, middle/ring, index/ring) but spend more time on those that include the ring finger so it can catch up.  This will be great for your coordination and finger strength.
You might also want to give some attention to your fingernails.  Generally, when fingerpicking, you will contact the string with a combination of flesh and nail.  The flesh helps with muting and the nail helps with attack (nature's plectrum).  If the nail is too short, you'll get a duller (fleshier) sound.  If the nail is too long, it can sound brittle.  If the nail is jagged or rough, you'll get an uglier and/or out-of-control sound.
If you plan to play fingerstyle a lot, you'll probably want to grow your nails a little and shape them so that they make smooth and consistent contact with the strings -- no grabbing catching.  Each person's hands and fingers and nails are different, so you'll need to experiment to find what works for you.
Comment: I appreciate your advice!


Having trouble with linked lists, program will not print the elements

Question: I am supposed to do an assignment in C programming language. It includes linked lists and reading user input from the console.
The user inputs numbers into the console, for example ( 1 3 5 7 0 ), which are added, one by one, to the beginning of the linked list. 0 marks the end of the transition. This is what the linked list should look like after the first part: 7 5 3 1
I need to code two different functions that will delete different elements of the linked list.
First function deletes all elements from the list that have the value that you input, and second function deletes the element on the position that the user inputs, if it exists.
At the end, you should print the list.
I've written the the first function correctly, and I am sure about it, with the second function (the one that deletes elements on a certain position) I had some trouble. I made a simple function that counts how many nodes are there in total, so if someone puts a number larger than the amount of nodes, a message would pop up. I also used that function to make a for loop and used it as a limit when searching for the element on a certain position, if that makes any sense. The program also won't print anything, I have no idea why.
    typedef struct Element Element;

    struct Element
    {
        int number;
        Element *next;
    };

    Element *addnewN(int number)
    {
       Element *newN = (Element*)malloc(sizeof(Element));

       newN->number = number;
       newN->next = NULL;

       return newN;
    }

    Element *add_on_beginning(Element *head, Element *newN)
    {
       newN->next = head;

       return head;
    }

    Element* delete_value(Element* head, int value)
    {
       Element *before = NULL;
       Element *temp = head;
       Element *newNhead = head;

       while(temp != NULL)
       {
          if(temp->number == value)
          {
            if(before == NULL)
            {
               newNhead = temp->next;
               free(temp);
               temp = newNhead;
            }
            else
            {
                before->next = temp->next;
                free(temp);
                temp = before->next;
            }
        }
        else
        {
            before = temp;
            temp = temp->next;
        }

     }
       return newNhead;
    }

    int counter(Element *head)
    {
       int count = 0;
       Element *temp = head;

       while(temp != NULL)
       {
         count++;
         temp = temp->next;
       }
       return count;
     }

    Element* delete_on_position(Element* head, int position)
    {
       int limit = counter(head);

       Element *temp = head;
       Element *newNhead = head;
       Element *before = NULL;

       if(position > limit)
       {
         printf("Error.\n");
       }

       for(int i = 0; i < limit; i++)
       {
          if(position == 0)
       {
          newNhead = temp->next;
          free(temp);
          temp = newNhead;
    }
    else if(position == i)
    {
        before->next = temp->next;
        free(temp);
        temp = before->next;
    }
    else
    {
        before = temp;
        temp = temp->next;
    }
}
return head;
}

void printElement(Element *element)
{
   printf("%d ", element->number);
}

void printList(Element *head)
{
   Element *temp = head;

   while(temp != NULL)
   {
      printElement(temp);
      temp = temp->next;
   }
}

void menu()
{
   printf("\t MENU \n");
   printf("1. Delete all elements from the list that have the value that
   you input.\n");
   printf("2. Delete the element on the position, if it exists.\n");
   printf("3. Print the list. \n");
   printf("4. Exit \n");
}

int main()
{
    Element *head = NULL;

    int i = 0;
    int arr[1000];
    char temp;
    int x;
    int y;

    printf("Input the numbers you want: \n");

    while(temp != '\n')
    {
       scanf("%d%c", &arr[i], &temp);

       if(arr[i] == 0)
       {
          break;
       }

       head = add_on_beginning(head, addnewN(arr[i]));

       i++;
     }

     menu();

     while(1)
     {
        scanf("%d", &x);

        switch(x)
       {
          case 1:
          {
             scanf("%d", &y);
             head = delete_value(head, y);
             break;
          }
          case 2:
          {
             scanf("%d", &y);
             head = delete_on_position(head, y);
             break;
          }
          case 3:
          {
              printList(head);
              break;
          }
          case 4:
          {
              return 0;
          }
     }

  }

   return 0;

 }

What you are supposed to get would be for example:
Input: 2 4 5 8 5 0 (in one line), and in one line each:
2
2
1
5
3

Output: 2 8
When debugged, the code does not show any errors.
Answer: add_on_beginning is not returning the correct value. It should return the node that was added, since it's the new head of the list. Nothing else will work correctly because of that, because head will always be NULL.
Element *add_on_beginning(Element *head, Element *newN)
{
   newN->next = head;

   return newN;
}


Add execute button to Commerce POS modal?

Question: I'm building a custom POS modal similar to the POS_Button_Modal_View -based ones that present a view. I wrote a modal that presents a page from a given callback:
class POS_Button_Modal_Page extends POS_Button_Modal {

  public function modalPage(CommercePOS $pos, $js) {
    $form_state = array(
      'title' => drupal_get_title(),
      'build_info' => array('args' => array($pos->getState()->getOrder())),
      'ajax' => $js,
      'pos' => $pos
    );

    if (!$js) {
      return drupal_build_form($this->config['page callback'], $form_state);
    }

    $output = ctools_modal_form_wrapper($this->config['page callback'], $form_state);

    return $output && !$form_state['executed'] ? $output : FALSE;

  }
...

The modal displays my page as intended, but I don't know how to build a submit button that works like the buttons in the POS-provided views.
The view in, eg. the SetUser POS modal uses the commerce_pos handler to render a button that executes the command:
class commerce_pos_handler_field_pos_command extends views_handler_field { ...

How can I build a submit button in my custom modal that executes my new command?
My command extends POS_Command with my custom implementation of execute()
class POSCommand_MyCommand extends POS_Command {

  function execute(CommercePOS $pos, $input = '') { ...

It seems like a POS_Button_Command should be created and rendered in the modal. But how does that get connected to my command?
Answer: Instead of a regular "page" callback, implement the page as a form with an action (submit) button. When the form is submitted and validates, the modal will be released courtesy of the way ctools_modal_form_wrapper() works.
POS_Command was not the right way to think about the problem in this case. POS_Button_Command is better suited to a simple, pre-defined operation as in setting the order user from a list of users. I was trying to do a more complex operation in the modal, gather some data from form inputs, then run some commerce commands on the order.
Short answer: The POS_Button_Modal_Page class works for loading a custom modal page. Implement the page as a form, and do the execution code in the form_submit handler instead of using POS_Command.


What is the name of this statistical paradox/phenomenon: statistical significance depends on what would have happened but did not

Question: I don't remember it exactly, and I'd like to read up on it again.
It is about experiment design and frequentist hypothesis testing. A sequence of N measurements are made, and then when evaluating the data, whether the data shows a significant effect depends on why the experiment was a terminated: because it was already predecided that N measurements need to be made, or because of some other criterion (I don't remember). The "paradox" is that the data is the same, but we have to know how the experiment would have continued if something else had happened. So a part of the plan that never got applied is required to decide whether the effect is significant.
I clearly remember that this has a detailed Wikipedia article, but I can't find it either through Google or Wikipedia search or browsing. Maybe it was not designated as a "paradox", but an effect, phenomenon, thought experiment or something else.
Answer: You might be thinking of the Likelihood Principle.
Comment: Thank you, that's exactly it! More specifically it's the section [Experimental design arguments on the likelihood principle](https://en.wikipedia.org/wiki/Likelihood_principle#Experimental_design_arguments_on_the_likelihood_principle).
Comment: Well, the case in the question is a violation of the likelihood principle...
Answer: As @Flounderer mentioned, this is related to the likelihood principle. I think that, even more specifically, the "paradox" you're referring to is a violation of the conditionality principle.
The conditionality principle is attractive, since it does seem strange that the interpretation of experimental results would depend on counterfactual results from experiments that were not actually run, but the principle is not universally accepted -- notably, it is not accepted by frequentists.
Answer: You may be referring to the literature surrounding sequential hypothesis testing. This field originated with Abraham Wald during WWII and publication of his book Sequential Analysis around 1948 ... https://www.amazon.com/Sequential-Analysis-Abraham-Wald/dp/0486615790/ref=sr_1_1?s=books&ie=UTF8&qid=1472844126&sr=1-1&keywords=abraham+wald+sequential
More recently, Alexander Tartakovsky's book, also titled Sequential Analysis has become something of the bible in this field for its comprehensive overview ... https://www.amazon.com/Sequential-Analysis-Hypothesis-Changepoint-Probability-ebook/dp/B00MMOIWTS/ref=sr_1_1?s=books&ie=UTF8&qid=1472844136&sr=1-1&keywords=tartakovsky+sequential


Windows 2008 Audit - Acess Request Information

Question: I'm auditing some folders in a Windows 2008 R2 server and I have a "Success Audit" entry in the Security Event Log with the following "Access Request Information":
<code> Access Request Information:
                         Accesses:    %%1537

                         Access Mask:    0x10000
</code>
I'm not sure what type of access "%%1537" is.
What this Access Request Information means to you?
Answer: $1537 = %%1537 = DELETE
I used this blog to help me
http://my.opera.com/Lee_Harvey/blog/2008/10/14/microsoft-windows-security-audit-event-accesses-ids
Hope that answer your question


How to create an Enquiry form with ability to submit a collection of enquiries

Question: I am building a new site which has a large selection of different products/services on offer, the information for each is shown in  it's own node.
If the user has interest in a number of these services then I would like to give them the ability to 'add' the item to their enquiry along with a message. When they have added all of the items they are interested in they can then submit the enquiry.
Overall, the process shares similarities with an e-commerce workflow

View product
Add product to enquiry form builder with comment  (choose options and add to cart)
Browse other products and repeat steps 1&2.
Once happy, review enquiry (checkout)
If all is ok, submit enquiry (process order)

Using Drupal 7, how would you suggest I tackle this?
I only compared the process to e-commerce as it helped me think things through, the site isn't actually going to be selling the products. Strictly a tool to submit a detailed enquiry.
Comment: I've used Flag module and Views to do this with Webform in the past. It required some custom glue as far as I recall.  But Entity forms is newer and much more flexible. Perhaps that is a good place to start looking?
Comment: Entity forms uses core fields instead of the custom fields that Webform uses. So you should be able to add an entity  reference field on your products and services types.
Answer: Switch to Entityform. This uses the core field APIs. Add an entity reference field on your products and services types. Details from the project page:

The Entityform module enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields. This means that out of the box, you can use any standard Drupal node field! As of the time this article was written, there were over three hundred "field" modules. And since Entityforms are "Drupal entities", you will automatically be able to use future "field" modules!
The forms can be used to create custom surveys, petition, and personalized contact forms, and other customized form. (For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.)
As with everything in Drupal, there are Pros and Cons to using Entityform. All though Entityform is a powerful tool, it is not always the best solution. The article When to Use Entityform discusses the advantages and disadvantages that Entityform may have over other methods of creating user "submittable" forms. Do not use Entityform for forms that will contain 150+ form elements

Entity form works well with other modules like Rules so you can get really custom with your behaviours.
Comment: This is great for building my forms, thanks!

What i'm struggling with is deciding how to store the quotes prior to submission.

Once the user adds a service/product to the quote they may browse to other pages, possibly adding new services/products to the quote prior to submission.

My first thought is to use cookies for storing the info. However, could I store the incomplete quotes in the database with a SID - this would let me track abandoned quotes. Not vital but it would be handy.
If that makes sense, is there any modules that might be of use to me?

Thanks!
Comment: As I mentioned in my earlier comments I've used the Flag module in combination with Forms to do exactly what you are trying to do.


scrollable div with fixed element inside

Question: please have a look at this jsfiddle: http://jsfiddle.net/devboell/kjFps/
I need to make a div, whose contents will overflow both horizontally and vertically.
There also needs to be an element that will scroll along horizontally, but remain fixed vertically.
To explain the code:

there is a main container div, and at first I had a single background div that is double the size of the container in x and y direction.
the scale div is the element that should always be visible at the top of the container, but should scroll horizontally.
my thought was to divide the background div in a backgroundHorizontal and backgroundVertical, and then position the scale absolutely in the backgroundHorizontal.
still, when scrolling down, the backgroundVertical pushes the scale up and out of view.

There is also a further requirement, and although I don't want to ask two questions at the same time, I think I should mention it because it might influence the solution for this problem. The requirement is that the vertical scrollbar should alway be visible, and not only when you scroll all the way to the right, like it does now.
Thanks in advance!
Answer: I have faced the similar problem, and can say that according to specification it ia impossible to have div scrollable horizontaly, and fixed vertically at once time.
The solution I used is like:
1. set inside element position to absolue;
$.('container').on('scroll', function(){
$('.inside-element').css('left', $.('container').scrollLeft())
})
Comment: ye, I was afraid of that, although your solution is clean enough as well. I'll wait to see if anyone else responds, and accept your answer later. thanks!


Alternative to passing chord harmonization in closed position

Question: I'm not entirely satisfied with the way I've harmonized the third beat of these trumpet parts, highlighted in the screenshot, for this big band transcription. (The trumpets are playing on their own over the rhythm section for this phrase.)

I'm trying to follow the basic rules of harmonizing parts in the big band swing idiom, in particular no repeated notes (except when the melody note is repeated). I'm also trying to keep to closed position since this is trumpets and I don't want too wide a spread. It seems that I'm therefore forced to harmonize the third beat as a passing chord. But it's a strong beat and to my ear this doesn't sound quite right.
Have I missed something? Is there a better alternative that doesn't result in repeated notes? Should I move outside closed position just for this chord?

So sorry for cutting off the key signature! It is of course E flat.
Comment: Would it not work or be idiomatic to put an 1/8 rest on beat 3 before stating the chord in question off the beat?
Answer: I'm going on the assumption that Eb is your tonic chord and you are using 3 flats in the key signature. If not, please specify what the key is.
I would think of "rules" more as guidelines. Assign importance to the various elements and work as best as you can around them. Having an Ebo7 on beat 3 for a full quarter note might not be ideal and maybe to you it is more important to have that be an Eb7 or Eb9 than break the no repeating rule or maintaining close voicings. In that case it's time to explore bending the rules a bit.
I can think of a few solutions. The first uses no repeated notes and is to open up that voicing and make it Eb,Bb,G,Db. You can substitute F for G in voice 3 if you want the 9th in the voicing. This solution adds some brief contrary motion which isn't bad.
Another solution is to use repeated notes on voices 2-4, or Eb,Db,Bb,G. The down side is the repeated notes but this maintains the close voicing. You can also swap out an F for the G and E for the F in voice 4 which eliminates one repeated note and harmonizes beat 4 as an E7, which also works fine.
Experiment and see what hits your ear best. If you can sequence this into a DAW you can sit back and listen to your options in detail. In the end, maybe the diminished chord is preferable to you but it's good to explore options, even if they break the rules or guidelines because how it sounds to you is more important than the rules.
Answer: I suggest dropping T3 to G and T4 to F, then continuing down chromatically. To my ear, the change in the weight of the chord toward the lower end reinforces the descending line, making it feel like it drops further, because the three lower voices drop by thirds.
No repeated notes, close position, and an "in" chord on beat 3.
NOTE: T2's final Ab was intended to be a G. If using the Ab, the chord should probably be changed to Eb7sus4 to avoid a conflict with the rhythm section playing G against to Ab.

I also like using T3 and T4 as described, but keeping T1 and T2 as in the OP. Just a different take on the same overall sound.
Comment: In your first example voice 2 ends on an Ab but it's an Eb7 chord.
Comment: E♭11? I never thought of that, but it sounds great.
Comment: I decided to go for that first one. Keeping the E♭11 going in the second figure really seems to work, as does bunching T2, 3 and 4 together at the bottom. Thank you.
Comment: @IanGoldby I'm glad you like it. Truthfully, the Ab was a mistake — I meant it to be G. A happy accident, it seems..
Comment: @JohnBelzaguy Yeah. Mistake. I meant it to be a G. I added a note to the post.
Answer: Here's a couple of possibilities.
Comment: No, I meant the C.  Nice crunch!
Comment: Yes, repeating the note in T3&4 after the long note is probably a good compromise. (Your C in T3 must have been intended to be a B♭. T3 C against T2 D♭ is too dissonant for me.)


Abrir arquivos, passando variável como nome do arquivo

Question: Tenho a seguinte situação, um arquivo "tabelas.txt" onde tenho em torno de 2000 linhas com nome de arquivos a qual quero passar linha a linha pegando o nome dos arquivos e verificar quais existem e quais não.
O problema ocorre quando após pegar o nome do arquivo a ser verificado tento passar ele para abri-lo depois ifstream obj (arq), o estranho é que se eu digitar passando a string com o caminho e não a variável arq que é string o arquivo é lido sem problemas.
Segue o código utilizado:
#include <iostream>
#include <fstream>
#include <string>
#include <string>
using namespace std;

int main () {
    string line;
    ifstream myfile ("tabelas.txt");
    if (myfile.is_open()){
        while (! myfile.eof() )
        {
            getline (myfile,line);
            string arq = "..\\dados\\"+ line+".csv";

            ifstream obj (arq);
            if (!obj)
                cerr<<"Ocorreu um erro ao abrir o arquivo"<<endl;
        }
    myfile.close();
    }

    else cout << "Unable to open file";

    return 0;
}

Segue imagem demonstrando o erro:
http://prntscr.com/by4opb
Comment: Não consegui reproduzir o erro http://ideone.com/VCbQyo
Comment: estais utilizando qual IDE? estou utilizando o Dev-C++
Comment: Não usei IDE algum, isso não importa. http://pt.stackoverflow.com/q/101691/101
Comment: Compreendo a diferença entre os termos, porem já vi acontecer erro no dev c o qual não acontecia no Code::Blocks, acabou sendo mais por curiosidade mesmo. Tentei de diversas formas e não foi possível, acabei fazendo em python porem, se possível gostaria de saber como fazer em C++ também, tens alguma outra forma(ex: outra função) que eu possa obter o resultado a qual procuro?
Answer: Reconstruí ele para ler arquivos da forma como normalmente faço.
Segue o código abaixo:
#include <iostream>
#include <fstream>
using namespace std;

int main () {
    ifstream myfile ("x.txt", ifstream::in);
    string line;
    if(myfile.is_open()){
        while(getline(myfile, line)){
            line = "..\\dados\\" + line + ".csv";
            ifstream testfile (line.c_str(), ifstream::in);
            if(testfile.is_open()){
                cout << "O arquivo '"<< line <<"' existe\n";
            }else{
                cout << "O arquivo '" << line << "' nao existe\n";
            }
        }
    }
    myfile.close();

    return 0;
}

Comment: Desculpa, não compreendi o que quisesse dizer com os caracteres estarem codificados.
Comment: Eita, Agora estava funcionando .-.
Comment: Opa!!! Vi somente agora que editou hahah. Seu código funcionou perfeitamente e observei que o diferente entre nossos código era o ".c_str()", somente adicionando isso funcionou, alem disso o meu código apresentou uma performasse maior. Onde seu demorou alguns segundos para demonstrar os arquivos que não existiam enquanto o meu foi "instantâneo". Agradeço muito pela sua ajuda. E vou dar um mix entre os códigos trazendo a melhor parte de cada, pois o seu visivelmente ficou muito melhor que o meu.
Comment: retificando: ambos foram "instantâneos" , eu estava rodando uns processos pesados na maquina no momento que executei o seu !!


Only allow certain roles to publish content, other roles can save as unpublished?

Question: I have a Content Admin and a Translator Roles.
Content Admin's can create, edit, delete, and publish content (this is working fine)
Translator's shouldn't be allowed to publish content, they should only be able to create and edit translations. (it should save as unpublished).
Anyone know how to achieve what I'm trying to do in Drupal 8? Or know if a module that does this has been ported to Drupal 8?
Comment: You need a module for that for sure.
Comment: I found an interesting discussion worth noting. [Change "Save and keep un-/published" buttons to a "Published" checkbox and an included "Save" button](https://www.drupal.org/node/2068063)
Comment: Looks like you will have to custom module it until a stable Rules is out.
Comment: If it was like D7 where you checkbox something to be published, it would be as easy as using hook_node_presave and then checking or unchecking the box. But since D8 is totally different with those 2 buttons, idk how to approach this.
Answer: You will need to alter insert / update node entity form:

Define a permission "Save unpublished content"
Make a hook_form_alter or hook_form_ENTITY_TYPE_form_alter
Check if you are alter the exact entity types you need.
Hide all buttons you don't need (based on permission)
Add button ('save unpublished content') (based on persmission)
When submitting: call the default submission and add yours to set the status 0.

Save button is an UL with two LI elements: save published, save unpublished:


django file upload in 2 steps

Question: I want to upload a file in 2 steps.
First I want to upload it and show the errors and on the second step I
want actually to save the file data in the database.
So I made a simple form and my problem is how to pass the same file to
the form on the second step?
I mean how to insert request.FILES data in the same form again. Or
maybe there is a better way?
Thanks,
Arshavski Alexander.
Comment: maybe you could pass it around within session?
Answer: First,
Using django's inbuilt File field, you don't store the files in the database, but in the filesystem. You only store the metadata in the database.
Next,
If you want to validate a file input, you can use the standard form validation, where you define the the clean_file_field_name and raise the forms.ValidationError django automatically does the "showing of the page until proper input is provided" for you.
That is the right way of doing it.

django file upload in 2 steps


Rails 4.2 constants - where to put them: application.yml vs custom config file.rb

Question: I have some constants I am using throughout my app.
I'd say there are three types:

some are really passwords to external stuff like sendgrid login/password
some are internal "secret codes" like devise secret key
some are just what I'd call global constants that is to say there are constants that we use a lot throughout the app and don't want anybody to easily change this. They nearly never change. Some examples: the ID of our facebook page, or the number of deals "per page" we define in our infinite scrolling on the homepage (critical for UX), or the url of our brand-validated logo on aws cdn(present in many view files html.erb and assets javascript .js files). One aspect I also have in mind when asking my question, is that even if they seem less critical than a devise key, for those constants, I would like to gather, to make sure very few people and only authorized developers can change those critical data.

Here's what we do today:

For 1 and 2: I put the constants on config/application.yml
And for 3 : I put the constants on a custom .rb config file as described by official Rails guide (guides.rubyonrails.org/v4.2/configuring.html#custom-configuration)
For example: on /config/initializers/app_custom.rb
Rails.application.configure do
    config.x.infite_scrollhp_feed_per_page_deals = 30
end

then it is called in a controller this way:
nb_per_page = Rails.configuration.x.infite_scrollhp_feed_per_page_deals

But each time I am unsure if I should put global constants inside config/application.yml or in my custom config .rb file?
What is the recommended "Rails -way"? How to decide where to put them ? Is there a generally accepted "good-sense"/"proven to be efficient/well-structuring" practice/rule ?
Also is there a different in performance that is to say are application.yml "injected" faster into view (.html) and assets(.js) files when user load a page than if they are defined on my custom config file ?
Answer: I would advise using config/secrets.yml for sensitive data (1 and 2):
  development:
    some_password: ...

  test:
    some_password: ...

  production:
    some_password: <%= ENV["SOME_PASSWORD"] %>

This way you can put different settings for different environments (for development, test and production).
And I would highly recommend keeping the production sensitive data in ENV variables.
When it goes for non sensitive data (3) I would put in config/environments/*.rb files when different settings are needed for different environments.
If that's not the case and the setting is the same for all environments, I would put it into application.rb, application.yml or in a custom file in initializers/* or even as class constants.
Comment: `application.yml` is also good place to put it when you have the same settings for all envs.
Comment: then in your vision, what would remain in config/application.yml ? nothing?
Comment: btw, by design the file config/application.yml is not commited inside our repo, so what is inside application.yml remains "secret" :-)
Comment: I would rather commit the `application.yml` to the repo, because the local setup of the app is simpler then. Of course without putting sensitive data there, but fetching them from ENV.
Comment: regarding your last comment, ok but when you say "fetching from ENV", where do you put those ENV ? they're all in in secrets.yml ?
Comment: No, in `secrets.yml` you can read an enviromental variable: `ENV['VARIABLE_NAME']`. But this variable have to be set in your system (for production, directly on production server). You can search google how to set env vriables, eg: "linux how to set environment variables".
Comment: ok thanks, weird. I thought i knew how to do this. in my app the ENV were set in application.yml which was not commited in the repo:)
Comment: Ah.. true. So in your case `application.yml` is used to set the env variables. I didn't picked that up.


Python mido: "OSError: undefined status byte 0xf9"

Question: Got

OSError: undefined status byte 0xf9

while using mido to separate the tracks of musics in a dataset.

The dataset is lakh/Clean MIDI subset. I am not so sure wheather this error is caused by an identified midi file or the python script itself, because the error still shows up when I have deleted the midi file that blocks the running.
The full .py file that I ran:
from mido import Message, MidiFile, MidiTrack
import os

root_dir = r"C:\Users\admin\Desktop\clean_midi"
mid = MidiFile(r"C:\Users\admin\Desktop\clean_midi\.38 Special\Caught Up In You.mid")

musicain_dirs = os.listdir(root_dir)
for dir in musicain_dirs:
    musicain_dir = os.path.join(root_dir, dir)
    if not os.path.exists(dir):
        os.makedirs(dir)
    musics = os.listdir(musicain_dir)
    for music in musics:
        src_mid = MidiFile(os.path.join(musicain_dir, music))
        tar_dir = os.path.join(dir, music)
        if not os.path.exists(tar_dir):
            os.makedirs(tar_dir)
        for track in src_mid.tracks:
            if len(track) > 5:
                tar_mid = MidiFile()
                tar_mid.tracks.append(track)
                tar_name = os.path.join(tar_dir, track.name.replace("/"," ") + "_" + music)
                if not os.path.exists(tar_name):
                    tar_mid.save(tar_name)
        print(music)

I have no idea about this "SPEC_BY_STATUS", and I could not find anything about this list and specs.py.
Comment: Please post the traceback as a text, not a screenshot.
Comment: first you could use `print( os.path.join(musicain_dir, music) )` before `MidiFile(os.path.join(musicain_dir, music)` (which raises error) to see which file makes problem. Maybe you have more files with this problem. Second: maybe you know some tools which can show some information about file midi - and you could check if other tools have also problems with this file. Maybe this file is not correct midi or it uses some new standard which Python doesn't know.
Answer: Problems reading the files
There is something in the MIDI file that mido doesn't like or understand.  Midi.org has a table of status bytes and their meanings that lists status byte value 0xF9 (decimal 249) as "Undefined (Reserved)".  So raising an exception if this occurs in a MIDI file looks like a reasonable action.  Other software might just ignore this status and pretend it isn't there.
Interestingly I can't reproduce this with the given data set, but get the same exception with the status byte value 0xF5, which according to the table is also undefined.  The song is "Always on My Mind" by the Pet Shop Boys.
But that's not the only problem loading MIDI files from that set.  So the code must handle exceptions when creating MidiFile objects.  I encountered a total of 272 files that didn't load with mido for various reasons.  A very obvious one — there is a WAV file: clean_midi/Queen/temp2.wav.  Others have data bytes outside the range of 0…127, or have an unexpected end of file, or there is no MThd signature at the start of the file, and some have more specific problems with notes and modes that don't match somehow.
The code from the question tries to treat each entry in the clean_midi/ directory as a subdirectory — which fails for the two text files in clean_midi/.
So on the readings side the code must make sure it treats only directories as directories, filter for files with the *.mid extension to not pick up the WAV file, and handle exceptions when loading a MIDI file.  For instance by writing out the files path and at least exception type and text, to be able to analyze it later.
Depending on what the goal is, this relatively small amount of unreadable files, 272 of 17,256 total, could just be ignored.
The source of the dataset says for the full dataset of 176,581 MIDI files:

Please note - no attempt was made to remove invalid MIDI files from this collection; as a result it contains a few thousand files which are likely corrupt.

Problems writing the tracks
There are problems on the track writing side too.  At least one track name contains a byte of value 0 which can't be used in file names.
Tracks don't have to have distinct names within a MIDI file, so the code doesn't write track files because they would have the same name as an already written track file.  This could be fixed by including the track number in the file name.  I would also rearrange the order to {tracknumber}_{original_name}_{track_name} so it's easier to see which files belong together when the file names are in the same directory, sorted lexicographically.
Then there is one MIDI file with a really long file name and a really long track name which would result in a 530 character long file name in the original code. That is too long for some file systems.  So the code should limit the file name to a reasonable length.
The revised code
Beside the things specific to the MIDI files mentioned above, the os and os.path functions should be replaced by pathlib to make the code a bit simpler and easier to read and understand.  Also the main program is quite long and nested, so at least splitting a MIDI file into tracks should be factored out into a function.
#!/usr/bin/env python3
from pathlib import Path

from mido import MidiFile

CLEAN_MIDI_PATH = Path("/home/bj/forum/clean_midi")

def log_file_problem(path, type_, message):
    print("----")
    print(path)
    print(type_, message)

def split_midi(midi, file_path, tracks_path):
    for track_number, track in enumerate(midi.tracks, 1):
        if len(track) > 5:
            track_midi = MidiFile()
            track_midi.tracks.append(track)

            track_name = track.name[:100].replace("/", " ").replace("\0", " ")
            track_midi_file_path = (
                tracks_path
                / f"{track_number:03d}_{file_path.stem[-50:]}_{track_name}.mid"
            )
            if track_midi_file_path.exists():
                log_file_problem(
                    track_midi_file_path, "Warning:", "file already exists!"
                )
            else:
                track_midi.save(track_midi_file_path)

def main():
    for musician_source_path in CLEAN_MIDI_PATH.iterdir():
        if musician_source_path.is_dir():
            musician_target_path = Path(musician_source_path.name)
            musician_target_path.mkdir(exist_ok=True)

            for midi_file_path in musician_source_path.glob("*.mid"):
                try:
                    midi = MidiFile(midi_file_path)
                except Exception as error:
                    log_file_problem(midi_file_path, type(error), error)
                else:
                    tracks_path = musician_target_path / midi_file_path.stem
                    tracks_path.mkdir(exist_ok=True)
                    split_midi(midi, midi_file_path, tracks_path)

if __name__ == "__main__":
    main()

Python mido: ”OSError: undefined status byte 0xf9“


DbUpdateConcurrencyException on a DB with no other users. Workaround is failing with a NullException error

Question: New to MVC/EF... My MVC web app was created using the code first from database model since I already had the database (SQLExpress)...
I'm getting the following error when I try an update a record to the database:

Store update, insert, or delete statement affected an unexpected
  number of rows (0). Entities may have been modified or deleted since
  entities were loaded

I got this error when using the standard code generated using the code first from database Entity Framework model.  Strange because I'm working on a standalone machine which no one else has accessing to.
Here is the code that was failing:
if (ModelState.IsValid)
{
    db.Entry(tblPropGroup).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
}

So I wrote the following work around, which worked flawlessly for a while:
if (ModelState.IsValid)
{
db.Entry(_Prop).State = EntityState.Modified;
bool saveFailed;
do
{
 saveFailed = false;
 try
 {
 db.SaveChanges();
 }
 catch (DbUpdateConcurrencyException ex)
 {
 saveFailed = true;
 // Update original values from the database
 var entry = ex.Entries.Single();
 entry.OriginalValues.SetValues(entry.GetDatabaseValues());
 }
} while (saveFailed);

Can anyone explain why db.SaveChanges results in a DbUpdateConcurrencyException on a DB with no other users? It makes no difference if I make any changes to the data or not. I have 22 different tables I'm access in this program, about half won't work without this workaround.
Comment: The only other line of code in that method is the return statement and the viewbag entries in the event that ModelState.IsValid returns false and none of the above code executes.
Comment: Could you show the complete method, I think this is related to the context, maybe it is still open and not closed after a previous operation.
Answer: I suspect this is related to a race condition related to the context of the database.
Here are some answers:
side-effect of a feature called optimistic concurrency
Store update, insert, or delete statement affected an unexpected number of rows (0) EntityFramework
That may help.
It is better to use:
using(DBContext context = new DBContext())
{
    //Entity code
}

To work with your context.
Comment: Thanks looking at this, I am out of town with no access to a computer but I will look into this more when I get back.  Thank you.


assigning setTimeout to global variable and clearing in separate function many times

Question: The code below is meant to move a small red div up the screen when the user presses the spacebar.  In the function 'shoot' i create a new div and set a timeout before it will start moving up the screen from the 'moveLazer' function.
THE PROBLEM:  If you shoot a couple times, the 'lazerLifeCycle' variable clears when one div hits the top of the screen but also clears the timeout for the second or third div that is still moving but not at the top yet.  From what I see, using setInterval doesnt fix the problem.   I know its because lazerLifeCycle is global, but i don't see the right way to do it.  Please help!    The js and html are below.  Note they are 2 different files if you want to copy/paste and try it.  Run it in firefox or chrome.  It doesn't do anything in IE.
//level3.js

var lazerId = 1;

var init = function(){
    var ship = document.getElementById('randRect');
    ship.style.left = '700px';
    ship.style.top = '300px';
}

document.onkeyup = function(e) {
  if(e.keyCode == 37) {
    moveLeft();
  } else if(e.keyCode == 39){
    moveRight();
  } else if(e.keyCode == 32){
    shoot();
  }
}

var shoot = function(){
    lazerId = lazerId + 1;
    var ship = document.getElementById('randRect');
    width = parseInt(ship.clientWidth);
    xPos = parseInt(ship.style.left);
    middle = ((xPos + (width/2)) - 3) + 'px'; //-3 is to center it i think
    var lazer = document.createElement('div');
    lazer.id = lazerId;
    var body = document.getElementById('body');
    body.appendChild(lazer);
    lazer.style.position = 'absolute';
    lazer.style.width = '7px';
    lazer.style.height = '13px';
    lazer.style.left = middle;
    lazer.style.top = '287px';
    lazer.style.backgroundColor = 'red';
    lazerLifeCycle = setTimeout('moveLazer(' + lazerId.toString() + ');', 10);
}

var moveLazer = function(lazerElementId){
    var lazer = document.getElementById(lazerElementId.toString());
    var lazerTop = parseInt(lazer.style.top);
    if( (lazerTop - 1) < 0){
        lazer.style.top = '0px';
        clearTimeout(lazerLifeCycle);
    } else {
        lazer.style.top = (lazerTop - 1) +'px'
        lazerLifeCycle = setTimeout('moveLazer(' + lazerElementId.toString() + ');', 10);
    }
}

var moveLeft = function(){
    var ship = document.getElementById('randRect');
    shipXPos = parseInt(ship.style.left);
    if( (shipXPos - 15) < 0){
        ship.style.left = 0+'px';
    } else {
        ship.style.left = shipXPos - 15+'px';
    }
}

var moveRight = function(){
        var ship = document.getElementById('randRect');
    shipXPos = parseInt(ship.style.left);
    if( (shipXPos + 15) > 1300){
        ship.style.left = 1300+'px';
    } else {
        ship.style.left = shipXPos + 15+'px';
    }
}

window.onload = init;

//level3.html

        <title>random</title>

<-- or -->

Answer: Working Demo
Ok heres a simplified vs with changed code.
var shoot = function(){
    lazerLifeCycle = moveLazer(lazerId);
}

var moveLazer = function(lazerElementId){
    var lazer = document.getElementById(lazerElementId.toString());
    var lazerTop = parseInt(lazer.style.top);
    if( (lazerTop - 1) < 0){
        lazer.style.top = '0px';
    } else {
        lazer.style.top = (lazerTop - 1) +'px'
        setTimeout(function(){moveLazer(lazerElementId);}, 10);
    }
}

Basically you dont need to worry about clearing timeouts, since they dont reoccur unless you tell them to. Also to make it to where you can shoot more than one lazer you just need to reference the ID that was passed to moveLazer to begin with. Basically it will continue on until the lazer hits the top. Also allowing the support of multiple shots.


Function f(1/n)=1/n!

Question: I am trying to work on a problem in complex analysis. Although I know how to solve it, I am only stuck at one point.
The problem asks if there exist a holomorphic function $f$ on the unit disk such that $f(\frac{1}{n})=\frac{1}{n!}$.
Here, the approach will be to consider another function $g$ that coincides with $f$ on a discrete set (mainly $\{\frac{1}{n};n \in \mathbb{N}$}) and use the uniqueness theorem to show that they coincide with each other everywhere on the unit ball.
Now, if our function $g$ is not analytic on the unit ball, we will get what we need.
I cannot find such function $g$. It is easy to do it when $f(n)=\frac{1}{n+1}$ but here the factorial is making it a little bit difficult.
Comment: Related: [holomorphic function on punctured disk satisfying $\left|f\left(\frac{1}{n}\right)\right|\leq\frac{1}{n!}$ has an essential singularity at $0$](https://math.stackexchange.com/questions/2104353/holomorphic-function-on-punctured-disk-satisfying-leftf-left-frac1n-righ)
Comment: Your logic seems flawed to me: if $g$ is not analytic, then you have no reason to claim that it coincides with $f$ on the unit ball. For instance, you could just define $g(\frac{1}{n})=\frac{1}{n!}$ and $g(x)=0$ if $x$ is not the reciprocal of a positive integer; but it is clear that this proves nothing.
Comment: Do you know a complex function that extends the positive integers factorial? I'm thinking $f(x) = \frac{1}{\Gamma(x+1)}$
Comment: I do not. I can read about it. It is not analytic on the u it disk?
Comment: Yeah you are totally right. I think this would have worked if f analytic on a bigger disk and we only need them to coincide on the smaller one.
Answer: The idea is simply that such a function, to exist, would have to be "too flat". More formally: let $f$ be an hypotetical holomorphic function that satisfies your hypothesis. It would then satisty:
$$f(0)=\lim f(\frac 1n)=\lim \frac 1{n!}=0\\
f'(0)=\lim \frac{f(\frac 1n)}{\frac{1}{n}}=\lim \frac{n}{n!}=0\\
f^{(k)}=k!\lim \frac{f(\frac 1n)}{n^k}=k!\lim \frac{n^k}{n!}=0
$$
Thus $f=\sum \frac{f^{(n)}(0)z^n}{n!}=0$, which contradicts $f(\frac 1n)=\frac 1{n!}$
Answer: There is no such function. If there was, its Taylor series centered at $0$ would be of the form$$a_kz^k+a_{k+1}z^{k+1}+\cdots,$$for some $k\in\mathbb N$ and $a_k\neq0$. But then$$\lim_{n\to\infty}\frac{\left\lvert f\left(\frac1n\right)\right\rvert}{\left\lvert\frac{a_k}{n^k}\right\rvert}=1.$$In particular$$\lim_{n\to\infty}\frac{\left\lvert f\left(\frac1n\right)\right\rvert}{\frac1{n^k}}\neq0.$$But$$\lim_{n\to\infty}\frac{\frac1{n!}}{\frac1{n^k}}=0.$$
Comment: Thank you. Both answers make sense. Do you think there is an approach using the uniqueness theorem without going through the gamma function?
Comment: I don't think so.

Function f(1/n)=1/n!


Somar valores depois de um separador

Question: Como não sei muito de javascript gostaria de uma ajudinha para resolver esse meu problema
Nesse script abaixo tenho que fazer o calculo pegando só os últimos dígitos separados pelo hífen -
value="10-banana-2,55" ==> só somar o  ( 2,55 ) depois do segundo traço

id-nome-valor

$(function() {
  total = document.getElementById('total');
  $(document.getElementsByName('choice')).bind('click', function() {

    var valTotal = total.value;

    valTotal = parseFloat(valTotal.replace(',', '.'));

    var valInput = (this.value);

    valInput = parseFloat(valInput.replace(',', '.'));

    var novoTotal = 0;
    var value = (this.checked) ? parseFloat((valTotal + valInput)).toFixed(2) : parseFloat((valTotal - valInput)).toFixed(2);
    total.value = value.replace('.', ',');
  });

});

<form name="listForm" id="listForm">
  <input type="checkbox" name="choice" value="10-banana-2,55" />2,55

  <input type="checkbox" name="choice" value="12-uva-3,00" />3,00

  <input type="checkbox" name="choice" value="13-pera-1,00" />1,00

  <input type="checkbox" name="choice" value="16-tmate-2,00" />2,00

  <input type="text" size="4" name="total" id="total" value="100,00" />
</form>
Answer: Tens de partir esse valor em pedaços mas também converter Strings 2,55 em Numeros com ..
Sugestão:

$(function() {
  function converterNumero(nr) {
    if (typeof nr === 'number') return nr;
    return Number(nr.replace(',', '.'));
  }

  var total = $('#total');
  var escolhas = $('[name="choice"]');
  escolhas.on('change', function() {

    var soma = escolhas.get().reduce(function(soma, el) {
      if (!el.checked) return soma;
      var nr = el.value.split('-').pop();
      var value = converterNumero(nr);

      return soma + value;
    }, Number(converterNumero(total.val())));
    total.val(soma);
  });
});

<form name="listForm" id="listForm">
  <input type="checkbox" name="choice" value="10-banana-2,55" />2,55

  <input type="checkbox" name="choice" value="12-uva-3,00" />3,00

  <input type="checkbox" name="choice" value="13-pera-1,00" />1,00

  <input type="checkbox" name="choice" value="16-tmate-2,00" />2,00

  <input type="text" size="4" name="total" id="total" value="100,00" />
</form>
Answer: Utilizando o seu script, para não complicar muito e você entender o que se passar, pode fazer assim
$(function() {
        total = document.getElementById('total');

        $(document.getElementsByName('choice')).bind('click', function() {

            var valTotal = total.value;

            valTotal = parseFloat(valTotal.replace(',', '.'));

            // Pega o valor selecionado e divide pelo '-', o resultado do split gera um array
            var valInput_split = (this.value).split('-');

            // Pega o último valor deste array, que no seu caso é o valor que você quer somar
            var valor_final = valInput_split[valInput_split.length-1];

            var valInput = parseFloat(valor_final.replace(',', '.'));

            var novoTotal = 0;
            var value = (this.checked) ? parseFloat((valTotal + valInput)).toFixed(2) : parseFloat((valTotal - valInput)).toFixed(2);
            total.value = value.replace('.', ',');
        });

    });

Em resumo basta troca restas duas linhas
var valInput = (this.value);
valInput = parseFloat(valInput.replace(',', '.'));

Por estas três linhas
var valInput_split = (this.value).split('-');
var valor_final = valInput_split[valInput_split.length-1];
var valInput = parseFloat(valor_final.replace(',', '.'));

Answer:
Não use mais .bind porque ele se tornou obsoleto desde a versão 1.7
  do jQuery e foi removido da versão 3.0.

Uma sugestão para pegar o valor é usar o método .substr(). Basta usar como argumento único o .lastIndexOf("-")+1, ou seja, irá pegar o primeiro caractere após o último hífen até o final da string.
No exemplo abaixo substituí alguns métodos JS puro por métodos jQuery:

$(function() {
   var total = $('#total');
  $('[name=choice]').on('click', function(){

    var valTotal = total.val();

    valTotal = parseFloat(valTotal.replace(',', '.'));

    var valInput = this.value.substr(this.value.lastIndexOf("-")+1);

    valInput = parseFloat(valInput.replace(',', '.'));

    var novoTotal = 0;
    var value = (this.checked) ? parseFloat((valTotal + valInput)).toFixed(2) : parseFloat((valTotal - valInput)).toFixed(2);
    total.val(value.replace('.', ','));
  });

});

<form name="listForm" id="listForm">
  <input type="checkbox" name="choice" value="10-banana-2,55" />2,55

  <input type="checkbox" name="choice" value="12-uva-3,00" />3,00

  <input type="checkbox" name="choice" value="13-pera-1,00" />1,00

  <input type="checkbox" name="choice" value="16-tmate-2,00" />2,00

  <input type="text" size="4" name="total" id="total" value="100,00" />
</form>

Somar valores depois de um separador


Split short exact sequence contradiction

Question: Am I doing it wrong or is this an exception to the split rules?
There is a short exact sequence
$$1 \longrightarrow \mathbb Z/_{2\mathbb Z} \hookrightarrow \mathbb Z/_{4\mathbb Z} \twoheadrightarrow \mathbb Z/_{2\mathbb Z} \longrightarrow 1$$
Using group representations
$\mathbb Z/_{2\mathbb Z} \simeq \left\{\begin{pmatrix}-1&0\\0&-1\end{pmatrix}, \begin{pmatrix}1&0\\0&1\end{pmatrix}\right\}$ and $\mathbb Z/_{4\mathbb Z} \simeq \left\{\begin{pmatrix}-1&0\\0&-1\end{pmatrix},\begin{pmatrix}1&0\\0&1\end{pmatrix}, \begin{pmatrix}0&1\\-1&0\end{pmatrix}, \begin{pmatrix}0&-1\\1&0\end{pmatrix}\right\}$
There cannot be any retraction but using the surjection $\rho : \begin{pmatrix}a&b\\c&d\end{pmatrix} \longmapsto ad + bc$
isn't there a section $\iota : \begin{pmatrix}-1&0\\0&-1\end{pmatrix} \longmapsto \begin{pmatrix}0&-1\\1&0\end{pmatrix}$ ?
This would imply that we have a semi-direct product but I know this is not the case because $\mathbb Z/_{4\mathbb Z} \not\simeq \mathbb Z/_{2\mathbb Z} \rtimes \mathbb Z/_{2\mathbb Z} \simeq \mathbb Z/_{2\mathbb Z} \times \mathbb Z/_{2\mathbb Z}$...
What gives ?
Answer: Your $\iota$ is not a homomorphism. $\iota(-I)^2 \ne \iota((-I)^2)$.
Comment: Damn, I missed that. Obviously ^^ Thx


Field extension of degree two is normal

Question: I want to show that each extension of degree $2$ is normal.
I have done the following:
Let $K/F$ the field extension with $[F:K]=2$.
Let $a\in K\setminus F$. Then we have that $F\leq F(a)\leq K$.
We have that $[K:F]=2\Rightarrow [K:F(a)][F(a):F]=2$.
There are the following possibilities:

$[K:F(a)]=1$ and $[F(a):F]=2$
In this case we have that $K=F(a)$ and $\deg m(a,F)=2$.
In $K$, since $a\in K$, we have that $m(a,F)=(x-a)g(x)$, with $\deg g(x)=1$. Since $g$ is a linear polynomial of $K[x]$ , so it is of the form $x-c$, so its root $c$ must belong to $K$.
That means that $m(a,K)$ splits in $K$, i.e., all the roots are in $K$. Does this mean then that all the irreducible polynomials that have one root in $K$, have all the roots in $K$ ? Or how do we conclude then that the extension $K/F$ is normal ?
$[K:F(a)]=2$ and $[F(a):F]=1$
In this case we have that $F=F(a)$, and so $a\in F$, a contradiction.

Is this correct? Could I improve something?
Comment: This is basically right, but normality means that if an irreducible polynomial $f \in F[x]$ has a root in $K$, then all of the roots of $f$ lie in $K$. So apply your argument directly to prove this fact.
Comment: A theorem says that $L/K$ is normal (and finite) if only if $L$ is the splitting field of some polynomial in $K[x]$.
Comment: If an irreducible polynomial (assume it's monic by dividing out by the leading coefficient) $f \in F[x]$ has a root $\alpha \in K$, then $f$ is the minimal polynomial of $\alpha$ (why?). Then follow your argument. Alternatively, consider Charter's response.
Comment: Up to scaling, yes
Comment: Normality means that **all** the irreducible polynomials in $F[x]$ satisfy this property, or not? Knowing that the minimal polynomial satisfy this property, how can we conclude that all the irreducible polynomials have all the roots in $K$ ? @AshwinIyengar
Comment: Does it maybe hold that all the polynomials other than the $m(a,F)$ are multiples of $m(a,F)$ and so not irreducible, because of the following? We are looking the polynomials in $F[x]$ that have roots in $F[a]$. So, either the polynomials have roots in $F$ and then they are not irreducible in $F[x]$ or they have roots in $F[a]$, i.e., they have as root an expression of $a$. If they have as a root $a$, then they are a multiple of $m(a,F)$. Can it be that they have an other polynomial expression of $a$ as a root, for example $a^2$ ?  @AshwinIyengar
Comment: In my notes there is the following definition:
$$$$
$E/F$ normal $\Leftrightarrow$ each irreducible of $F[x]$ that has a root in $E$, has all its roots in $E$ (it splits in E)
$$$$
$E/F$ normal $\Leftrightarrow$ each irreducible of $F[x]$ has either no root in $E$ or it splits in $E$ $$$$ @Charter
Comment: Do we have that if an irreducible polynomial $f\in F[x]$ has a root $a\in K$, then $f$ is the minimal polynomial of $a$, because otherwise we there would be a polynomial with smaller degree than $f$ that has the root $a$. Is this not possible? @AshwinIyengar
Comment: Ah ok... Thank you!! :-) @AshwinIyengar
Answer: The idea of your solution is ok but there are little mistakes. First of all, it's $[K:F]=2$ and not $[F:K]=2$. Now you have $\deg m(a,F)=2$, and since $a$ is a root of $m(a, F)$ we can write in $K$: $m(a, F)=(x-a)g(x)$, using that $\deg m(a, F)=2$ we get $\deg g(x)=1$, so $g(x)$ has a root $c\in K$. This means that $m(a, F)\in F[x]$ splits in $K$, so by theorem that I wrote in the commentaries we have that $K/F$ is normal.
Alternatively, you can use the well-known fact that if $G$ is a group and $H$ is a subgroup of $G$ such that $|G:H|=2$, then $H$ is a normal subgroup of $G$, and then apply the fundamental theorem of Galois theory.
Comment: @MaryStar yeah, it's correct, but I prefer to define a normal extension $E/F$ to be an extension where "each irreducible of $F[x]$ that has a root in $E$, has all its roots in $E$." Using this definition is easy to prove the theorem that I used in my answer.
Comment: So, is the statement of my notes that every irreducible polynomial must have either all the roots or no root $K$, wrong?
Comment: Ah ok... How could we prove it? Could you give me a hint?
Comment: With "some polynomials" of your Theorem are the ones meant that have a Root in E?
Comment: It's not "some polynomials" but just "one polynomial", and yes, that polynomial splits in $E$. For a proof of the theorem you can check chapter 9, section 9.2 of Stewart's book "Galois Theory" (3rd edition).

Field extension of degree two is normal


Proof that $\left(\frac{1}{x}, \frac{1}{y}\right)$ is a convex region if $(x, y)$ is

Question: I'm trying to convince (prove) myself that if a set $S \subset \mathbb{({R^+})^2}$ is a convex region, then $S' := \left\{ \left(\frac1{x}, \frac1{y}\right) ; (x, y)\in S \right\}$ is also a convex region. I've tried using the definition of convexity, and the couple of convexity-preserving transformations (linear, affine, etc.) but I still can't establish my claim. Is my claim even true?
The closest I've gotten to show this is that $(x,y) \text{ is convex} \implies (x,y,1) \text{ is convex} \implies \left (1, \frac{y}{x}, \frac{1}{x}\right) \text{ is convex (perspective transform)} \implies \left (\frac1x, \frac{y}{x}\right) \text{ is convex}$
Here by $(x, y)$ I am abusing notation to refer to the set $S$.
PS: For the problem I'm actually trying to solve, $S$ is the interior of an ellipse, so even if my claim isn't true for general $S$, could it be true for this particular case?
Comment: An inequality which can be useful (a version of the fact than Arithmetical Mean larger the Harmonic Mean) $\frac{1/x+1/y}{2} \ge \frac{1}{(\tfrac{x+y}{2})}.$
Answer: It is not true, not even for an ellipse. A line segment (and hence, a sufficiently thin ellipse) may be warped by the transformation, see example picture below.
Comment: I think you should swap the red and the blue dot on the straight line, no? $(3,1)$ gets mapped to $( 1/3, 1).$
Comment: Though it might still be true for circles
Comment: Whoops, oh well
Comment: A great answer. Now, I checked for the circle $(1.5, 1.5) + (\cos t, \sin t)$ and the image is visibly concave. [link](https://www.wolframalpha.com/input/?i=ParametricPlot%5B+%7B1%2F%28Cos%5Bt%5D+%2B+1.5%29%2C+1%2F%28Sin%5Bt%5D%2B1.5%29%7D%2C+%7Bt%2C0%2C2Pi%7D%5D)
Comment: Great counter-example, thanks!