Reiniciar aplicação - Python

Question: Bom dia pessoal, tudo bem? Estou aprendendo ainda a programar em python, sou iniciante. Estou fazendo uma simples calculadora para fazer calculo de peso e custo de matéria prima. Queria que ele reiniciasse caso uma resposta fosse fora dos padrões necessários (atualmente o programa só trava para qualquer resposta errada). Se alguem puder me dar alguma dica por favor. Segue demonstração de como está, obrigado desde já.
while True:
    print("Utilize apenas valores com ponto, e não virgula!" '\n')
    tipo = input ("1020, 1045, 4340, ou 8620? ")
    if (tipo == "1020" or tipo == "1045"): ###1020###
        material = input('Chapa (C) ou barra (B)? ')
        if (material == "C" or material == "c"): ###CALCULO CHAPA###
            altura = float(input('ALTURA: '))
            largura = float (input ('LARGURA: '))
            comprimento = float (input ('COMPRIMENTO: '))
            peso= round ((altura * largura * comprimento * 7.85 / 1000000),3)
            resultado=print ('\n' f'>>>>>>>> PESO CHAPA 1020/1045: {peso} KG <<<<<<<<\n')
            preço = round ((peso * 7),3)
            print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n')
            print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS CHAPA 1020###
            altura1 = float (input ("ALTURA FINAL: "))
            largura1 = float (input ("LARGURA FINAL: "))
            comprimento1 = float (input ("COMPRIMENTO FINAL: "))
            peso1= largura1 * altura1 * comprimento1 * 7.85 / 1000000
            resultado1=print ('\n' f'>>>>>>>> PESO FINAL DA PEÇA: {peso1} KG <<<<<<<<\n')
        elif (material == "B" or material == "b"): ###CALCULO BARRA###
            diametro = float(input('DIAMETRO: '))
            comprimento = float (input ('COMPRIMENTO: '))
            peso= (diametro * diametro * 3.1416 * 7.85 / 4000) * (comprimento/1000)
            resultado=print ('\n' f'>>>>>>>> PESO BARRA 1020/1045: {peso} KG <<<<<<<< \n') ###PESO###
            preço = peso * 7
            print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n') ###PREÇO###
            print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS BARRA 1020###
            diametro1 = float (input ("DIAMETRO FINAL: "))
            comprimento1 = float (input ("COMPRIMENTO FINAL: "))
            peso1 = (diametro1 * diametro1 * 3.1416 * 7.85 / 4000) * (comprimento1/1000)
            resultado1=print (f'\n>>>>>>>> PESO FINAL DA PEÇA {peso1} KG <<<<<<<<\n')
        tempera = input ("POSSUI TEMPERA? (S/N) ") ###TEMPERA###
        if (tempera == "S" or tempera == "s"):
            custotratamento= 6.10 * peso1
            print ('\n' f'>>>>>>>> TEMPERA: R$ {custotratamento} <<<<<<<<\n')
        elif (tempera == "N" or tempera == "n"):
            custotratamento = 0
        oxidacao = input ("POSSUI OXIDAÇÃO? (S/N) ") ###OXIDAÇÃO###
        if (oxidacao == "S" or oxidacao == "s"):
            custooxidacao= 2 * peso1
            print ('\n' f'>>>>>>>> OXIDAÇÃO: R$ {custooxidacao} <<<<<<<<\n')
        elif (oxidacao == "n" or oxidacao == "N"):
            custooxidacao = 0
            print ('\n')

Answer: O problema ocorre quando não é um digitado um número válido, e a conversão para float lança um ValueError, o que encerra a execução do programa.
As outras respostas estão sugerindo colocar todo o código dentro de um try/except, o que de fato funcionaria. Mas aí qualquer erro em qualquer ponto do programa faria o loop se repetir novamente desde o início. Ou seja, se o usuário já digitou quase todos os valores e só deu erro no último, o programa voltaria para o início e pediria todos os valores novamente.
Não seria melhor se ele só pedisse para digitar novamente a informação que deu erro, e mantivesse as demais? Neste caso, a abordagem seria um pouco diferente.
De forma geral, você pode fazer um loop para uma informação específica, e só pedir que digite novamente em caso de erro. Um algoritmo mais geral seria algo como:
repetir enquanto não tem dados válidos:
    ler o dado
    converter (para número, por exemplo)
    validar (se é um número mesmo, ou se o valor é um dos válidos ("s" ou "n", por exemplo))
    se deu erro, volta para início do loop
    se o valor é válido, sai do loop

Em Python, uma alternativa para isso seria:
def ler_valores(mensagem, mensagem_erro=None, conversao=None, valores_validos=None):
    while True:
        try:
            dado = input(mensagem)
            if conversao: # se tem conversão a ser feita
                dado = conversao(dado)
            if valores_validos: # se tem uma lista de valores válidos
                if dado in valores_validos: # verifica se é um dos valores válidos
                    return dado
                else:
                    print('Você só pode digitar um dos valores válidos:', ', '.join(map(str, valores_validos)))
            else:
                return dado
        except ValueError:
            print('digite um valor válido' if mensagem_erro is None else mensagem_erro)

Aí basta trocar o seu loop para usar esta função. Quando eu quero ler um número, a conversão é float, e quando estou lendo as opções (como "C"/"B", ou "S"/"N"), a conversão pode ser "transformar em maiúscula" e a lista de valores válidos são as respectivas letras. Ficaria assim:
tipos_validos = [ '1020', '1045', '4340', '8620' ]

while True:
    print("Utilize apenas valores com ponto, e não virgula!\n")
    tipo = ler_valores(f'Digite o tipo ({", ".join(map(str, tipos_validos))}): ', valores_validos=tipos_validos)
    if tipo == "1020" or tipo == "1045":
        material = ler_valores('Chapa (C) ou barra (B)? ', conversao=lambda s: s.upper(), valores_validos=['C', 'B'])
        if material == "C": ###CALCULO CHAPA###
            altura = ler_valores('ALTURA: ', conversao=float)
            largura = ler_valores('LARGURA: ', conversao=float)
            comprimento = ler_valores('COMPRIMENTO: ', conversao=float)
            peso = round(altura * largura * comprimento * 7.85 / 1000000, 3)
            print(f'\n>>>>>>>> PESO CHAPA 1020/1045: {peso} KG <<<<<<<<\n')
            preço = round(peso * 7, 3)
            print(f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n')
            print('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS CHAPA 1020###
            altura1 = ler_valores('ALTURA FINAL: ', conversao=float)
            largura1 = ler_valores('LARGURA FINAL: ', conversao=float)
            comprimento1 = ler_valores('COMPRIMENTO FINAL: ', conversao=float)
            peso1 = largura1 * altura1 * comprimento1 * 7.85 / 1000000
            print(f'\n>>>>>>>> PESO FINAL DA PEÇA: {peso1} KG <<<<<<<<\n')
        elif material == "B": ###CALCULO BARRA###
            diametro = ler_valores('DIAMETRO: ', conversao=float)
            comprimento = ler_valores('COMPRIMENTO: ', conversao=float)
            peso = (diametro * diametro * 3.1416 * 7.85 / 4000) * (comprimento / 1000)
            print(f'\n>>>>>>>> PESO BARRA 1020/1045: {peso} KG <<<<<<<< \n') ###PESO###
            preço = peso * 7
            print(f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n') ###PREÇO###
            print('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS BARRA 1020###
            diametro1 = ler_valores('DIAMETRO FINAL: ', conversao=float)
            comprimento1 = ler_valores('COMPRIMENTO FINAL: ', conversao=float)
            peso1 = (diametro1 * diametro1 * 3.1416 * 7.85 / 4000) * (comprimento1 / 1000)
            print(f'\n>>>>>>>> PESO FINAL DA PEÇA {peso1} KG <<<<<<<<\n')

        tempera = ler_valores("POSSUI TEMPERA? (S/N) ", conversao=lambda s: s.upper(), valores_validos=['S', 'N'])
        if tempera == "S":
            custotratamento = 6.10 * peso1
            print(f'\n>>>>>>>> TEMPERA: R$ {custotratamento} <<<<<<<<\n')
        elif tempera == "N":
            custotratamento = 0
        oxidacao = ler_valores("POSSUI OXIDAÇÃO? (S/N) ", conversao=lambda s: s.upper(), valores_validos=['S', 'N']) ###OXIDAÇÃO###
        if oxidacao == "S":
            custooxidacao = 2 * peso1
            print(f'\n>>>>>>>> OXIDAÇÃO: R$ {custooxidacao} <<<<<<<<\n')
        elif oxidacao == "N":
            custooxidacao = 0
            print('\n')

Repare que \n pode ficar na própria string, não precisa colocá-lo separadamente. Outro detalhe é que print não retorna nada (tecnicamente, ele retorna sempre None), então não faz sentido fazer resultado = print(etc). Faça apenas print(etc) e pronto (até porque você não está usando essas variáveis resultado para nada, e mesmo que usasse, o valor delas seria None, então elas são desnecessárias de qualquer maneira e podem ser removidas).
Uma das respostas estava sugerindo criar uma função e chamar ela mesma dentro do except (antes de ser editada), o que é um uso totalmente errado de recursão (que é quando uma função chama ela mesma, saiba mais lendo aqui e aqui). Apesar de "funcionar", depois de um certo número de iterações, pode haver um estouro de pilha (já usando o loop acima, ele pode se repetir quantas vezes quiser, que não haverá este problema). Agora a resposta foi editada e a recursão foi retirada, menos mal.

Outra opção é usar a função ler_valores para criar versões mais especializadas dela. Por exemplo:
def ler_float(mensagem, mensagem_erro=None):
    return ler_valores(mensagem, mensagem_erro, conversao=float)

def ler_sn(mensagem, mensagem_erro=None): # lê opção sim ou não
    return ler_valores(mensagem, mensagem_erro, conversao=lambda s: s.upper(), valores_validos=['S', 'N'])

Aí basta fazer algo como:
altura = ler_float('ALTURA: ')
largura = ler_float('LARGURA: ')
etc...

tempera = ler_sn("POSSUI TEMPERA? (S/N) ")

Se bem que dá para fazer ainda:
def ler_varios_float(*mensagens):
    return [ ler_float(mensagem) for mensagem in mensagens ]

...
altura, largura, comprimento = ler_varios_float('ALTURA: ', 'LARGURA: ', 'COMPRIMENTO: ')
...
altura1, largura1, comprimento1 = ler_varios_float('ALTURA FINAL: ', 'LARGURA FINAL: ', 'COMPRIMENTO FINAL: ')
etc...

O loop não inclui uma opção para sair, então o programa fica se repetindo indefinidamente. Uma opção seria colocar algum valor para que o mesmo saia, algo assim:
tipos_validos = [ '1020', '1045', '4340', '8620', '0' ]

while True:
    print("Utilize apenas valores com ponto, e não virgula!\n")
    tipo = ler_valores(f'Digite o tipo ({", ".join(map(str, tipos_validos))}) ou "0" para sair: ', valores_validos=tipos_validos)
    if tipo == '0': # não precisa converter para int, é meio redundante aqui
        break # digitou zero, sai do loop
    if tipo == "1020" or tipo == "1045":
        etc...

Comment: (Tive 3 ótimas respostas entao provalvemente vou repetir esse comentário para as 3, mas...) Que aula!! Hahaha bastante informação nova para eu assimilar, estou estudando faz poucos dias. Vou levar um tempo para entender todos os códigos novos que foram inseridos por vocês, mas desde já muitissimo obrigado! Já foi muito esclarecedor. <3 Obrigado por dedicar seu tempo pra me ajudar. Abração!
Answer: Você pode usar while's ao invés de if's e aí ele só vai passar dessa parte quando os valores forem válidos.
while True:
    print("Utilize apenas valores com ponto, e não virgula!" '\n')

    tipo = input ("1020, 1045, 4340, ou 8620? ")
    while(tipo != "1020" and tipo != "1045"):
        tipo = input ("Valor inválido. 1020, 1045, 4340, ou 8620? ")

    material = input('Chapa (C) ou barra (B)? ').upper()
    while (material != 'C' and material != 'B'):
        material = input('Material inválido. Chapa (C) ou barra (B)? ').upper()

    if (material == "C"): ###CALCULO CHAPA###
        aux = True
        while(aux):
            try:
                altura = float(input('ALTURA: '))
                largura = float (input ('LARGURA: '))
                comprimento = float (input ('COMPRIMENTO: '))
                peso= round ((altura * largura * comprimento * 7.85 / 1000000),3)
                resultado=print ('\n' f'>>>>>>>> PESO CHAPA 1020/1045: {peso} KG <<<<<<<<\n')
                preço = round ((peso * 7),3)
                print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n')
                aux = False
            except:
                print('Valores inválidos.')

        aux = True
        while(aux):
            try:
                print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS CHAPA 1020###
                altura1 = float (input ("ALTURA FINAL: "))
                largura1 = float (input ("LARGURA FINAL: "))
                comprimento1 = float (input ("COMPRIMENTO FINAL: "))
                peso1= largura1 * altura1 * comprimento1 * 7.85 / 1000000
                aux = False
            except:
                print('Valores inválidos')
        resultado1=print ('\n' f'>>>>>>>> PESO FINAL DA PEÇA: {peso1} KG <<<<<<<<\n')

    else: ###CALCULO BARRA###
        aux = True
        while(aux):
            try:
                diametro = float(input('DIAMETRO: '))
                comprimento = float (input ('COMPRIMENTO: '))
                peso= (diametro * diametro * 3.1416 * 7.85 / 4000) * (comprimento/1000)
                resultado=print ('\n' f'>>>>>>>> PESO BARRA 1020/1045: {peso} KG <<<<<<<< \n') ###PESO###
                preço = peso * 7
                print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n') ###PREÇO###
                aux = False
            except:
                print('Valores inválidos')

        aux = True
        while(aux):
            try:
                print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS BARRA 1020###
                diametro1 = float (input ("DIAMETRO FINAL: "))
                comprimento1 = float (input ("COMPRIMENTO FINAL: "))
                peso1 = (diametro1 * diametro1 * 3.1416 * 7.85 / 4000) * (comprimento1/1000)
                resultado1=print (f'\n>>>>>>>> PESO FINAL DA PEÇA {peso1} KG <<<<<<<<\n')
                aux = False
            except:
                print('Valores inválidos')

    tempera = input("POSSUI TEMPERA? (S/N) ").upper() ###TEMPERA###
    while (tempera != 'S' and tempera != 'N'):
        tempera = input("Resposta inválida. POSSUI TEMPERA? (S/N) ").upper()

    if (tempera == "S"):
        custotratamento= 6.10 * peso1
        print ('\n' f'>>>>>>>> TEMPERA: R$ {custotratamento} <<<<<<<<\n')
    else:
        custotratamento = 0

    oxidacao = input ("POSSUI OXIDAÇÃO? (S/N) ").upper() ###OXIDAÇÃO###
    while (oxidacao != 'S' and oxidacao != 'N'):
        oxidacao = input ("Resposta inválida. POSSUI OXIDAÇÃO? (S/N) ").upper()

    if (oxidacao == "S"):
        custooxidacao= 2 * peso1
        print ('\n' f'>>>>>>>> OXIDAÇÃO: R$ {custooxidacao} <<<<<<<<\n')
    else:
        custooxidacao = 0
        print ('\n')
    print('FIM')
    print('')

Na parte de conferir as respostas ele passa tudo pra letra maiúscula utilizando a função upper, então não precisa botar duas comparações pois sempre vai ser em letra maíuscula.
Comment: Essa não é a melhor forma para consertar isso, quando eu chegar em casa vou lhe mostrar uma solução melhor. Mas essa "gambiarra" deve funcionar se você estiver com muita pressa
Comment: Não estou com pressa não hahahah se puder mostrar depois a outra forma (se for diferente dos outros dos outros comentarios) eu vou ler atentamente. Estou começando entao qualquer dica de alguem mais experiente já é super válida! Desde já muito obrigado!!!
Comment: Editei minha resposta. Agora a solução está bem melhor!
Comment: Mais uma aula que recebo! Hahahaha brigadão Natan. Vou olhar com calma e estudar para entender toda a estrutura. Como estou começando eu olho e ainda não entendo algumas coisas, mas me ajudou muito! Muitissimo obrigado por dedicar seu tempo pra me ajudar. Grande abraço!!
Answer: Olá! Pelo o que eu entendi o erro está acontecendo nos inputs, em que se a pessoa colocar um valor fora do pedido da erro, se for isso você pode fazer isso:
while True:
    print("Utilize apenas valores com ponto, e não virgula!" '\n')
    #a questão da vígula você pode resolver com um replace:
    #numero_float = float(str(variavel_input).replace(',', '.'))
    #A vírgula será substituida por ponto
    tipo = input ("1020, 1045, 4340, ou 8620? ")

    valores_possiveis = [1020,1045,4340,8620] #novo
    if int(tipo) in valores_possiveis: #verifica
        if (tipo == "1020" or tipo == "1045"): ###1020###
            material = input('Chapa (C) ou barra (B)? ')

            ##ALTERAÇÃO
            lista_materiais = ['C', 'B'] #Quais os materiais possiveis
            meterial = material.upper()  #Se acaso a letra fornecida estiver em minuscula

            if meterial in lista_materiais: #Verifica se o material fornecido esta na lista
                if (material == "C" or material == "c"): ###CALCULO CHAPA###
                    altura = float(input('ALTURA: '))
                    largura = float (input ('LARGURA: '))
                    comprimento = float (input ('COMPRIMENTO: '))
                    peso= round ((altura * largura * comprimento * 7.85 / 1000000),3)
                    resultado=print ('\n' f'>>>>>>>> PESO CHAPA 1020/1045: {peso} KG <<<<<<<<\n')
                    preço = round ((peso * 7),3)
                    print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n')
                    print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS CHAPA 1020###
                    altura1 = float (input ("ALTURA FINAL: "))
                    largura1 = float (input ("LARGURA FINAL: "))
                    comprimento1 = float (input ("COMPRIMENTO FINAL: "))
                    peso1= largura1 * altura1 * comprimento1 * 7.85 / 1000000
                    resultado1=print ('\n' f'>>>>>>>> PESO FINAL DA PEÇA: {peso1} KG <<<<<<<<\n')
                elif (material == "B" or material == "b"): ###CALCULO BARRA###
                    diametro = float(input('DIAMETRO: '))
                    comprimento = float (input ('COMPRIMENTO: '))
                    peso= (diametro * diametro * 3.1416 * 7.85 / 4000) * (comprimento/1000)
                    resultado=print ('\n' f'>>>>>>>> PESO BARRA 1020/1045: {peso} KG <<<<<<<< \n') ###PESO###
                    preço = peso * 7
                    print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n') ###PREÇO###
                    print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS BARRA 1020###
                    diametro1 = float (input ("DIAMETRO FINAL: "))
                    comprimento1 = float (input ("COMPRIMENTO FINAL: "))
                    peso1 = (diametro1 * diametro1 * 3.1416 * 7.85 / 4000) * (comprimento1/1000)
                    resultado1=print (f'\n>>>>>>>> PESO FINAL DA PEÇA {peso1} KG <<<<<<<<\n')
                tempera = input ("POSSUI TEMPERA? (S/N) ") ###TEMPERA###

                ##ALTERAÇÃO
                tempera = tempera.upper() #colocando em maiuscula
                if tempera in ['S', 'N']:

                    if (tempera == "S" or tempera == "s"):
                        custotratamento= 6.10 * peso1
                        print ('\n' f'>>>>>>>> TEMPERA: R$ {custotratamento} <<<<<<<<\n')
                    elif (tempera == "N" or tempera == "n"):
                        custotratamento = 0

                    oxidacao = (input("POSSUI OXIDAÇÃO? (S/N) ")).upper() #Coloquei em maiuscula  ###OXIDAÇÃO###

                    ##ALTERAÇÃO
                    if oxidacao in ['S', 'N']:

                        if (oxidacao == "S" or oxidacao == "s"):
                            custooxidacao= 2 * peso1
                            print ('\n' f'>>>>>>>> OXIDAÇÃO: R$ {custooxidacao} <<<<<<<<\n')
                        elif (oxidacao == "n" or oxidacao == "N"):
                            custooxidacao = 0
                            print ('\n')
    else:
        print('Digite um valor válido!\n')

Ou simplesmente colocar um try e except:
while True:
    print("Utilize apenas valores com ponto, e não virgula!" '\n')
    tipo = input ("1020, 1045, 4340, ou 8620? ")
    try:
        if (tipo == "1020" or tipo == "1045"): ###1020###
            material = input('Chapa (C) ou barra (B)? ')
            if (material == "C" or material == "c"): ###CALCULO CHAPA###
                altura = float(input('ALTURA: '))
                largura = float (input ('LARGURA: '))
                comprimento = float (input ('COMPRIMENTO: '))
                peso= round ((altura * largura * comprimento * 7.85 / 1000000),3)
                resultado=print ('\n' f'>>>>>>>> PESO CHAPA 1020/1045: {peso} KG <<<<<<<<\n')
                preço = round ((peso * 7),3)
                print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n')
                print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS CHAPA 1020###
                altura1 = float (input ("ALTURA FINAL: "))
                largura1 = float (input ("LARGURA FINAL: "))
                comprimento1 = float (input ("COMPRIMENTO FINAL: "))
                peso1= largura1 * altura1 * comprimento1 * 7.85 / 1000000
                resultado1=print ('\n' f'>>>>>>>> PESO FINAL DA PEÇA: {peso1} KG <<<<<<<<\n')
            elif (material == "B" or material == "b"): ###CALCULO BARRA###
                diametro = float(input('DIAMETRO: '))
                comprimento = float (input ('COMPRIMENTO: '))
                peso= (diametro * diametro * 3.1416 * 7.85 / 4000) * (comprimento/1000)
                resultado=print ('\n' f'>>>>>>>> PESO BARRA 1020/1045: {peso} KG <<<<<<<< \n') ###PESO###
                preço = peso * 7
                print (f'>>>>>>>> PREÇO: R$ {preço} <<<<<<<<\n') ###PREÇO###
                print ('DEFINA AS DIMENSÕES FINAIS DA PEÇA') ###DIMENSOES FINAIS BARRA 1020###
                diametro1 = float (input ("DIAMETRO FINAL: "))
                comprimento1 = float (input ("COMPRIMENTO FINAL: "))
                peso1 = (diametro1 * diametro1 * 3.1416 * 7.85 / 4000) * (comprimento1/1000)
                resultado1=print (f'\n>>>>>>>> PESO FINAL DA PEÇA {peso1} KG <<<<<<<<\n')
            tempera = input ("POSSUI TEMPERA? (S/N) ") ###TEMPERA###
            if (tempera == "S" or tempera == "s"):
                custotratamento= 6.10 * peso1
                print ('\n' f'>>>>>>>> TEMPERA: R$ {custotratamento} <<<<<<<<\n')
            elif (tempera == "N" or tempera == "n"):
                custotratamento = 0
            oxidacao = input ("POSSUI OXIDAÇÃO? (S/N) ") ###OXIDAÇÃO###
            if (oxidacao == "S" or oxidacao == "s"):
                custooxidacao= 2 * peso1
                print ('\n' f'>>>>>>>> OXIDAÇÃO: R$ {custooxidacao} <<<<<<<<\n')
            elif (oxidacao == "n" or oxidacao == "N"):
                custooxidacao = 0
                print ('\n')
    except:
        print('Os dados informados não são válidos')

Espero ter ajudado! Abraço!
Comment: (Tive 3 ótimas respostas entao provalvemente vou repetir esse comentário para as 3, mas...) Que aula!! Hahaha bastante informação nova para eu assimilar, estou estudando faz poucos dias. Vou levar um tempo para entender todos os códigos novos que foram inseridos por vocês, mas desde já muitissimo obrigado! Esse da vírgula vai me ajudar bastante, toda hora me confundo heheh Obrigado por dedicar seu tempo pra me ajudar. <3 Abração!

Reiniciar aplicação - Python


Animating a jquery set one object at a time

Question: First, I'm relatively new to both js and jQuery, so I apologize in advance if this is a really stupid question.  That said, here it is:
I'm trying to create a cannon-like animation for a background that does a slow 'sweep-like' transition from one image to another.
The biggest issue I've been running into is ensuring that;
a.  The increment counter is progressed and;
b.  Each 'slice' of the image completes its fadeOut before the next begins.
If there's an easy (or obvious) way of doing this, I'd love to hear it.  I've been pulling my hair out for a while now trying to figure out why these (and other similar variations) aren't working.
HTML:
img class="bg"  (10 instances of this)
(function () {
  // --- Variation 1 ---

  function effect() {
    var i = 0,
    var current = $(".bg_1:eq(" + i + ")"),
      arrLength = $(".bg_1").length;
    while (i < arrLength) {
      current.fadeOut(1000, 0);
      i++;
    }

  }
  effect();

  // --- Variation 2 ---
  function effect() {
    var i = 0,
    var current = $(".bg_1:eq(" + i + ")"),
      arrLength = $(".bg_1").length;
    while (i < arrLength) {
      current.fadeOut(1000, 0, function () {
        i++;
      });
    }

  }
  effect();

})();

I think it may be a problem with the scope of the 'i' variable, or a conflict in jQuery at that depth of scope.  Any possible solutions would be GREATLY appreciated!
Thanks.
Answer: Without seeing your html, it's a bit hard to answer, but here's a general way to animate multiple elements in sequence:
(function _loop(idx) {
    var $elements = $('#wrapper .bg'), idx = idx % $elements.length;
    $elements.eq(idx).fadeIn('slow').delay(2500).fadeOut('slow', function () {
      _loop(idx + 1);
    });
}(0));

demo: http://jsfiddle.net/UU5AM/
Answer: Your solutions are animating all the pictures at once. You have to install a recursive chain of events to do this:
// initial count value declared outside the function to not reinitialize
var count = 0;
function effect() {
  // search the current image
  var current = $(".bg_1:eq(" + count + ")");
  // if there's an image, fade it out
  if (current.length) {
    current.fadeOut(1000, function() {
     // increment the count;
     count++;
     // call the function recursively
     effect();
    });
  }
}
// call the function
effect();

See it working with the JSFiddle here
Comment: Thank you!  This looks remarkably similar to something I tried earlier.  I must've had the order mixed up.  You're a champ.
Comment: You're welcome! I just updated the post with a js fiddle, so you can see it in action.
Answer: Your var current will always be the same
try this:
function effect() {
    var i = 0;
    var arrLength = $(".bg_1").length;
    while (i<arrLength) {
        $(".bg_1:eq(" + i + ")").fadeOut(1000, 0);
        i++;
    }

}
effect();

Only now it will run as fast as the while loop goes. That means it will fade everything out almost immediately. You might want to run a setTimeout function for as long as the fadeOut goes:
var i = 0;
setTimeout(function(){
    $(".bg_1:eq(" + i + ")").fadeOut(1000, 0);
    i++;
}, 1000);

And ofcourse you will need to reset it when it reaches the end.
Edit:
Beat Richartz way, running the function again when the fadeOut is completed, is even better then the setTimeout.
Answer: You can use fadeOut's callback argument to provide it with a function which it will execute when the animation is completed. You can use this to raise the counter and (if necessary) animate the next element.
For example:
(function () {

  function effect() {
    var i = 0,
    var current = $(".bg_1:eq(" + i + ")"),
      arrLength = $(".bg_1").length;
    var animateNext = function() {
      current.fadeOut(1000, 0, function() {
        i++;
        if (i < arrLength) {
          animateNext();
        }
      });
    }
    animateNext();
  }

  effect();

})();

As you can see, we've stored a reusable function in animateNext. We call it at the end of effect the first time to start the string of animation. After that, each next animation is started from the callback in fadeOut.


gulp v4 function async task does not finish executing

Question: I am working with v4 gulp and converting my tasks to functions. I have a simple clean function that executes a parallel task.
const clean_server = () => del('build/server/*');
const clean_client = () => del('build/client/*');

export function clean(done) {
  gulp.parallel(clean_server, clean_client);
  done();
}

When I call done() the way I'm calling above, which is also suggested from the docs https://gulpjs.com/docs/en/getting-started/creating-tasks, I see the task get initiated, however, it doesn't actually complete the task.
However, when I change it to:
export function clean(done) {
  gulp.parallel(clean_server, clean_client)(done);
}

This way works.
So my question is,  why doesn't the first way as suggested by the docs complete the async task?
Answer: Because done must be passed as a callback to parallel. Either like the way you did on or like the following
gulp.parallel(done => {
  clean_server()
  clean_client();
  done();
})


Distribution of multivariate gaussian under linear constraints

Question: Let $Z_1 \ldots Z_n$ be i.i.d Gaussians and introduce a set of linear constraints 1 through k, where the $j$'s constraint is the a linear combination of the $Z$'s take a specific value, i.e.
$ \sum_{i=1}^n w_{i,j}Z_i = c_j $
Where $w_{i,j}$ is a set of weights, and $c_j$ is the value for that constraint. Intuitively, this distribution should be also a gaussian, with now different first and second moments. I was able to find a derivation for what it would look like for a single constraint (see https://www.mdpi.com/2227-9091/6/3/64), but I'm unsure how to derive its form for more than one constraint.
Answer: Partial answer, I may delete later:
Let $W \in \mathbb{R}^{n \times k}$ have entries $w_{i,j}$. Let $c = \begin{bmatrix} c_1 \\ \vdots \\ c_k\end{bmatrix}$ and $Z = \begin{bmatrix} Z_1 \\ \vdots \\ Z_n \end{bmatrix}$. The constraint is $W^\top Z = c$. I will assume the columns of $W$ are linearly independent.
Let $\tilde{W} \in \mathbb{R}^{n \times (n-k)}$ be such that $A:=\begin{bmatrix} W & \tilde{W}\end{bmatrix} \in \mathbb{R}^{n \times n}$. Then $$U := A^\top Z = \begin{bmatrix} W^\top Z \\ \tilde{W}^\top Z \end{bmatrix} \sim \mathcal{N}(0, \Sigma)$$
where $$\Sigma := A^\top A = \begin{bmatrix}W^\top W & W^\top \tilde{W} \\ \tilde{W}^\top W & \tilde{W}^\top \tilde{W}\end{bmatrix}.$$
The conditional distribution of $\tilde{W}^\top Z$ given $W^\top Z = c$, which is a Gaussian distribution whose parameters can be written down in terms of $\tilde{W}^\top Z$, $c$, and the blocks of $\Sigma$.


Compare dates using VBA

Question: I am trying to parse sheet with time stamps and count number of occurrences.
my data have header (date, hour, instance, day), so I want to parse through days and when there is new day I record time (this is time of first event that day) and increment counter  next to that "time" value (I add list of timestamps at column 11)
My code is:
Sub Count()

Dim i As Integer
Dim j As Integer

Dim Day As String
Dim Vrijeme As Date
Dim test As Date

For i = 1 To 5673

If Cells(i, 4).Value <> Day Then
        Day = Cells(i, 4).Value
        Vrijeme = Cells(i + 1, 2).Value

        For j = 5 To 500
        test = Cells(j, 11).Value

           If Vrijeme = test Then     // This is place that doesn t work
                counter = Cells(j, 12).Value
                counter = counter + 1
                Cells(j, 12).Value = counter

            End If
            DoEvents

         Next j

    End If

Next i

End Sub

But this doesn t work, I event manualy set cell format to "Time" ... any idea why this doesn t work. when I do debug variable read data correctly but when it compare values this don t work ...
thx
Answer: try to use TimebValue and DateValue.
as
Day = DateValue(Cells(i, 4))
Vrijeme = TimeValue(Cells(i + 1, 2))
test = TimebValue (Cells(j, 11))

You need to compare comparable values, to be 100% sure that they are comparable convert them bout in one format.
Comment: Runtime error 13, Type mismatch , I converted time to minutes from midnight and worked fine.... I am quite sure that problem is related to cell format

Compare dates using VBA


please check my proof and comment it

Question: Let $\left(\frac1{(2k+1)!}\right)$ be an infinite sequence. I want to show the following limit
$\lim \limits_{k \to \infty}{\frac{1}{(2k+1)!}}=0.$
Below is my proof. Please check it, I'm not confident about my ability.
For all nonnegative integer of k, we have
$0<(2k+1)\le(2k+1)!$
$\frac{1}{2k+1}\ge\frac{1}{(2k+1)!}>0.$
As $k\to\infty, \frac{1}{2k+1}\to0.$ Thus, as $k\to\infty$, $\frac1{(2k+1)!}\to0$
Comment: Looks like a great application of the squeeze theorem to me!
Comment: Alternatively, you can try $\frac{e^x-e^{-x}}2=??$
Comment: Your proof is correct=)
Comment: Proof is correct. You may also try with $\frac{1}{(2k+1)!} \le \frac{1}{2^{2k}}$
Comment: Your proof is perfectly good if we can take it as known that $\lim_{k\to\infty}\frac{1}{2k+1}=0$, and if we can take the Squeezing Theorem as known. If we need a formal $\epsilon$-$N$ argument, both of the above facts must be proved. So whether a proof is adequate is context-dependent.
Comment: thanks all of you who sent in comments and help.
Answer: As mentioned in the comments, your proof is great. <code>:)</code>

please check my proof and comment it


Prove $\lim_{h\to0}\frac {f(x+h)-f(x)}{h}=f'(x)$ uniformly if $f\in C_c^{1}(\mathbb R)$.

Question: I try to use the fact $f\in C_c^1(\mathbb R)$ which means it is a function with compact support whose derivative is continuous. This implies $f'$ is uniform continuous. But then it turns out uniform continuity of the limit function does not imply the uniform convergence of the sequence. Now I am thinking if I can show $f_n$ is equicontinuous, which will then solve the problem. But I cannot manage to show it. I am stuck here. Any hints and comments are appreciated! Thanks.
Comment: What do you mean with $C_c^1(\mathbb R)$?
Comment: It means it is $C^1$ function with compact support. Just edited.
Answer: Let $\epsilon>0.$ Since $f'$ is uniformly continuous on $\mathbb R,$ there exists $\delta>0$ such that $|y-x|<\delta$ implies $|f'(y)-f'(x)|<\epsilon.$ So if $x\in \mathbb R$ and $0<|h|<\delta,$ the MVT shows there exists $c$ between $x$ and $x+h$ such that
$$|\frac{f(x+h)-f(x)}{h} - f'(x)| = |f'(c)-f'(x)|<\epsilon.$$
Comment: Oh yes MVT really works here. Thanks!
Answer: HINT:
Write $f(x+h) - f(x) = \int_x^{x+h} f'(s) d s = h \int_{0}^1 f'(x + t h) d t$ so
$$\frac{f(x+h)-f(x)}{h} - f'(x) = \int_{0}^1 (f'(x+t h) - f'(x) )\ d t$$
Comment: Then by uniform continuity of $f'$, the right hand side is uniformly small. Thanks!
Comment: @JKDASF: It may be convenient at times to see it as a continuous function of $(x,h)$ that is $0$ for $h=0$. When $f$ is $C^k$ then the function is $C^{k-1}$.


Delete all users and there content apart from user 1

Question: I have been asked to help look after a Drupal site that was created by a third party. This site has lots of users (~13,000) and for each user lots of items of content was created.
I want to clean the database from users and content to improve performance. When a user try to log into the site via an ID a user account is created, a web service is called and the correct content is recreated. My next job is to create some cron tasks to keep the data controllable going forward.
I want a way to delete all the users apart from user id 1. I looked at VBO but every now and again it will stop running and I have to start again (it has never completed).
I have created a drush command which calls the following:
function delete_users_batch_delete() {
  drush_print('Deleting Users');
  $uids = delete_users_get_uids();
  $count = count($uids);

  $temp = 0;
  foreach ($uids as $uid) {
    $temp++;
    user_delete($uid);
    if ($temp % 25 == 0) {
      drush_print('deleted ' . $temp . ' from ' . $count);
    }
  }
  drush_print('All users deleted');
}

function delete_users_get_uids() {
  $result = db_query('SELECT u.uid FROM {users} u WHERE u.uid > 1');
  $uids = $result->fetchCol();
  return $uids;
}

However this is running very slow on my local machine. What would be the best way to delete everything quickly.
If I had started the project myself I would just run my install script which would set up a new instance of the site with it configured correctly. Sadly I don't have this and just one big database dump.
Comment: @Mołot all the content is stored in another backend system. Logging in with a guid calls a web service that gets the data for that user. A drupal user is created and the content from the WebService is used to generate content in Drupal. There was a bug when the project launched which meant that each time someone logged in new content was created rather than using the referenced content. It is a big mess. If was starting from scratch I would do it very different!
Comment: If site is so user and data-centric, is it wise to simply delete all that?! I mean, if my 13000 users are complaining site is slow, I would be terrified to think what they would say if I would suddenly kick them out of it and delete their content. Site would be fast, but with 13000 people less to earn on. And if one user generates mere $1 / month, it's pretty amazing difference in one's wallet. Are you damn sure site owner wants this? Do you have it written and signed?
Comment: Well, that explains a lot. Now, feel free to comment on my answer if it causes you any problems.
Answer: You can use Views Bulk Operations (VBO) module...
Above module allows to execute bulk operations on nodes, users, comments; it also permits to apply the selected operation to all the nodes, users, or comments using the Batch API. The batch API allows forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.
There is a setting in the View's VBO options to enable a select all button that select all items across all users and unselect admin.
Comment: @Johnny but if your problem is "this is running very slow on my local machine" then using some kind of batch is needed. And [Drush can process Batch API functions, apparently](https://drupal.org/node/873132), just as well.
Comment: http://drupal.stackexchange.com/questions/2499/drush-scripting-or-batch-api put me off from using the Batch API as it browser dependent.
Answer: You can do this with Devel's Devel Generate submodule. Go to Generate users, set the number of users to generate to 0 and tick the Delete all users (except user id 1) before generating new users option, then click on the Generate button.
Answer: There is user_delete_multiple(array $uids) function just for mass deletion. So do not loop on your own, let the Drupal do it.

Delete multiple user accounts.
Parameters

$uids: An array of user IDs.

Note that it might not be much faster as it still needs to loop for hooks invocation.
Also, array with 13000 entries may be a bit big for ->condition('uid', $uids, 'IN') call, I would suggest to use some kind of batch processing and split whole list to chunks somewhere between 100 and 1000 users per chunk, depending on your configuration (calculations are hard, easier to test).
Answer: With the devel_generate module which is a submodule of the great Devel module you could also use Drush to do that.
Please backup your DB in advance ;)
Delete ALL content.
drush genc --kill 0 0

Delete all articles.
drush genc --kill --types=article 0 0

Delete all users except uid 1.
drush genu --kill 0

For genu with --kill that's a hard coded condition in the query: ->condition('uid', 1, '>') to not delete uid 1.
Comment: @jgrocha – `drush en devel` and then `drush en devel_generate` and then whatever else you would like to run from this answer.
Comment: How do I install `devel_generate`? My `drush` does not undestant `genu 0`.


Ajax request com setInterval que pisca

Question: O seguinte pedaço de código tem como objetivo colocar o conteudo de um ficheiro de texto dentro de uma div.Como o ficheiro de texto pode ser atualizado, pretende-se que a div esteja atualizada com o conteudo mais recente do ficheiro. Mas a cada 2 segundos o conteudo da div pisca. Como posso atingir o mesmo obtjetivo sem que o conteudo da div pisque? Obrigado.

Comment: Olá João, o que estás a fazer está no caminho certo. Eu mudaria para `setTimeout(loadXMLDoc, 2000);` a ser disparado dentro do `.onreadystatechange` para garantir que só tens uma chamada de cada vez. Em relação a "piscar" dá-me ideia que tens muito conteúdo e que o browser precisa de tempo para fazer a renderização... podes  mudar menos conteúdo de cada vez? E já agora podes clarificar na tua pergunta o que tem esse conteúdo? Imagens? só texto?
Comment: É preciso também verificar se o `responseText` já está disponível, pois o `onreadystatechange` é chamado várias vezes antes disso. Talvez seja a causa do problema.
Comment: O conteudo é apenas texto. É um ficheiro .txt com apenas duas palavras. Obrigado
Answer: @João, realizei alguns testes aqui, o problema ocorria quando o innerHTML era substituído por um texto Longo.
Para contornar esta situação, fiz o seguinte.

Criei uma div chamada container
Adicionei o Texto a div container
Limpei a div minhaDiv
Adicionei a div containerà div minhaDiv

Para a demostração abaixo, usei a API BaconIpsum para gerar um texto aleatório.

setInterval(loadXMLDoc,2000);

var minhaDiv = document.getElementById("minhaDiv");
function loadXMLDoc(){
    var xmlhttp;
    // codigo para IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.responseText && xmlhttp.responseText.length > 0)
        {
            var content = document.createElement("div");
            var paragrafos = JSON.parse(xmlhttp.responseText);
            for (var i = 0; i < paragrafos.length; i++) {
                var paragrafo = document.createElement("p");
                paragrafo.innerHTML = paragrafos[i];
                content.appendChild(paragrafo);
            }

            if (minhaDiv.firstChild){
                minhaDiv.removeChild(minhaDiv.firstChild);
            }
            minhaDiv.appendChild(content);
        }
    }
    xmlhttp.open("GET","http://baconipsum.com/api/?type=all-meat&paras=10&start-with-lorem=1",true);
    xmlhttp.send();
}

Comment: @TobyMosque Acho que meu comentário lá em cima pode ter te induzido a essa verificação de se a resposta está vazia, mas o melhor seria checar se a requisição está finalizada e foi bem-sucedida: `if(xmlhttp.readyState == 4 && xmlhttp.status == 200)`
Comment: Obrigado pela resposta. Vou estudar o este codigo que me pareceu bastante bom. Pois existem exertos do codigo que dizem respeito à manipulação da DOM.

Ajax request com setInterval que pisca


Ruby on Rails: Send email from show page

Question: I am a Rails noob and have a problem sending an email from a show page. There are several contact form tutorials out there but I cannot find one where I send an email from a page like a 'show' page. I have big errors in my routes I believe. In the model I state that Users have several Promotions and on the promotions show page I want to allow the current_user to send an email to @user.
here is app/mailers/quote_mailer.rb
class QuoteMailer < ActionMailer::Base
  default :from => "email@example.com"

  def quote_mail(promotion)
    @user = user
    mail(:to => user.email, :subject => "You have an inquiry homeboy!")
  end
end

In promotions_controller I put this action which I think might be wrong:
def quotedeliver
  QuoteMailer.quote_mail.deliver
  flash[:notice] = 'report sent!'
  redirect_to root_path # or wherever
end

Here is the form that I use to send the email (the :url is probably wrong but I dont know how it should look)
<%= form_for quote_mail, :url => quotedeliver_promotion_path(promotion), :html => {:method => :put } do |f| %>
  <%= f.text_area :body %>
  <%= f.submit %>
<% end %>

I would love some help with this. I cannot find anything like it on stackoverflow, I have been trying for days. Thank you!
Comment: Whats the error you are getting..
Comment: what is your smtp settings in development.rb ?
Answer: You are probably missing the route in config/routes.rb
you can define it like
post '/quotedeliver_promotion' => 'promotions#quotedeliver', :as => quotedeliver_promotion

Note that quotedeliver has to be rewritten quote_deliver to follow ruby syntax conventions. When you call
QuoteMailer.quote_mail.deliver

You are not giving the parameter, so try this
QuoteMailer.quote_mail(current_user).deliver

And change your method with
def quote_mail(user)
  mail ....
end

and you are all good
Comment: Thanks for the answer Albandiguer! I am getting NoMethodError in Promotions#show undefined method `quote_deliver_promotions_path' this is the form. I would love your help!                       <%= form_for @quote_mail, :url => quote_deliver_promotions_path(@user), :html => { :method => :put } do |f| %>
             <%= f.text_area :body %>
      <%= f.submit %>
    <% end %>
Comment: Hi, you can submit this form using POST. so remove :html => {:method => :put}, If you defined the route as i told, the path is quotedeliver_promotion_path, no parameter. The user is given to the model in the controller
Answer: There are some excellent screen casts (through Railscasts) regarding sending e-mail http://railscasts.com/?tag_id=28.
One last thing, do not attach your mail sending method to a show action (if you are doing currently), the reason is show action is only for view something and users might be refreshing that page, So if you attach a mailer to that, mails might go out for each refresh.
Comment: thanks for this tip... based on this info i think this means that I am going to use a jquery modal to show the mail form which will exist on another page.
Answer: def quote_mail(promotion)
   @user = user
  mail(:to => user.email, :subject => "You have an inquiry homeboy!")
end

from where you are access user variable, it should be promotion i think.


How does gitlab eases the work of authorizing ssh key?

Question: While using git, in order to authorize developers, we ask them provide their public ssh key and then mark them as authorized.
With gitlab, developer can save their ssh public key through the Account Interface. How is the authorizing part handled!?
Please reply at earliest.
Answer: It is managed through gitlab-shell, which replaces gitolite since GitLab 5.0.
The bin/install script is invoked from ~/.ssh/authorized_keys.
It comes with a set of commands, including ones for ssh key management:
Keys:

Add key

./bin/gitlab-keys add-key key-782 "ssh-rsa AAAAx321..."

Remove key

./bin/gitlab-keys rm-key key-23 "ssh-rsa AAAAx321..."

Remove all keys from authorized_keys file

./bin/gitlab-keys clear

Comment: hi VonC! You mentioned "The `bin/install` script is invoked from `~/.ssh/authorized_keys`. There is similar comment in `bin/gitlab-shell`. I am not able to understand how this 'invoking' thing is going on. When push or pull is being made, how does gitlab-shell know about it?


Even roots and exponents power rule

Question: I've a question about exponents power rule applied to even roots.
Assuming as facts

$x \in \mathbb{R}$
$\sqrt[2n]{x^{2n}} = |x|$
$\sqrt[a]{x^b} = x^{b/a}$
the exponents power rule $({x^a})^b = x^{a b}$ is true
$x^{a b} = x^{b a}$

Problem 1
We have that $\sqrt[2n]{x^{2n}} = {x^{2n}}^{\frac{1}{2n}} = x^1 = x$ applying 3.
How is it possible that $\sqrt[2n]{x^{2n}} = x$ if 2 is true? That means that $|x| = x$ which is clearly not true.
Problem 2
$x^{a/b} = x^{a\frac{1}{b}} = x^{\frac{1}{b}a}$ applying 4 and 5.
But this is not true for all a and b. For instance, if $a=2, b=4$:

$x^{2/4} = x^{2\frac{1}{4}} = \sqrt[4]{x^2}$
$x^{2/4} = x^{2\frac{1}{4}} = x^{\frac{1}{4}2} = ({\sqrt[4]x})^2$

That results in saying that $ \sqrt[4]{x^2} = ({\sqrt[4]x})^2$ which is false.
Comment: The second problem results in a correct conclusion.
Comment: @Tavish how could be correct?
The first one have a domain in all R, the second one in x>=0
Comment: Any real number has two square roots $x^2=(-x)^2$. So when we use the root symbol, is is convention to take the positive real root, hence (2). Taking roots involves choices, so the exponents power rules are only true for all $a,b,x$ if $x$ is non-negative. Whenever we take a non-integer power, there are normally multiple "answers" and we always take the non-negative one if we can
Comment: This also explains Tavish's comment. The fourth root function is defined only from the non-negative reals to the non-negative reals. Both sides are, by definition, non-negative
Answer: When you divide the exponent in $x^{2n/2n}$ you have to remember that, by definition, the square root of any number is always positive, which means that you have to get the module of the expression before doing the actual division
As for the second one, when you go from $\sqrt[4]{x^2}$ to $(\sqrt[4]{x})^2$ you are restricting the domain (from R to R+), which means the two are not equivalent. In order to actually make them equivalent, you have to take the absolute value of x before moving the exponents around
Comment: I don't have enougth reputation to give you a vote, but thank you very much

Even roots and exponents power rule


Number of ways to dissect a square into triangles of equal area

Question: Monsky's theorem states that it is impossible to dissect a square into an odd number of triangles of equal area.  If $n$ is an even integer, I am interested in the number of ways of dissecting a square into $n$ such triangles.  Call $s_n$ this number.  My question is:

What are the first terms of the sequence $s_n$?

with an option on this other question:

How can we compute $s_n$ for a given $n$?

Judging from the lack of answers to this question, it does not seem trivial that these numbers are even finite, let alone known.  Obviously, $s_2=2$, and I believe that $s_4=25$.  Other values are unknown to me.
Added 15/05/2015: I believe that $s_6$ is at least (and perhaps exactly) equal to $818$. This, however, does not lead to any sequence of the OEIS, so I'd be happy to be proved wrong.
Added 03/06/2015: For $n=2,4$ (but not for $n=6$, see mjqxxxx's answer below) the equidissections of the square that I could find all involve triangles whose vertices are rational numbers.  For larger $n$, it is not sufficient to look only at equidissections satisfying this property.
Comment: @AlexR There are two ways of dissecting the square into two isoceles triangles, and each of these can be dissected in 3 ways.  This gives $2\times 3\times 3$ dissections, one of these (the $\times$ one) appearing twice.  So $17$ dissections.  Now, you can split the square into two rectangles in $2$ ways, and each rectangle can be split into two triangles in $2$ ways.  This adds $8$ new dissections, for a total of $25$ (I had overlooked the doubly counted dissection, editing my post right now!).
Comment: Forgive me if this question is stupid, but if two dissections can be made identical by using the symmetry of the square, would you still consider them distinct? (I think that by your note that $s_{2}=2$ the answer to this is "yes" but you may have thought of one I've overlooked.) Also, is the order in which the dissecting edges are added important to you?
Comment: Can you enlighten us on how you got $s_4$? I must be overlooking massive amounts of dissections since I can only come up with $9$ ($\times$, $\backslash/$ and its four rotations, $//$ and its four rotations / reflections)
Comment: @Shai Indeed, I am looking for the number of dissections in an "absolute sense", not up to symmetries of the square (although this number would be interesting as well).  I am not sure I understand what you mean by the "order" in which the edges are added, but I would guess that the answer is no: I am only interested in the dissections themselves, not their construction (unless this leads to an answer to my second question).
Comment: @Pierre-GuyPlamondon Ah so I forgot about the $16$ with a "ray" pattern. Thanks :)
Answer: Even for $n=6$ it doesn't seem necessary for the coordinates to be rational.  For instance, consider the following dissection into six right triangles of equal area:

The four interior points do not, I think, have rational coordinates.  Calling the lower left corner $(0,0)$ and the lower right corner $(1,0)$, I found the interior point at lower right to be at $\left(\frac{1}{2} + \frac{1}{6}\sqrt{5}, \frac{1}{3}\right)$.
Comment: Nice example! It seems this pattern can be used to produce equidissections into $n$ triangles for any even $n\geq 6$, and that most of them will have irrational coordinates.
Comment: I'll award you the bounty for this example that I'm very glad to see, but I won't accept your answer since the question is still not settled.


extending Function

Question: I've been seeing the syntax:
var module = {

    func: function(value) {

        some code;

    }.func2("value");

}

cropping up in various places, as am wondering how this is done. I remember seeing an article about it a while back, but can't find it now. Whatever I try .func2("value") just trows syntax errors.
For example, take a look at SproutCore's intro to their TemplateView.
Todos.StatsView = SC.TemplateView.extend({
  remainingBinding: 'Todos.todoListController.remaining',

  displayRemaining: function() {
    var remaining = this.get('remaining');
    return remaining + (remaining === 1 ? " item" : " items");
  }.property('remaining').cacheable()
});

Seems like it would be a useful tool to give users when writing factories.
Thanks.
Comment: This looks highly consistent to the way http://jquery.com/ works. You probably saw applications using the library.
Comment: I've also seen it in SproutCore. Seems like it would be a useful for factories.
Comment: awesome! I've really learnt something today.
Answer: You can add properties to Function's prototype and then chain function definitions. For example:
Function.prototype.trigger = function(trigger) {

    var setValue = this;

    return function(thevalue) {
        alert(trigger + ' set to ' + thevalue);
        setValue(thevalue);
    };

};

var _value = 0;

var setValue = function(thevalue) {

    _value = thevalue;

}.trigger('value');

setValue(25);

When setValue is defined the trigger function is called within the scope of the anonymous function it's chained to, and setValue is assigned the value returned by trigger. In this case we're just alerting that setValue is being called, but this opens some very cool possibilities.
Pretty slick.
Answer: The syntax I think you are looking for it is:
func: (function(value) {
    //some code;
}("value"));

In which the anonymous function is called immediately and its return value assigned to func.
See also: How do JavaScript closures work?
Comment: No, closures I understand. Check out the edit. SproutCore uses it to allow users to flag functions for caching, data bind, etc...
Answer: that's kind'a weird.Maby is was something like :
var module = {
    func : (function(){
        return {func2 : function(v){alert(v);}};
    }).func2('alert me');
}

you cannot chain function definitions (function func (){}.func1()),only function calls (if configured properly) that would look like : func1().func2().func3().....
Comment: Ah, but you can it would seem. I just don't get how. Example at: http://guides.sproutcore.com/html_based.html#defining-your-model. I would assume they were looping the code through some kind of preprocessor, but I've seen this in a few places now.
Comment: In pure javascript,that would trigger an error. If you want to use an interpretor for you own language and then translate it into javascript, almost anything is possible.Just take a look at how processing works. It uses the processing(mainly C) language with all the classical declaration types : `int a;`,`char b;`,`void main(){}`,which in pure js would trigger errors, but it is first interpreted and then translated into javascript, so everything works fine. Although it is possible, it's abit of a headake to go through all that just for a slick synthax.
Comment: I'd agree. I've just seen this syntax in so many places now that I assume there's some trick to it. Extending Function's prototype, or Function's constructor's prototype...
Comment: This answer is misleading. Of course you can call a function on a function expression. The only caveat is that the operator precedence rules forces parenthesis around the function. The `new` keyword is not needed at all (and would change the program altogether!). Working example: `(function() { return 1 + 2; }).toString()`
Comment: @Jakob You're right, got a bit carried away with the oop part. the thing is that you cannot call a function on a function expression, but you can call it on a function result (if that result is an object that holds that function)
Comment: @gion: see answer above. You can call a function on a function expression if you extend Function's prototype. So `var fn = function() { ... }.foo();` is valid as long as you have `Function.prototype.foo = function() { ... };` in there somewhere. Very different thing than calling a function on the result of a function, as you're example does.

extending Function


Optimal way to get a content type's field definition

Question: When I need a content type's field definition in Drupal 8+, I used to run the following code (for getting 'body' field in content type 'page'):
$page_fields = \Drupal::getContainer()->get('entity_field.manager')
               ->getFieldDefinitions('node', 'page');
$body_definition = $page_fields['body'];

I learned, that it is also possible by running the following code:
$body_definition = \Drupal::entityTypeManager()
                  ->getStorage('field_config')
                  ->load('node.page.body');

Now my question is, what's an advantage of one over the other? The latter is of course only one line, but that can't be the end of the story, I guess. Is one of these ways the "Drupal way"?
Answer: Field definitions can be defined in different places. The first code examples gets all definitions, the second code example only a specific field definition and it finds only configured fields.
The service entity_field.manager is responsible for discovering fields in multiple locations, configuration and a lot of different methods in code, which might be extended in future to find even more. So using this service is the most generic way to get field definitions.
Use \Drupal only in hooks, not in classes. And then you can reference services via \Drupal::service('entity_field.manager'), you don't need to get the container.
Comment: No, the field manager doesn't read YAML files directly, only the active config in db. Normally base fields are defined in the entity class and bundle fields in config. But there are a lot of other methods to create or alter field definitions. For example bundle fields can be defined in the entity class, too. Also in hooks. But this is rarely used.
Comment: Thanks a lot, 4k4. Out of curiosity, where else could a field be defined if not in (db) configuration? Does this include configuration files, for example if there were a field defined in a (not yet imported) yml file?


Java netbeans autoresize textarea

Question: I am using netbeans 7.0.1 to build a simple JFrame application
I am putting a textarea and a couple of buttons on using the gui builder
the buttons are on the same vertical level and the right hand button shifts right on resize of the window - that is fine but I would like the text area to do the same - i.e. resize to fit the relevant width of the window.
For the life of me I cannot see how this is done - I have looked around and I can find code for a hand coded app but not for netbeans gui builder
Answer: Update: Ah sorry, didn't read the full question, you really want to do it with netbeans.. :) Well, well, now you have this post how to do it hand-crafted aswell! :)
I wouldn't use an GUI builder for this task. It is easy to create such layout with FlowLayout and BorderLayout:

Screenshot was produced by this code:
public static void main(String... args) throws Exception {
    JFrame frame = new JFrame("Test");

    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    buttonPanel.add(new JButton("Hello"));
    buttonPanel.add(new JButton("World!"));

    frame.add(buttonPanel, BorderLayout.NORTH);
    frame.add(new JTextArea("Hello World!"), BorderLayout.CENTER);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 400);
    frame.setVisible(true);
}

Answer: It's all about the layout you're using. I would personally use GridBagLayout, probably because I am accustomed to it. Basically, you should follow these steps:

Change the layout of the container which owns the textarea to GridBagLayout. You can do that by right-clicking on the container(being it the JFrame, a panel, whatever) and there you will see the Layout menu. It contains a GridBagLayout option.
In the component inspector select the JScrollPane that owns the JTextArea. Check out the "Layout" section in the properties tab. It contains the GridBagConstraints which command the layout behaviour of the JScrollPane and thus commands the JTextArea.
Play with the layout properties :). Basically you should set the X and Y weight to 1, and the Fill to "Both". This will tell the JScrollPane to fill any vertical and horizontal space there is on the Frame, and the X and Y weight will pull any other components as far as possible.

You can read more about GridBagLayout here: http://netbeans.org/kb/docs/java/gbcustomizer-basic.html
Learning GridBagLayout could take a couple of hours, getting used to it could take a couple of days, but it's worth learning. Just my 2 cents.
Comment: Thanks for that, I have now found the editor and am happily using it - just stuck on anchoring vertically....

Java netbeans autoresize textarea


Showing that $\frac{1}{k(k+1)} = \frac{1}{k} - \frac{1}{k+1}$

Question: I have a simple development of an expression that I can not understand how it was made. The expression is:
$$\begin{align}\frac{1}{k(k+1)} & = \frac{1}{k} - \frac{1}{k+1}     \end{align}$$
Can please someones show me how the left side is equal to the right side?
Thank you!
Comment: First introduction to partial fractions?
Comment: This is an example of a [partial fraction](http://en.wikipedia.org/wiki/Partial_fraction) expansion of a rational function, which is easily calculated by the [Heaviside cover-up method.](http://en.wikipedia.org/wiki/Heaviside_cover-up_method) It deserves to be better known that this method [also works for *nonlinear* denominators.](http://math.stackexchange.com/a/23498/242)
Comment: Thanks for you answers! Partial fractions are actually introduced later in my book. Still it was good to read up on them!
Answer: When adding two fractions, it is useful to use common denominator.
In your case, $k(k+1)$ is a multiple of both $k$ and $k+1$, so you can write:
$$\frac1k-\frac1{k+1}=\frac{k+1}{k(k+1)}-\frac{k}{k(k+1)}=\frac{(k+1)-k}{k(k+1)}=\frac{1}{k(k+1)}.$$

A slightly different approach: If you are given $\frac1{k(k+1)}$ and you want to simplify it, you may notice that $\frac{k+1}{k(k+1)}=\frac1k$ and $\frac{k}{k(k+1)}=\frac1{k+1}$ are simpler expressions. So you can ask whether you can somehow write the numerator using $k+1$ and $k$. And you can: $1=(k+1)-k$.
So you get
$$\frac1{k(k+1)} = \frac{(k+1)-k}{k(k+1)}=\frac{k+1}{k(k+1)}-\frac{k}{k(k+1)}=\frac1k-\frac1{k+1}.$$
Comment: Thank you! This was probably the way I was supposed to do it according to my book. Many thanks!
Answer: Recall how fractions are subtracted:
$$
   \frac{a}{b} - \frac{c}{d} = \frac{a \cdot d}{b \cdot d} - \frac{b \cdot c}{b \cdot d} = \frac{a \cdot d- b \cdot c}{b \cdot d}
$$
In the case at hand $a=c=1$, $b=k+1$ and $d=k$.
Comment: Thank you for your answer!


Uploading Image in Oracle Blob with Asp.net MVC 5 and show on html page

Question: I have very new in asp.net seeking you help that, I am trying to upload image with the data of new user I can successfully add user information in database. But now I am stuck with uploading image. My form working perfectly passing all data to the action so I am starting from there:
public ActionResult SaveUser(string oid, string fname, string uname, string pass, string pass2, string bt, HttpPostedFileBase image)
{

    string iuser = Session["UserID"].ToString();
    string fileName = Path.GetFileName(image.FileName);
    String fileExtension = Path.GetExtension(fileName);
    int fileSize = image.ContentLength;

    if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".jpeg")
    {
        Stream stream = image.InputStream;
        BinaryReader binaryReader = new BinaryReader(stream);
        byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
    }

    if (pass == pass2)
    {
        if (bt == "0")
        {
            string packge = "tflhr.pro_new_user.insert_data";
            ds = new DataSet();
            ds = _clsDataAccess.package_user(packge, fname, uname, pass, iuser );

        }

    }

    return RedirectToAction("User", new { cpid = 0, bt = 0 });
}

In the action image containing images now how I can upload the image data in database here is my connection:
public DataSet package_user(string package, string fname, string pass, string uname, byte[] bytes, string iuser)
{
    conn = new OracleConnection(clsConnection.ConnectionSave);
    conn.Open();

    cmd = new OracleCommand(package, conn);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add("cur_c1", OracleType.Cursor).Direction = ParameterDirection.Output;
    cmd.Parameters.Add("user_name", OracleType.VarChar).Value = fname;
    cmd.Parameters.Add("user_pass", OracleType.VarChar).Value = pass;
    cmd.Parameters.Add("user_enid", OracleType.VarChar).Value = uname;
    cmd.Parameters.Add("user_name", OracleType.Blob).Value = bytes;
    cmd.Parameters.Add("iuser", OracleType.VarChar).Value = iuser;
    cmd.Parameters.Add("euser", OracleType.VarChar).Value = iuser;

    oda = new OracleDataAdapter(cmd);
    ds = new DataSet();

    conn.Close();
    oda.Fill(ds);
    return ds;

}

and store procedure is:
CREATE OR REPLACE PACKAGE BODY TFLHR.pro_new_user as
procedure insert_data (cur_c1 out t_cursor, user_name in varchar2, user_pass in varchar2,
user_enid in varchar2, bytes in blob, iuser in varchar2, euser in varchar2)
is
code varchar2(5);
begin
select nvl(max(to_number(user_text)),0)+1 into code from tflhr.t_user;
insert into tflhr.t_user (oid, user_text, user_name, user_pass, user_enid,image, iuser, euser,user_path)
values
('USERx'||lpad(code,5,'0'), lpad(code,5,'0'), user_name, user_pass, user_enid, bytes, iuser, euser, lpad(code,5,'0'));
open cur_c1 for
select '1' from dual;
        commit;
    end insert_data;
end;
/

And I got Exception
Exception Image
How I change this parameter to upload image. Plz help me and short out if there any mistake. Thank You
Comment: Are you want to pass image data into stored procedure from `package_user`? I think you should add `OracleDbType.Blob` parameter for your SP to insert byte array from the image, then in viewmodel set the `` source with virtual path of the image.
Comment: Thank you for your quick replay. Plz check that i have change my  code and getting this error *An exception of type 'System.Data.OracleClient.OracleException' occurred in System.Data.OracleClient.dll but was not handled in user code*
Comment: Can you provide exception details (also with inner exception) and stack trace? I suspected you're using wrong parameter name in `cmd.Parameters.Add("user_name", OracleType.Blob).Value = bytes;`. If you can provide stored procedure codes, it's much better.
Comment: I have added store procedure and Exception. Plz let me know if further information need
Answer: The exception multiple instances of named argument in list occurs because you're adding the same parameter name twice as shown in this snippet (and the parameter name is also wrong corresponding to parameter data type):
cmd.Parameters.Add("user_name", OracleType.VarChar).Value = fname;
cmd.Parameters.Add("user_pass", OracleType.VarChar).Value = pass;
cmd.Parameters.Add("user_enid", OracleType.VarChar).Value = uname;

// user_name parameter used twice here, the exception thrown
cmd.Parameters.Add("user_name", OracleType.Blob).Value = bytes;

You should add bytes parameter name instead:
cmd.Parameters.Add("cur_c1", OracleType.Cursor).Direction = ParameterDirection.Output;
cmd.Parameters.Add("user_name", OracleType.VarChar).Value = fname;
cmd.Parameters.Add("user_pass", OracleType.VarChar).Value = pass;
cmd.Parameters.Add("user_enid", OracleType.VarChar).Value = uname;
cmd.Parameters.Add("bytes", OracleType.Blob).Value = bytes; // problem fixed
cmd.Parameters.Add("iuser", OracleType.VarChar).Value = iuser;
cmd.Parameters.Add("euser", OracleType.VarChar).Value = iuser;

Note that you can use AddWithValue to simplify the parameter definitions, but make sure they're passed with proper data types.
Additionally, you should pass method parameters in proper order:
ds = _clsDataAccess.package_user(packge, fname, pass, uname, bytes, iuser);

because the method signature looks like this:
public DataSet package_user(string package, string fname, string pass, string uname, byte[] bytes, string iuser)

Comment: ok! That problem is solved now  I am getting this error now *{"ORA-01460: unimplemented or unreasonable conversion requested\n"}* further help plz
Comment: You can see similar issue [here](http://www.dba-oracle.com/t_ora_01460_unimplemented_or_unreasonable_conversion_requested.htm). It related to ODP.NET version you're using, not the query string. Try update to newer ODP.NET version.
Comment: Is there any other way?
Comment: My ODP.NET Version is 12


How could I test ClassNotFoundException is being thrown?

Question: I have question that similar to my previous question where I have the following class:
public class FileClass {
    public void funcB() throws ClassNotFoundException {
        throw new ClassNotFoundException();
    }
}

I would like to test whether ClassNotFoundException will be thrown when funcB() is called. Thus I have this test code:
public class TestFileClass {
    @Test(expected=ClassNotFoundException.class)
    public void testFuncB() throws ClassNotFoundException {
        FileClass fc = Mockito.spy(new FileClass());
        Mockito.doThrow(new ClassNotFoundException())
        .when(fc).funcB();
    }
}

But the test were failed due to following error:
java.lang.AssertionError: Expected exception: java.lang.ClassNotFoundException
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:35)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Any clue how could I test ClassNotFoundException in funcB()?
Answer: If you're testing a method invocation on an instance of type FileClass, don't mock the instance. Just create an actual instance and call the method.
@Test(expected = ClassNotFoundException.class)
public void testFuncB() throws ClassNotFoundException {
    FileClass fc = new FileClass();
    fc.funcB();
}

Mocking is meant for things that you know ([would]) work but don't want to setup.
As @dzezzz states in the comments, a ClassNotFoundException (is that really the exception you want to test?) could be thrown in the FileClass constructor. If that is not something that should happen and that you want to test, you can set up the following test so that it is only expected from the method invocation
@Rule
public ExpectedException exception = ExpectedException.none();

@Test()
public void testFuncB() throws ClassNotFoundException {
    FileClass fc = new FileClass();
    exception.expect(ClassNotFoundException.class);
    fc.funcB();
}

The test will pass only if a ClassNotFoundException is thrown after the ExpectedException#expect() call.
Comment: @dzezzz Good point. `ClassNotFoundExcepton` can pretty much happen anywhere, but it does help to restrict the scope we want to test. OP really shouldn't be testing that exception though IMO.
Comment: If this exception is thrown in FileClass constructor such test will pass. Better use ExpectedException @Rule and expect exception right before the call of funcB.
Answer: If you test FileClass then don't mock it. You should mock the classes which are used by FileClass.
If you don't want that the exception will come out from test method.
There is a solution:
@Test(expected = ClassNotFoundException.class)
public void testFuncB(){
    try{
        FileClass fc = new FileClass();
        fc.funcB();
        fail();
    }catch(ClassNotFoundException ex){
    }
}

In this solution you catch the exception if it is thrown but your test fails when it isn't.
Comment: Remove the `expected`.


How can I improve my picking accuracy when I'm standing and can't see my guitar strings?

Question: I do most of my guitar practice seated and can easily see the strings when I'm playing solos or arpeggios.  But when I play with my friends, I'm usually standing and can't see the strings to pick.  I'm not horrible at it but I definitely notice my confidence suffers and I make a lot of mistakes with the pick.  Since I'm not likely to start practicing standing up, are there any specific drills or techniques to use to improve my accuracy with a pick?
I realize just not looking is a drill in itself but I'm wondering about any specific drills to focus on this aspect of my technique.  One thing I've tried that seems to work fairly well is to sort of visualize the six strings and just play to an imaginary image that I would see if I was looking.  This works fairly well but seems a bit distracting from my playing. I mostly play simple blues and rock tunes.
Comment: You need to stop looking at your hands.  This is not ideal.
Answer: You've already identified what you need to do...
Practise whilst standing.
If that's the only way to stop you looking at your hands, then do it.
Answer: First point - is your guitar at the same height on your body standing and sitting? If not, then the angles of both hands/arms will be different, making life tricky.
Second point - I guess your picking hand is floating, not touching the bridge or just behind it. This will mean that you have no solid datum point for your hand. It hovers, and that's often a good reason for missing the string you want to play.
Without muting the strings - although it's a pretty good place to do that, put your palm, lightly resting it just behind the saddles. That way, small movements can be made which take your pick from string to string.


Nav also moves when applying margin top in TailWind

Question: When I try to apply margin-top to a container, the container moves, but so does the nav bar, do you guys know what can I do? I am using TailwindCSS, please check the images:
First Image

Second Image

        Home

        About

        Services

        Portfolio

        Contact

Hi! This is

DIEFONRO

Junior Front-End Developer

    <button class="hire">HIRE ME</button>
    <button class="get-cv">GET CV</button>

Comment: try removing "fixed" class from  And "mt-16" from ".container"
Answer: I think adding top-0 to the  will fulfill your wish.
Comment: Literally solved it, thank you so much!


Why do we study the noise sequence in time series analysis?

Question: I am studying time series analysis for the very first time and I cannot seem to get my head around the fact that the entire time series analysis is about studying and modelling the behaviour of the noise component of the time series model. But why is it that we are so concerned about the noise?
From what I could gather is that it's the only component of the time series model (with reference to the classical decomposition model) which is random and thus we should care and try to understand its behaviour. Also, noise is not synonymous to error.
But then what does this exactly imply and how exactly is it useful for understanding the time series at hand?
Any help is much appreciated!
Comment: When you fit a particular time series model you want to know if the model is accurate and testing to see if the noise term is random is part of that, If randomness is rejected you might want to add terms to the model.
Answer: A time-series breaks down to the components seasonality, trend and noise.
Let's take oil prices.
Trend component tells you whether oil prices are going up or down and by approximately how much (steep upward slope, plateauing downward slope etc.)
Seasonality says that given it is winter, what effect does that have on oil prices.
Both the above are derived from the data itself. Now let's take a moment to understand the beauty of the third component- noise.
The most common white noise time series analysis assumes (among other things) that the noise mean zero, some variance and each point of decomposed noise is uncorrelated the signal. The uncorrelated part simply means it is independent of the signal i.e. the trend + seasonality.
Consider the following equations:
y = ax + bz

b is a constant and z is independent of x but contributes to y.
Now what if the true distribution of z actually looked like
z = mp + nq

Now you cannot directly observe or measure p and q but they contribute to z!
If z is your time-series noise, what seems random is actually controlled by a lot of latent variables. Example- changes in foreign policy that make oil import harder, or massive failure of equipment at major offshore oil plant.
All these effects can then be observed in Noise, but cannot be directly attributed or linked to their root cause. So, it becomes essential to model noise in time series analysis.
(Update: for the sake of an interpretable example I imply that foreign policy changes and equipment failure would not impact trend and seasonality. That's not 100% accurate but it is really hard to come up with intuitive latent variables :D)
Comment: What I don't understand is why the noise should be modeled with an AR or MA process. How does doing regression on past errors or past values capture the effect of latent variables?
Answer: Why to be concerned about the noise? If you are not concerned about, than you can have troubles with overfitting (you are modelling noise instead of signal). Also good knowledge about noise allows you to filter that noise, so you can get pure signal. Imagine, that you want to study signal y(t)=sin(t)+sin(3t), where sin(3t) is the noise. If you obtain Fourier spectrum of signal y(t), then you can substract noise and you get pure data signal without noise only because you know information about noise. Also if you want to use for example Kalman filter to predict data, you need to have apriori information about noise, so you can make succesful data fusion and get valid results.
Comment: ok, so keeping this in mind and referring back to the classical decomposition model, we remove the trend and seasonal component as the first step and we are then left with the pure noise sequence. We then model this noise sequence and understand its behaviour to get a better understanding of my original time series and also use the estimated noise sequence for prediction of future values of the observations. Is my understanding correct here?
Comment: Yes, you got the point. Actually knowing the noise parameters can also help us to estimate the confidence of our forecast.
Comment: Imagine, that you are modeling proces that is given as follows: y(t) = f(t) + noise, where noise is value from gaussian distribution with zero mean and some variance sigma. We can say at any time t, that in at time t+1 we are going to obtain value of y(t+1) as (f( t+1) +- 3*sigma) in 99.6% of all cases. We can say this if we know parameters of the noise..


JSON Parsing text are In Encoded Form

Question: I am a newbie in iOS development. I parsed a JSON Data From URL like as:
http://www.janvajevu.com/webservice/specific_post.php?post_id=2885

And I parsed a JSON data from it like as:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.webSpinner startAnimating];
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"http://www.janvajevu.com/webservice/specific_post.php?post_id=2885"]];
dispatch_async(kBgQueue, ^{
    data = [NSData dataWithContentsOfURL: url];
    [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}

-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
    NSError* error;
    self.webDictionary= [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
    self.webArray=[_webDictionary objectForKey:@"data"];
}
self.headingString=[self.webArray valueForKey:@"post_title"];
NSLog(@"Web String %@",self.headingString);
[self.webSpinner stopAnimating];
self.webSpinner.hidesWhenStopped=TRUE;
NSString *headingString=[NSString stringWithFormat:@"%@",self.headingString];
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@"()  \n\""];
self.headLabel.text=[headingString stringByTrimmingCharactersInSet:charsToTrim];
}

Then I got a response like as means I got label text as:
"\U0aaa\U0abe\U0a97\U0ab2 \U0aae\U0abe\U0ab8\U0acd\U0aa4\U0ab0"

And when I parsed English letters from like as here in my URL "author_name" contain English letters when I parsed it then it print as same as in JSON data but other language means here my URL other data contain Gujarati letters then it is parsed in to decoded or not in Gujarati letters.
Here I not encoded my URL in my code then how it come in this format? Please give me solution for it.
Comment: You want that your label show Gujarati text?
Comment: Yes I want My Label Shows Me same text in my URL Shows You Shows My Url JSON Data?Here my JSON Data are in Gujarati font and When I parsed it then it Comes like as "\U0aaa\U0abe\U0a97\U0ab2 \U0aae\U0abe\U0ab8\U0acd\U0aa4\U0ab0"
Comment: For which data you are getting such text? For post title? or for all?
Comment: @Janmenjaya i got this type of text for key "post_title" and i try for key "author_name", "post_views","post_id" then i got data same as in my url.and i not try it for "description" key because this Description key i want to load in WebView.
Comment: Did you get your answer? or else i can modify your function, which will work.
Comment: @Janmenjaya i got my answer.
Answer: You need to convert ASCII(Unicode Escaped) to Unicode(UTF-8).
check this : http://www.rapidmonkey.com/unicodeconverter/reverse.jsp
In first text box put your \U0aaa... text and click convert you will get what you want.
Now how you can do this in Objective-C:
Try this and let me know what you get.
NSData *data = [self dataUsingEncoding:[NSString defaultCStringEncoding]];

NSString *unicodeString = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];

self.headLabel.text = asciiString;

Comment: It Contain Same Value Please You Check it.
Answer: try this
NSString *aDescription  =  self.webArray[0][@"post_title_slug"];
NSString  *aTitle = [[aDescription stringByRemovingPercentEncoding] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

JSON Parsing text are In Encoded Form


$\Gamma(\alpha+1,t)\geq (t+1)\Gamma(\alpha,t)$:Inequality related to incomplete gamma function

Question: I am trying to prove an inequality which goes as
For $\alpha\geq 1$,$\int_{t}^\infty u^{\alpha}e^{-u}du\geq (t+1) \int_{t}^\infty u^{\alpha-1}e^{-u}du$ for any $t\geq 0$. Using the notation of incomplete gaussian function $\Gamma(\alpha+1,t)\geq (t+1)\Gamma(\alpha,t),\forall t\geq 0$.
For example:
Answer: We have
$$\int_t^\infty u^\alpha e^{-u} du = t^\alpha e^{-t} + \alpha \int_t^\infty u^{\alpha -1} e^{-u} du.$$
The inequality is now equivalent to
$$t^\alpha e^{-t} \geq (t+ 1-\alpha) \int_t^\infty u^{\alpha -1} e^{-u} du.$$
If $t\leq \alpha -1$, the inequality is trivial. We consider $t > \alpha -1$. Define the function
$$f(t) = \frac{t^\alpha}{t+1 -\alpha} e^{-t} - \int_t^\infty u^{\alpha -1} e^{-u} du,\quad t > \alpha -1.$$
Differentiating $f$, we get
$$f'(t) = -\frac{(\alpha -1) t^{\alpha -1}}{(t+ 1-\alpha)^2} e^{-t} < 0.$$
Therefore
$$f(t) > \lim_{t\to \infty} f(t) = 0,\quad \forall \alpha -1 < t < \infty.$$
Comment: nice and effective ! (+1)
Answer: I don't have the rep points to comment, so I've put this in an answer box, but have you tried showing the inequality holds at some convenient $t$ (say $t=0$), then differentiating both sides with respect to $t$ (using product rule on the right). If the derivative on the left is greater than that on the right for all $t$ and $\alpha$ under your conditions, then you've got it.
[update]
You can consider this comparing two curves. One is the curve on the left of the inequality, the other on the right. If the curve on the left starts out greater than the one on the right in the range of interest ($t \in [0,\inf)$), and the slope of the curve on the left is always greater than the one on the right, then the function on the left must always be greater. [another update--I wrote this, but I think it's wrong, sorry; I see your point--] [wrong part] This can be true even though the difference between the two curves gets smaller and smaller as $t$ goes to $\inf$. [end wrong part]
Comment: The difference is not increasing as t goes to infinity. Actually, it is a very tight bound when t goes to infinity.


SQL: CASE in JOIN table

Question: We have: 3 tables

users {id, role_id}
staff {user_id}
clients {user_id}

Relation one-to-one — users-staff and users-clients
Sample data:
users_table, client_table
Question: How to select data from these 3 tables optionally?
If users.role_id = 4 join from clients, else join from staff. Can i do like something like this?
I try:
SELECT "users" JOIN CASE WHEN users.role_id IN (4) THEN 'clients' ELSE 'staff' ON "users"."role_id" IN (4) THEN 'clients' ELSE 'staff'.user_id = users.id

But have error

ERROR: syntax error at or near "JOIN" LINE 2: JOIN CASE WHEN users.role_id IN (4) THEN 'clients' ELSE 'sta...
Comment: Please provide sample data and desired results.
Comment: @GordonLinoff edit post with sample data pictures for u
Answer: Is this what you want?
SELECT u.*,
       (CASE WHEN users.role_id IN (4) THEN 'clients' ELSE 'staff' END) as role
FROM users u
WHERE u."role_id" IN (4);

The above works.  But if your tables have other columns, you might want:
select u.*,
       (case when c.user_id is not null then 'client' else 'staff' end)
from users u left join
     clients c
     on u.role_id = 4 and c.user_id = u.id left join
     staff s
     on u.role_id <> 4 and s.user_id = u.id;

Answer: You can use two queries and then use UNION ALL to combine the result:
SELECT
    <columns>
FROM users AS u
INNER JOIN clients AS c
    ON c.user_id = u.id
WHERE u.role_id = 4

UNION ALL

SELECT
    <columns>
FROM users AS u
INNER JOIN staff AS s
    ON s.user_id = u.id
WHERE u.role_id <> 4

SQL: CASE in JOIN table