Mysql acima de 5mil linhas

Question: Bom pessoal estou a desenvolver um código só que me deparei com o seguinte problema, quando realizei teste de performance com 5mil linhas ele excedeu o limite de 30 seg... o que pode esta de errado?
$app->get('/receitagrafico/', function() use ($app) {
$request = \Slim\Slim::getInstance()->request();
 $router = $app->router();

$datai = date("Y-m-01");
$dataf = date("Y-m-t");

    $stmt1 = getConn()->query("SELECT SUM(totalz + entrega - ajuste) AS valor_total_soma FROM movimento WHERE status!='C' AND data BETWEEN '{$datai}' AND '{$dataf}'");
        $onoff = ( $stmt1->rowCount() > 0 ? true : false );
        $dados_produto = $stmt1->fetchObject();
        $total_atual = ( $onoff ? $dados_produto->valor_total_soma : 0 );

    $stmt1 = getConn()->query("SELECT SUM(totalz + entrega - ajuste) AS valor_total_soma FROM movimento WHERE status!='C' AND data BETWEEN '{$datai}' AND '{$dataf}'");
        $onoff = ( $stmt1->rowCount() > 0 ? true : false );
        $dados_produto = $stmt1->fetchObject();
        $bugfix = ( $dados_produto->valor_total_soma == 0 ? 1 : $dados_produto->valor_total_soma );
        $total_passado = ( $onoff ? ($total_atual-$dados_produto->valor_total_soma)/$bugfix*100 : 0 );

$total_lanche = [];
$lanche_lengd = [];
    $stmt1 = getConn()->query("SELECT produtos,data FROM movimento WHERE status!='C' AND data BETWEEN '{$datai}' AND '{$dataf}'");
        $onoff = ( $stmt1->rowCount() > 0 ? true : false );
        while($dados_produto = $stmt1->fetchObject()){
            if ($stmt1->rowCount() > 0) {
                $arr = explode(',', $dados_produto->produtos);
                $arrN_am = array();
                foreach($arr as $item){
                    $valor = explode(':', $item);
                    $arrN_am[][$valor[0]] = $valor[1];
                }
                foreach($arrN_am as $item => $id){
                    foreach($id as $item2 => $id2){
                        $id_produto = $item2;
                        $qtd = $id2;
                        if(is_double($id2)){
                            $qtd = 1;
                        }
                        $stmt3 = getConn()->query("SELECT * FROM produto WHERE hash={$item2}");
                        $resultado_lanche = $stmt3->fetchObject();
                        if (!isset($total_lanche[$resultado_lanche->nome])) {
                            $total_lanche[$resultado_lanche->nome] = $qtd;
                            $lanche_lengd[] = $resultado_lanche->nome;
                        }else{
                            $total_lanche[$resultado_lanche->nome] += $qtd;
                        }
                    }
                }
            }
        }

        if ($onoff){
            $tt3 = $lanche_lengd;
            $tt4 = [];
            foreach($total_lanche as $item => $id){
                $tt4['name'] = 'Abril';
                $tt4['data'][] = $id;
            }
        }else{
            $tt3 = 0;
            $tt4 = false;
        }

echo "[";
echoResponse(200, $total_atual);
echo ",";
echoResponse(200, $total_passado);
echo ",";
echoResponse(200, $tt3);
echo ",";
echoResponse(200, [$tt4]);
echo "]";

});

Retorno:
[53,0,["Torrada","Cachorro quente"],[{"name":"Abril","data":[4,1]}]]

1ªedição: pronto fiz as alterações nas variáveis, na db para DATE, e no código, não coloquei o date como index. Já fiz um teste com 5mil linhas nesse novo código e continua excedendo o tempo
estrutura do bd:

nova comparação... funcionou 5mil querys
        $stmt3 = getConn()->query("SELECT hash,nome FROM produto");
        $resultado_lanche = $stmt3->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
        $resultado_lanche = array_map('reset', $resultado_lanche);
        $resultado_lanche = array_map('reset', $resultado_lanche);

$total_lanche = [];
$lanche_lengd = [];
    $stmt1 = getConn()->query("SELECT produtos,data FROM movimento WHERE status!='C' AND data BETWEEN '{$datai}' AND '{$dataf}'");
        $onoff = ( $stmt1->rowCount() > 0 ? true : false );
        while($dados_produto = $stmt1->fetchObject()){
            if ($stmt1->rowCount() > 0) {
                $arr = explode(',', $dados_produto->produtos);
                $arrN_am = array();
                foreach($arr as $item){
                    $valor = explode(':', $item);
                    $arrN_am[][$valor[0]] = $valor[1];
                }
                foreach($arrN_am as $item => $id){
                    foreach($id as $item2 => $id2){
                        $id_produto = $item2;
                        $qtd = $id2;
                        if(is_double($id2)){
                            $qtd = 1;
                        }

                        if (!isset($total_lanche[$resultado_lanche[$item2]])) {
                            $total_lanche[$resultado_lanche[$item2]] = $qtd;
                            $lanche_lengd[] = $resultado_lanche[$item2];
                        }else{
                            $total_lanche[$resultado_lanche[$item2]] += $qtd;
                        }
                    }
                }
            }
        }

Comment: A gambiarra no armazenamento de data é o maior problema (talvez não seja o unico). Já tem o campo com formato de data por uma razão. Data se formata apenas na hora da exibição, não no banco. A primeira coisa a fazer é converter as colunas da tabela para Date ou DateTime.
Comment: Tem mais um cuidado - o MySQL aceita no between datas ilegais como 31 de janeiro, mas não valida na inserção. Melhor seria rever a lógica do 31, pegando o ultimo dia do mês com PHP - Tem resposta pra isso no site: https://pt.stackoverflow.com/questions/38632/70
Comment: Execute suas queries com um `EXPLAIN` na frente (logo antes do `SELECT`) e poste os resultados aqui. Só assim será possível opinar com precisão. Provavelmente será necessário criar índices nas suas tabelas. Salvar as datas com o tipo adequado em vez de string deve ajudar também.
Comment: O select vai ficar mais ou menos assim: `WHERE data BETWEEN '$id' AND '$id2'`
Comment: Exemplo: em vez de fazer um SELECT pra cada "hash", pode agrupar todos os hashes num array, e fazer um select .... WHERE hash IN ( lista de hashes)  só
Comment: Type: ErrorException
Code: 8
Message: Undefined property: stdClass::$totalz
File: C:\xampp\htdocs\loja\pHpServer-ADm\api\v1\index.php
Line: 4528
Comment: blz vou ajusta esse campo data, mais algum problema critico ou alguma dica para reescrever?
Comment: Tenta isso primeiro, e veja o que mudou. Tou lendo o resto pra ver se tem mais coisa. Lembre que vai ter que arrumar o lado PHP para passar a data em AAAA-MM-DD no between
Comment: Tá fácil, basta converter o campo (sugestão: crie um campo datetime, e não mexa no original ainda, dê um UPDATE tabela SET camponovo = STR_TO_DATE.... campovelho) e depois mude `$id = "01/".$dfaxxx256.$dfa43;` para `$id = $dfa43.'-'.$dfaxxx256.'-01';`
Comment: Se você depois [edit] o post e formatar melhor a indentação do seu código, ajuda a ler também.
Comment: Aliás, nem precisa de 2 variáveis. Pode por os dias no próprio select: `WHERE data BETWEEN '{$anomes-01}' AND '{$anomes-31}' ` - Poderia também usar `WHERE MONTH(data) = $mes AND YEAR(data) = $ano`, simplesmente, mas aí não aproveita índice. Cada caso é um caso.
Comment: @Bacco ja atualizei com o máximo que consegui
Comment: Bom, agora com o código indentado melhor, dá pra ver que você está fazendo outra query dentro do loop da primeira. O problema dificilmente é no MySQL agora, e sim no seu loop. Precisa repensar essa lógica toda pra fazer duas queries apenas. Por exemplo, faz a primeira pra pegar os hashes todos, e depois faz outra pra pegar os produtos. Fora isso, em vez do SELECT *, você pode pegar apenas as colunas que realmente vai usar. Pra ser sincero, refazer o código pensando melhor dá menos trabalho do que tentar consertar essa lógica. Tem muita complicação.
Comment: Mesmo a primeira query, não entendi a razão  de fazer duas vezes. E tem tanto foreach dentro do outro que é até dificil acompanhar. Provavelmente não precisaria de tudo isso. Seria mais fácil se você explicasse a estrutura das tabelas, e o resultado que quer obter (com um exemplo do que deveria ser retornado), em vez de mostrar o modo que acha que vai resolver.
Comment: seguinte a primeira pega o total do mes atual, a segunda pega o total to mes passado, e faz a taxa de crescimento. a terceira query organiza tudo em nome/quantidade
Comment: @Bacco achei aqui... e a logica da terceira querry... agora como simplifico essa analise
Comment: Então, mas vc ta fazendo query dentro de loop. Melhor separar, fazer uma só de cada, e usar agrupamentos e JOINs. Tente simplificar os passos, esquece o que tá feito até agora e repense em como fazer tudo com menos passos
Comment: @Bacco blz vou ver se consigo. vou por um fetchall fora da querry e por esse assay no in pra ver se funciona... correto?
Comment: @Bacco assim é 2 busca do mesmo jeito? ex. SELECT * FROM setor WHERE id NOT IN (SELECT id_setor FROM funcionarios GROUP BY id_setor);
Comment: @Bacco consegui fazer de outra forma... mais funcionou rodou com 5mil querys... pow me ajuda a limpra esse codigo ae como faz com esse IN... pow queria aprender... ou tenho que modular o bd produtos e modificação? qual a melhor opção
Comment: @Bacco eae qual o diagnostico dessa 3ª query?
Answer: Como estás a fazer uma query que usa BETWEEN numa tabela com muitos registos, o campo que usas no between deve estar configurado como INDEX.
O MySQL (e outros motores de base de dados) vão optimizar pesquisas que filtrem por esses campos.
Comment: Index não vai resolver, pois ele não está fazendo between na coluna, e sim numa conversão com STR_TO_DATE. Antes do index ele precisa acertar a coluna para data (vide comentários acima)
Comment: Sim, concordo que o campo tem de ser `date` antes de mais. Mas apesar de ele estar a usar o `STR_TO_DATE`, o campo pode ser `date` já, como não está especificado na pergunta que tipo é, assumo que seja e ai o `INDEX` vai de certeza ajudar.
Comment: @Bacco coloca a tua sugestão de criar campo novo e usar o between sem fazer a conversão como resposta para poder ser votado e aceite. Acho que essa é a solução mais correcta aqui.
Comment: Eu nem postei como resposta ainda pq pode ter outros problemas, só realmente tentei ajudar no que eu vi que claramente está complicado. De qualquer forma, vamos ver se o autor testa e dá um retorno, aí dá para complementar.

Mysql acima de 5mil linhas


Save multiple images on the server

Question: The following function renders a jqplot chart:
function renderChart($chart_id = null){
    //magic...
}

$chart_id defines the id of the chart to be rendered. Each chart has it's own settings.
In the corresponding view of the renderChart function (../views/charts/render_chart.ctp) the chart is displayed. I know that to save it I can use javascript and ajax.
What I need to do is save multiple charts as images on the server.
function saveMultipleImages(){
    renderChart(1);
    renderChart(2);
    renderChart(3);
}

But this solution just redirects me to the first function and stops there.
Comment: I'm confused.  Do you already have the renderChart function working or are you asking for help with that `magic`?
Answer: function renderChart($chart_id = null){
    //magic...

   return true;
  }

function saveMultipleImages(){
 $this->renderChart(1);
 $this->renderChart(2);
 $this->renderChart(3);
}

Save multiple images on the server


Unable to add Guava to NetBeans libraries

Question: I'm trying to add the Guava 18 release to a NetBeans project. I'm downloading it from their GitHub page.
But whenever I navigate in NetBeans, "Project" (right-click)  -> "Properties" -> "Libraries" -> "Add JAR/Folder", I'm unable to add the Guava  JAR that I downloaded.
This is strange, since I have no problem adding the Apache Commons Math JAR that I downloaded (and stored in the same folder).
Can anyone reproduce this problem, by creating a new NetBeans Project (in NetBeans 8.0.2), and trying to add the Guava JAR under Libraries?
Comment: I just downloaded the jar from your link and added it to a project with no apparent problems. Did you get an error message? Maybe the download was corrupted/incomplete. Try jar -tf the file to see if it looks ok.
Comment: I tried jar -tf and it looks okay. I'm using NetBeans 8.0.2 on OS X. I'm thinking this is a NetBeans bug? ... When I add the JAR, it simply doesn't show in the list. Nothing happens. When I add an Apache commons JAR, on the other hand, it shows up and adds successfully.
Answer: Random things to try:

Close netbeans, delete the cache directory (http://wiki.netbeans.org/FaqWhatIsUserdir),  and try again.
Check messages.log for clues. (http://wiki.netbeans.org/FaqLogMessagesFile)
Check nbproject/project.properties

It should have something like:
<code>file.reference.guava-18.0.jar=/home/shackle/Downloads/guava-18.0.jar
includes=**
jar.compress=false
javac.classpath=\
    ${file.reference.guava-18.0.jar}
</code>
You could try adding it manually if you have to.

Import something from guava, if you can still compile maybe it is just a display bug.
Create a Maven project instead, copy over your source, right-click dependencies, and add a dependency. You will need this info:
groupId = com.google.guava
artifactId=guava
version=18.0
Comment: I see, thanks. I ended up checking the box which said "Use dedicated folder for libraries" and that worked. But I feel like I shouldn't have to do this. Maybe I'll look into it more sometime later.


Determinar ordem de exibição de consultas ordenadas no MYSQL

Question: Tenho três tipos de ordens na tabela e preciso obter o resultado de forma que eu escolha quem indexará primeiro.
Preciso a respetiva ordem de indexação: ( ORDEM_COMUM EM PRIMEIRO )
ordem_comum, ordem_lancamento, ordem_catalogo
Tentei os exemplos abaixo ambos trazem a ordem_lancamento primeiro
EXEMPLO 1:
        .
        .
        .
         ORDER BY ordem_comum, ordem_proposta, ordem_lancamento";

EXEMPLO 2:
        .
        .
        .
        ORDER BY ordem_comum ASC, ordem_proposta ASC, ordem_lancamento ASC";

 EXEMPLO 3:
        .
        .
        .
        ORDER BY ordem_lancamento, ordem_proposta, ordem_comum";

CÓDIGO COMPLETO DA SELEÇÃO ABAIXO.
(Não foi eu que modelei e nem tenho permissão de alteração portanto evitar comentários desnecessários)
$sql = "SELECT *
FROM  `IMAGEMCONTROLE`
INNER JOIN  `PRODUTOS_PROPOSTA` ON  `PRODUTOS_PROPOSTA`.`PRODUTO_PROPOSTA` = `IMAGEMCONTROLE`.`IMAGEMCONTROLE_PRODUTO`
WHERE `IMAGEMCONTROLE`.`IMAGEMCONTROLE_LINHA` >0
ORDER BY `PRODUTOS_PROPOSTA`.`ORDEM_LANCAMENTO_ESPECIAL`,`PRODUTOS_PROPOSTA`.`ORDEM_PROPOSTA`,`PRODUTOS_PROPOSTA`.`ORDEM_LANCAMENTO`, `IMAGEMCONTROLE`.`IMAGEMCONTROLE_CATEGORIA`";

Answer: Olá, tente o seguinte:
SELECT
    ordem_comum,
    ordem_proposta,
    ordem_lancamento
FROM
    tableName
ORDER BY
    ordem_comum ASC,
    ordem_proposta ASC,
    ordem_lancamento ASC

Espero ter ajudado, abraço!
Comment: Da uma olhada no código completo da seleção, tentei colocar  'campos,*' mas não da certo


Blind Suggestion Reviewer

Question: Today I rejected this edit suggestion, as the suggested edit was not at all related, the user has edited the answer to add his question regarding same problem.
After My rejection it was approved by two other reviewers (I don't think they have even checked what the edit is  suggested). After  that I found one more edit from the same user and approved by same two reviewers, in this edit also user has added same I am having too problems.
I rollback both the answer to the first revision. What can we do to restrict such blind approvals?
Answer: First of all, thanks for rolling back.
The user that edited the posts will be contacted.
Unfortunately there can't be a general restriction on editing posts.
If you find future edits like this, flag the post explaining what is wrong and actions will be taken for the people that do this and the ones that approve the edits.
Comment: @Piyush, if you found any posts like this, simply do flag (in need of moderator intervention) with some explanation. Then mod will identify the issue.
Comment: I don't think you can flag the edit only.
Comment: is it okay to flag the answer/question for the edit or there is any other option to flag the edit only?

Blind Suggestion Reviewer


Automatically Triggering Airflow DAG in Cloud Composer on GCP without Cloud Functions

Question: Hello Stack Overflow community,
I'm currently working on a project at work where I need to automatically trigger an Airflow DAG in Cloud Composer on Google Cloud Platform (GCP) whenever a .csv file is uploaded to a Google Cloud Storage (GCS) bucket. However, there's a restriction in my organisation that prevents the use of Cloud Functions for this purpose.
I've successfully implemented a solution using Cloud Functions, but due to organisational constraints, I need to explore alternative methods that are both efficient and cost-effective. I would appreciate any guidance or suggestions on achieving this without relying on Cloud Functions.
If you've encountered a similar scenario or have ideas on how to set up this file upload trigger without using Cloud Functions, your insights would be incredibly valuable.
Thank you in advance for your help!
As mentioned, I know how to do this using Cloud Functions, but this is prohibited in my organisation, so I need to find alternative methods.
Comment: Do you know why it's forbidden? Because alternative are many, serverless and very cheap, or more legacy and more costly. I can name at least 2 first: Cloud Run and Cloud Workflow -> This one is funny: use an orchestrator to trigger an orchestrator!! I love it! :))
Comment: No, I do not know the specifics. Though, how would Cloud Run/Cloud Workflow be used to trigger the DAG automatically?
Comment: Cloud Run is very similar to Cloud Functions. That's why, if Cloud Functions is not an option, Cloud Run should not also (if your cloud sec team is aware and smart; not sure!!) You can use Eventarc to catch the Cloud Storage event and invoke your Cloud Run, as you invoke your Cloud Functions. The migration should be simple. Cloud Workflow is different. You can also invoke it with eventarc. However Cloud Workflow can only call API. However you can get eventarc message data and call an API, like Airflow API to run your dag. There are more translation work with this solution.
Comment: As a crazy option -  trigger a Cloud Build job.
Answer: Something I can think of is Polling with a Time-Based DAG
Set up a DAG in Airflow that runs on a regular schedule (e.g., every 5 minutes).
Within the DAG, use a GoogleCloudStorageListOperator to list the files in your GCS bucket.
Compare the current file list with a previously stored list.
If a new file appears, trigger the necessary downstream Airflow tasks or a different DAG.
hope this help :)
ref : https://airflow.apache.org/docs/apache-airflow/1.10.12/_api/airflow/contrib/operators/gcs_list_operator/index.html


Como faço para sobrescrever uma string com acento por outra sem?

Question: Eu queria substituir os caracteres com acento por outros sem e gerar uma nova string, só que parece haver algo errado na comparação que estou tentando fazer na função retiraAcento. Consultei a tabela ASCII, mas ainda não entendi bem o erro. Talvez seja o uso do ponteiro, não sei.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

#define num_moveis 4
#define max_caracteres 256
char retiraAcento(char * nome, int tam);
int verificaNome(char * nome, int tam);
char leValidaNome(char * prodAux);
void menu(char moveis[][256]);
int main(int argc, char *argv[]) {
    char moveisDisponiveis[num_moveis][max_caracteres] = {{"sofa"}, {"mesa"}, {"estante"}, {"escrivaninha"}};
    char prodAux[max_caracteres];
    menu(moveisDisponiveis);
    leValidaNome(prodAux);

    return 0;
}
void menu(char moveis[][256]){
    int i=0;
    printf("Relacao dos moveis disponiveis\n\n");
    for(i=0; i < num_moveis; i++){
        printf("%s\n", moveis[i]);
    }
}
char leValidaNome(char * prodAux){
    int tam = 0, flag = 1;
    do{
        //system("cls");
        printf("\nInforme o produto desejado:");
        scanf(" %[^\n]s", prodAux);
        *prodAux = tolower(*prodAux);
        tam = strlen(prodAux);
        retiraAcento(prodAux, tam);
        //printf("%s", prodAux);
        flag = verificaNome(prodAux, tam);
        system("cls");
        if(flag == 0){
            printf("\nNome vazio ou com numeros!\n");
        }

    }while(!flag);

    return *prodAux;
}
int verificaNome(char * nome, int tam){

    int i=0, flag = 1;
    if(tam == 0){
        flag = 0;
    }else{
        for(i; i < tam; i++){
            if(isdigit(nome[i])){
                flag = 0;
            }else{
                flag = 1;
            }
        }
    }
    //printf("%d", flag);
    return flag;
}
char retiraAcento(char * nome, int tam){
//á = 225, à =224 , é=233, è=232, í=237, ì=236, ó=243, ò = 242, ú = 250, ù = 249
//falta acrescentar mais alguns caracteres
    unsigned char i;

    for(i=0; i < tam; i++){
        if(nome[i] == 225 || nome[i] ==  224){
            nome[i] = 97;
        }else if(nome[i] == 233 || nome[i] == 232){
            nome[i] = 101;
        }else if(nome[i] == 237 || nome[i] == 236){
            nome[i] = 105;
        }else if(nome[i] == 243 || nome[i] == 242){
            nome[i] = 111;
        }else if(nome[i] == 250 || nome[i] == 249){
            nome[i] = 117;
        }
    }
    //printf("%s", nome);
    return *nome;
}

Comment: Qual o pedaço de codigo com problemas então? Na tabela ascii não suporta assentos.
Comment: A função retiraAcento.Quando entra ali, a comparação parece não acontecer.
Comment: Quando eu escrevo "Ó" vai ser armazenado na variavel o "Ó" ? Ou vai ficar outro caracter ? Pode ser ai o problema
Comment: Vai ficar o caracter O, sem acento.
Comment: Esses valores da tabela ascii estão errados, é por isso que dá mal, eu a fazer debug do programa reparo que `á` equivale a `-96`
Answer: Acentos não é suportado na tabela ascii, por isso a origem deste problema todo e por isso impossivel de se fazer.
Mas pode utilizar esse exemplo abaixo faça os prints de debug, como entrada coloque algo como áàéèíìóò e assim vê os valores "ascii" que realmente quer, pois esses valores que colocou são os errados. É possivel utilizar isto no seu compilador, mas se for para outro, muito provavelmente já não dá, como disse acentos não faz parte do ascii.
   for(i=0; i<tam; i++){
        printf("%c %d\n", nome[i],(int)nome[i]);
        system("PAUSE");
        if(nome[i] == 160 || nome[i] ==  224){
            nome[i] = 97;
        }else if(nome[i] == 233 || nome[i] == 232){
            nome[i] = 101;
        }else if(nome[i] == 237 || nome[i] == 236){
            nome[i] = 105;
        }else if(nome[i] == 243 || nome[i] == 242){
            nome[i] = 111;
        }else if(nome[i] == 250 || nome[i] == 249){
            nome[i] = 117;
        }
    }

Comment: Entendi, Fábio. Eu deveria ter feito isto, mas acabei pegando os valores decimais errados na tabela. Vou corrigir aqui. Qualquer coisa, eu volto.


Windows BATCH question mark as script parameter

Question: I cannot figure out how to know if my script is called with a question mark (?)
For example I have run.bat a b c ?
SET /A argCount=0
FOR %%x IN (%*) DO (
    SET /A argCount+=1
    ECHO %%x
)
ECHO %argCount%

This prints as the following, note that the question mark does not register as the 4th parameter.
a
b
c
3

I also tried to call it with the following variations, the question mark just un-detectable.
run.bat a b c ?
run.bat a b c -?
run.bat a b c /?

How do I detect if there is a question mark as a script parameter?
Comment: Command line in Windows 7
Comment: Try quoting with backslash or double quotes: \? or "?"
Comment: `if "%4" equ "?" echo The fourth param is a question mark...`. Remember that a question mark _in a `for` command set_ work as a wild card!
Answer: As noted in the comments, a plain FOR treats the content inside the parentheses as a set of files where * and ? are wildcards.
To avoid this you can treat it as a string instead and use the FOR /F token parsing and a loop or you can use the classic SHIFT command to enumerate the parameters:
@echo off
call :testbatch_recursiveFor a b c ?
ECHO %argCount%

call :testbatch_shift a b c ?
ECHO %argCount%
goto :EOF

:testbatch_recursiveFor
IF "%~1" == "" SET /A argCount=0
FOR /F "tokens=1,*" %%x IN ("%*") DO (
    ECHO arg:%%x
    CALL %0 %%y
    SET /A argCount+=1
)
GOTO :EOF

:testbatch_shift
SET /A argCount=0
:testbatch_shift_loop
IF NOT "%~1" == "" (
    ECHO arg:%1
    SET /A argCount+=1
    SHIFT
    GOTO testbatch_shift_loop
)
GOTO :EOF

Comment: Thank you, the `SHIFT` command is more preferable in my case.


Facing slowness in database server after migrating from SSMS 2008 to SSMS 2016

Question: We have a RDP server which is running in 2008 version of SSMS and OS. Recently we migrated this server to 2016 version, both the OS(2016) and SSMS(2016).
The configured new machine(with ssms2016) is same to the old one(with ssms2008) in terms of system configuration. It has a 64-bit OS with x64-based processor. RAM memory is 64.0 GB and 2.39 GHz (32 processor).
We are facing severe performance issue while running stored procedures in SSMS 2016 version, as the same code base has been migrated from sql server 2008.We are loading data to these servers using SSIS ETL tools.
For example if we are running a stored procedure in old server(with ssms2008) it is taking 1 hour of time to complete the execution but the same SP is taking 10 hours of time in new server(with ssms 2016) sometimes even more.
To identify the root cause we have tried below approaches but so far nothing worked.
•   After migration we changed the compatibility level of sql server from 2008 to 2016.
•   Restored the database once again from old server (ssms 2008) to new server (ssms 2016 ) without changing the compatibility level.
•   Recompiled the stored procedures in new server(ssms2016).
•   updated the statistics in new server(ssms2016).
•   Done the disc reconfiguration/thickening of windows new server drives also.
•   While running time consuming stored procedures in new server(ssms2016), parallely ran sql server
profiler to identify the issue, but couldn't find anything
•   Ran parallelly same query in ssms 2008 and ssms 2016 servers at the same time, in old
server(ssms2008) execution got completed much faster than new server(ssms2016)
Note: Is there any solution we can try to get the same execution time in both servers.
Thanks in Advance
Bala Muraleedharan
Comment: Updating your version of SSMS would have no impact on how long the instance takes to run a query. SSMS is just an IDE. The fact that you *were* using SSMS 2008 implies you are using SQL Server 2008 (or prior) as well, as SSMS 2008 supports SQL Server 2000-2008R2 iirc (SSMS 2016 supports SQL Server 2008-2016). SQL Server 2008, and older, are all end of life now and you should be looking at upgrade paths ASAP.
Comment: Search/replace your question text with "ssms"-->"SQL Server " and it will be clearer. Capture the execution plans of the old and new server queries, upload to [Paste The Plan](https://www.brentozar.com/pastetheplan/), and add those links to your question.
Comment: Go read the documentation about compatibility level - it is not intended for production use and it is not a complete and exact "simulation" of the older version.
Answer: This problem may have two reasons:
1- Control the setting of your SQL server. Specifically limit maximum server memory to 60% of your RAM and increase the number of your tempdb(system database) files to reach to your CPU cores number.
2- Check your SP syntax. If you are using table type variable(@Table) change them to temp table(#Table).
Answer: I'm going to assume the SQL server version got updated too, as SSMS version would not make any difference.
It's impossible to tell of course, but query execution times can be drastically effected by the use of the new cardinality estimator in SQL Server 2014 and above.  99% of the time, things run faster, but once in a while, the new CE gets crushed.  Add this line to the stored procedure to run with the old 2008 CE and see if it makes any difference.
<code>OPTION(QUERYTRACEON 9481);
</code>


not able to post text to fb wall

Question: I am not able to post on fb using this code.getting null in response.after auth login.
<code>     public void postToWall(String message) {

        Bundle parameters = new Bundle();
        parameters.putString("message", message);
        parameters.putString("description", "topic share");
        try {
            facebook.request("me");
            String response = facebook.request("me/feed", parameters, "POST");

            Log.d("Tests", "got response: " + response);
            if (response == null || response.equals("")
                    || response.equals("false")) {
                showToast("Blank response.");
            } else {
                showToast("Message posted to your facebook wall!");
            }
        } catch (Exception e) {
            showToast("Failed to post to wall!"+e.getCause()+e.getMessage());
            e.printStackTrace();
        }
    }
</code>
Comment: which facebook sdk version you are using ?
Comment: 3.15.0 . i can not upgrade because it will increase apk size
Answer: Try this out :
<code>  Bundle parameters = new Bundle();

          parameters.putString("link", "http://www.google.co/");
          parameters.putString("caption","message");
    facebook.dialog(this, "feed", parameters,new DialogListener() {

        @Override
        public void onFacebookError(FacebookError e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(DialogError e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onComplete(Bundle values) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub

        }
    });
</code>
Comment: Try to send message in caption man  @srijanroychoudhury like this  parameters.putString("caption",message);
Comment: npp help, i tried can u post full working code or u just googling and posting
Comment: This code works fine for me i have tested it @srijanroychoudhury and I dont use google search to post answers dear, if i know and work on it i use to post.

not able to post text to fb wall


Cherrypy does not seem to work with curl post request

Question: I have the curious problem where I have a xmlrpc client and requests work fine with the Cherrypy server. I however, noticed that the curl command does not work. I get:
raise cherrypy.HTTPError(404, message=message)
cherrypy._cperror.HTTPError: (404, 'Missing parameters: data')

My cherrypy function is simple:
class XML(cherrypy._cptools.XMLRPCController):

    @cherrypy.expose
    def POST(self, data):
        cherrypy.response.headers['Content-Type'] = 'application/xml'
        return data

#Option 1
headers = {'Content-Type': 'application/xml'}
r = requests.post('http://localhost:8080/XML/POST',
                  data=data,
                  headers=headers,
                  stream=True)
#Option 2
xml_client = xmlrpc.client.ServerProxy('http://localhost:8080/XML/POST')
xml_client.POST(data)

The option that does not work is:
curl --form email@example.com -i -X POST 'http://localhost:8080/XML/POST/' -H 'Content-Type multipart/form-data' -H 'Accept application/soap+xml'

I would like to know why curl is not working with cherrypy the way the other two are working. I did try to find a reason but could not!
Any suggestions will be much appreciated!
EDIT:
Thanks to @cyraxjoe
For the answer, however as this is part of the solution, I want to make it easier to find. Found out that people suggest REST instead of XML-RPC for various of reasons, one could take a look here. So I have removed the XMLRPCController
    class XML():
    @cherrypy.expose
    def POST(self):
        cherrypy.response.headers['Content-Type'] = 'application/xml'
        data = cherrypy.request.body.read()
        return data

Hopefully this will help someone else as well!
Answer: I think that you have to put colons in the header (-H) options for curl.
curl --form firstname.lastname@example.com -i -X POST \
    -H 'Content-Type: multipart/form-data' \
    -H 'Accept: application/soap+xml' 'http://localhost:8080/XML/POST/'

Without them, the Accept header is not configured. You can see what curl sends with the -v option.
Comment: You are correct! However, this is only half of the solution. The other bit is that the cherrypy function does not require parameter to be passed this way.
`cherrypy.request.body.read()` , will read the data passed from curl.


Graphical analysis of the 4th order Runge-Kutta method

Question: Can someone represent the 4th order Runge-Kutta method graphically when iterating from $(x_k,t_k)$ to $(x_{k+1},t_{k+1})$?
Comment: Did you mean like the graphic [*here*](http://jmckennonmth212s09.wordpress.com/2009/02/03/runge-kutta-method-vs-euler-method/) or [*this*](http://www.boomer.org/c/p3/c10/c1003.html)?
Comment: Yes, the first link was very good. Amzoti, could you also please fill in the details for the nonlinear DE question? I worked on it, but having some trouble using a computer software to generate results for Euler, Implicit EUler with the 3 different step sizes. Thanks
Answer: You can look at the graphic here.
Also, you can merge/correlate that diagram in with the graphics I added here.
Comment: Yay!!!!!!!!!!!!!!!!!!!!
Comment: Kind of slowish tonight...
Comment: Could be...we'll still get some action with finals, etc...but it will be interesting to see what summer will be like.


How to express a symmetric polynomial in terms of elementary symmetric polynomials

Question: Can someone explain how to express a polynomial in terms of elementary symmetric polynomial.
(where there is possible) ?
For example if i have the polynomials:
$t_1^3+t_2^3$
$t_1t_2^2+t_2t_3^2+t_3t_1^2$
$t_1^2+t_2^2+t_3^3$
Comment: Only symmetric polynomials can be expressed in terms of combinations of symmetric polynomials. Also, the first polynomial isn't symmetric.
Comment: Don Thousand yes you mean : $t_1t_2^2+t_2t_3^2+t_3t_1^3$ right ,the 2nd one?
Comment: @Don Thousand can u explain how to express a symmetric polynomial in terms of elementary symmetric polynomials??
Comment: @rogerl no cuz the answers there connected yo computer science not math!
Comment: @Almaa Okay, how about [this one](https://math.stackexchange.com/questions/14051/symmetric-polynomials-and-the-newton-identities/14061#14061)?
Answer: Take your first polynomial for instance, which is symmetric in two variables: $x^3 + y^3$. We know that the ring of symmetric polynomials in two variables is generated by $e_1 = x + y$ and $e_2 = xy$, and we have
$$ e_1^3 = x^3 + 3 x^2 y + 3 x y^2 + y^3 = (x^3 + y^3) + 3 xy (x + y) = (x^3 + y^3) + 3 e_2 e_1,$$
and hence $x^3 + y^3 = e_1^3 - 3 e_1 e_2$.
You can do the same ad-hoc method in three variables and you'll quickly find an answer. If you want to see more sophisticated ways of doing this, consult a book on symmetric function theory.


Javascript component based game design

Question: I am developing a browser based game on a node.js server. I'm trying to implement a component based inheritance structure but I am unsure of the concepts with regards to javascript inheritance.
As far as I can make out, if I want to inherit from two component objects e.g. function Moves(){} and function IsVisible(){}, the usual prototypal inheritance doesn't work:
gameObject.prototype = new Moves;
gameObject.prototype = new IsVisible;

The is IsVisible object overwrites the Moves object as the gameObject prototype.
Below is my attempt at creating an inherit function that takes a target object and an arbitrary number of component objects as arguments. The target object then inherits the behavior and variables from the these components.
I'm not familiar with javascript inheritance and would like to know if the below method a good way of implementing a multiple inheritance type structure in javascript?
Are there any other well established practices dealing with this problem? (If it is a problem...)
Any help would be much appreciated.
function inherit(o){

    var proto = o;
    for(var i = 1; i < arguments.length; i++){
        var component =  new arguments[i]();
        for(var x in component){
            proto[x] = component[x];
        }
    }
}

function Player(name){

    var o = {};
    o.name = name;
    inherit(o, WorldSpace, Active);
    return o;

}

function WorldSpace(){
    this.pos = {x:0, y:0};
    this.orientation=0;
}

function Active(){
    this.acceleration = 1;
    this.velocity = {x:0,y:0};
    this.rotation = 0;
    this.rotationSpeed = (Math.PI*2)/30;
    this.throttle = false;
    this.currentSpeed = 0;
    this.maxSpeed = 10;
}

Comment: You don't want multiple inheritance, you want only mixins - you have no prototypes in your code. AaditMShah is perfectly right.
Comment: @Bergi Your line is now my googlism: http://www.googlism.com/who_is/a/aaditmshah/
Comment: Try making Player a constructor, and use the traditional way of javascript inheritance as can be found all over the web.
Comment: @Bergi Javascript doesn't support multiple inheritance so using `person.prototype = new WorldSpace; person.prototype = new Active` wouldn't work.
Answer: From what I see in your code you don't really need multiple inheritance. You are simply trying to mix in code from different constructors into one. This is possible and is actually really simple to achieve in JavaScript.
First let's rewrite your code for Player:
function Player(name) {
    this.name = name;
    WorldSpace.apply(this);
    Active.apply(this);
}

That's it. Simple right? Let me explain how the apply function works:

Every function in JavaScript has a special pointer called this.
When you call a function normally this usually points to the global object (e.g. window).
When you call a function preceded by the keyword new JavaScript creates an instance of that function and this points to that instance.
JavaScript also has two functions call and apply which are methods of every function and allow you to call that function with any value for the this pointer.

So essentially when I call WorldSpace.apply with this as the first argument, the this pointer in the WorldSpace function points the this in Player. You are essentially using the WorldSpace and Active constructors as mixins.
If you want to know more about how inheritance works in JavaScript I suggest you read this answer. Have you considered using a framework to make your life simpler?
Comment: Brilliant, I knew there must be a better way of doing it. I'm not considering a framework at the moment to concentrate on learning core javascript. Thanks for your help.

Javascript component based game design


Is it possible to prove everything in mathematics by theorem provers such as Coq?

Question: Coq has been used to provide formal proofs to the Four Colour theorem, the Feit–Thompson theorem, and I'm sure many more. I was wondering - is there anything that can't be proved in theorem provers such as Coq?
A little extra question is if everything can be proved, will the future of mathematics consistent of a massive database of these proofs that everyone else will build on top of? To my naive mind, this feels like a much more rigorous way to express mathematics.
Comment: It shouldn't be possible due to Goedel's Incompleteness Theorem.
Comment: The set of theorems of a computably-axiomatised first-order theory is computably enumerable – this is indisputable. So perhaps the question should be, can all of mathematics be captured in a sufficiently powerful first-order system?
Comment: Define "everything" and "possible" :) It's not clear from what I've read that Coq "proved" Feit Thompson, only that it verified a proof. In theory, you can write a "dumb" proof generator that checks all possible proofs for correctness, and thus yields all provable results. Coq might be more efficient, but it cannot be more complete than that.
Comment: Sure, but there is an "internal" meaning to incompleteness, and an "external" meaning to incompleteness. Basically, it is just saying that sufficiently complicated axioms cannot yield complete systems. That some axiom systems are incomplete is obvious (take the axiom for a ring and try to resolve the question "Is 1+1=0?") The shock of incompleteness is that we want our axioms to represent something, the natural numbers, we feel is "concrete." Essentially, complicated systems of axioms will have to be like the axiom for a ring.
Comment: Putting it briskly, Gödel's First Incompleteness Theorem uses rather elementary reasoning (and it was very important to Gödel that this was the case). Which is why the Theorem is formalizable in arithmetic, the point we rely on to prove the Second Theorem!
Answer: One of the computability results is that there must exist provable theorems in number theory that require very long proofs relative to their statements.
If $n$ is the encoding of a statement in number theory which can be proven, and $f(n)$ is the length of the shortest proof of that statement, then the function $$G(n)=\max \{f(k): k\leq n, k \text{ encodes a provable theorem}\}$$ is not only not computable, but it cannot be bounded above by any computable function, or else we could write a program that could essentially "find" all decidable statements - the set of decidable theorems would be recusrive, not just recursively enumerable. (I initially had an argument here about why that would be a problem, but that argument was flawed. I'm still pretty sure it is wrong for the decidables to be recursive, but it will take more work.)
In particular, then, for any total computable function $h$, there must be a provable theorem encoded by some $n$ such that the shortest proof, when encoded, is greater than $h(n)$.
So, in a practical sense, there will always be harder theorems, where we need more storage and compute time to verify the entire proof.
Comment: nit. technically true but I think the spirit of the question is "can all _provable_ theorems in mathematics be expressed in Coq?"
Answer: It is reasonable to believe that everything that has been (or can be) formally proved can bew proved in such an explicitly formal way that a "stupid" proof verification system can give its thumbs up. In fact, while typical everyday proofs may have some informal handwaving parts in them, these should always be able to be formalized in a so "obvious" manner that one does not bother, in fact that one is totally convinced that formalizing is in principle possible; otherwise one won't call it a proof at all.
In fact, I sometimes have the habit to guide people (e.g. if they keep objecting to Cantor's diagonal argument) to the corresponding page at the Proof Explorer and ask them to point out which particular step they object to.
For some theorems and proofs this approach may help you get rid of any doubts casting a shadow on the proof: Isn't there possibly some sub-sub-case on page 523 that was left out? But then again: Have you checked the validity of the code of your theorem verifier? Is even the hardware bug-free? (Remember the Pentium bug?)
Would you believe a proof that $10000\cdot10000=100000000$ that consists of putting millions of pebbles into $10000$ rows and columns and counting them more than computing the same result by a long multiplication?
Answer: Coming from a practical angle (i.e., not discussing the limits on logic that we know about due to the incompleteness theorem etc), your question might be rephrased as "Can we do all of the math that we do on paper, in Coq?"
The answer is "Dunno, it's tough. We'll get back to you."
You're not the first person to think so though, and there are efforts to "put math on computers". Check out Homotopy TT.
To elaborate a bit:
The main reason is that a large portion of mathematics is done using set theory as the working foundation, but set theory is not amenable to being expressed with computers. It's too declarative. The internal logic in Coq (Calculus of Co-inductive Constructions) is based on Martin-Löf Type Theory, which is a quite a different kettle of fish. So some definitions, although equivalent, aren't the same, and some of the low level stuff is not built up in the same way.
Widening the gap between the paper and machine worlds is that there is a preference for Constructive Math in the machine world. (oversimplifying: a preference for not using the law of excluded middle (or equivalent classical axioms/rules)) and intuitionistic logic.
Addendum: What I've been talking about above is how the logical foundations of coq are different from traditional foundations. That said, Coq is still doing math, that requires logical foundation, that is still subject to the limitations of formal logic. The incompleteness theorems etc.
P.S. - No physical computer system can by guaranteed bug free by mathematics. Even if your hard and software is verified, cosmic radiation/favourite energy source may cause bits in your machine to flip and all your verification goes out the window. Even with verification, some programs should be run in triplicate.
Answer: It is unlikely that Archimedes thought about theorems in category theory. In the future there will likely be new areas of mathematics. While a theorem prover might have encodings of results in these new areas they might not be readable for humans.


Install problems with XSendFile on Ubuntu

Question: I installed the apache dev headers:
sudo apt-get install apache2-prefork-dev

Downloaded and compiled the module as outlined here: http://tn123.ath.cx/mod_xsendfile/
Added the following line to /etc/apache2/mods-available/xsendfile.load:
LoadModule xsendfile_module /usr/lib/apache2/modules/mod_xsendfile.so

Added this to my VirtualHost:
<VirtualHost *:80>
    XSendFile on
    XSendFilePath /path/to/protected/files/

Enabled the module by doing:
sudo a2enmod xsendfile

Then I restarted Apache. Then this code still just provides me with an empty file with 0 bytes:
file_path = '/path/to/protected/files/some_file.zip'
file_name = 'some_file.zip'
response = HttpResponse('', mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(file_path)
return response

And there is not in the Apache error log that pertains to XSendFile. What am I doing wrong?
Comment: What do the headers look like that are received by the client?  Have you tried setting a more verbose log level (e.g., `LogLevel debug`)?
Answer: I got my code to work. The only difference is:
def serve_file(request, file):
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename="%s"' % smart_str(os.path.basename(_(file.file.name)))
    response['X-Sendfile'] = smart_str(_(file.file.path))
    # It's usually a good idea to set the 'Content-Length' header too.
    # You can also set any other required headers: Cache-Control, etc.
    return response


Django nullbooleanfield is defaulting to 'False' when left empty on form, shouldn't be Null?

Question: models.py
my_field = models.NullBooleanField(null=True)

forms.py
my_field = forms.BooleanField(
    label='my_field',
    required=False,
    widget=forms.RadioSelect(choices=[(True,'yes'),(False,'no')]))

When the form is submitted without the radio buttons selected, the form saves and defaults to false. Shouldn't it default to Null?
Comment: Shouldn't you use a `NullBooleanField` here in the form?
Answer: Your form uses a forms.BooleanField as form field, so it has no notion of None. You should use a NullBooleanField [Django-doc]:
class SomeForm(forms.Form):
    my_field = forms.NullBooleanField(
        label='my_field',
        required=False,
        widget=forms.RadioSelect(choices=[(True,'yes'),(False,'no')])
    )
As the documentation of the NullBooleanField says:

NullBooleanField
class NullBooleanField(**kwargs)

Default widget: NullBooleanSelect
Empty value: None
Normalizes to: A Python True, False or None value.
Validates nothing (i.e., it never raises a ValidationError).

Whereas for a BooleanField, the empty value is False:

BooleanField
class BooleanField(**kwargs)

Default widget: CheckboxInput
Empty value: False
Normalizes to: A Python True or False value.
Validates that the value is True (e.g. the check box is checked) if the field has required=True.
Error message keys: required


How to generate for loop number sequence by using variable names in bash?

Question: Could anybody explain how can I use variable names in bash for loop to generate a sequence of numbers?
for year in {1990..1997}
do
  echo ${year}
done

Results:
1990
1991
1992
1993
1994
1995
1996
1997
However
year_start=1990
year_end=1997
for year in {${year_start}..${year_end}}
do
  echo ${year}
done

Results:
{1990..1997}
How can I make the second case work? otherwise I have to write tedious while loops.
Thanks very much.
Answer: You can use something like this
for (( year = ${year_start}; year <=${year_end}; year++ ))
do
  echo ${year}
done

seq command is outdated and best avoided.
http://www.cyberciti.biz/faq/bash-for-loop/
And if you want real bad to use the following syntax,
for year in {${year_start}..${year_end}}

please modify it as follows:
for year in $(eval echo "{$year_start..$year_end}")

http://www.cyberciti.biz/faq/unix-linux-iterate-over-a-variable-range-of-numbers-in-bash/
Personally, I prefer using for (( year = ${year_start}; year <=${year_end}; year++ )).
Answer: Try following:
start=1990; end=1997; for year in $(seq $start $end); do echo $year; done

Comment: `seq` command is outdated, and not recommended for `bash v3.x+`
Comment: @chepner Would like to know the reason for not using backticks. Could they cause other problems?
Comment: @Sithsu They're hard to read, and hard to nest. There's no real reason to use them in place of `$( ... )`.


Pearson correlation coefficient test: low $r$ and low p-value

Question: I am running a correlation coefficient test, and the results were: $r = 0.382, p = 2.76 \times 10^{-13}$.  So the $r$ value is not that impressive (usually we see $r>.5$), but the $p$-value is still significant.  Usually I would think a low $r$ value would mean high $p$-value (no significant correlation), or vice versa (low $p$-value would mean a high $r$ value).
Could anyone please explain what this means?
Comment: "My statistic isn't very big but the p-value is tiny! What gives?" is an incredibly common question here (what gives is usually large sample size). The question usually indicates (i) some lack of understanding of [what a p-value is](http://en.wikipedia.org/wiki/P-value); and (ii) a problem you probably shouldn't have been calculating p-values for in the first place (if small p-values on small effects seem wrong, it's because you're probably actually interested in effect size). Significance tests are vastly overused.
Comment: You have a weak correlation, but it's definitely not zero. Where's the puzzle? If the correlation were higher, the P-value would be even smaller.
Comment: If you have some kind of absolute sense of "low" and "high" values of $r$, then what's the point of computing a p-value in the first place?  Perhaps you might enjoy reading the thread at http://stats.stackexchange.com/questions/31/what-is-the-meaning-of-p-values-and-t-values-in-statistical-tests.
Answer: This is a frequently asked question.  What constitutes a "low" (or 'weak', etc.) correlation is subject specific.  I'll take your word for it that in your field, $r = .382$ is "low".  The reasons why this might have turned out to be lower than you expected can be any number of possibilities including:

bad luck
range restriction
higher than normal error of some type (e.g., measurement error)
the correlation varies according to some factor you aren't aware of that happened to obtain in this case but doesn't typically

The reason you had a low $p$-value anyway is presumably due to high $N$.
Answer: You can look at a critical value table for Pearson's correlation to determine significance. You will need to look at your df, which is the number of participants minus 2 for Pearson's correlation.  For example, if you have 27 participants, your df is 25 (27-2). When looking at the critical value table, you need to find your df (25) at your set alpha level. If your alpha level is .05, then your r value will need to be higher than .381.  If it is, then you have significance, and you can say p <.05, or that your results have less than a 5% chance of error.  If your r value is lower than .381, then you do not have significance. Therefore, it is possible to have a low p value with a low r value because you are looking at the critical value table to tell if you have significance, not the p value. The p value is saying that you are 95% correct that your r value carries significance based on the critical value table. I obtained my understanding from the following website: http://www.gifted.uconn.edu/siegle/research/correlation/alphaleve.htm.
Answer: Basically you're explaining a situation where the relationship between your variables is very weak, but you have sufficient sample size or power to draw significant conclusions about it anyways. Depending on the question you want to explore, I would say what you have is a weak (albeit statistically significant) relationship, and if that relationship is between something like migration timing for salmonids and condition indexes, your relationship will not help you draw any biologically relevant information. You are likely missing a part of the picture when you have these results and testing correlation and covariates then running a multiple regression with un-related independent variables may really help. Be very careful how you interpret these results. Statements like "highly significant relationships" are a little misleading if not applied with the appropriate caveats.
Comment: "migration timing for salmonids and condition indexes" "biologically relevant information": I see no sign here that the OP's data are biological. If that's intended as an example that should make sense to non-biologists too, then the spirit is right but I don't think the example will work well.


Array Bidimensional

Question: Gostaria de percorrer com for um array bidimensional conforme o código:
var cadeiras = [[true, false, true, true, true, false, false, true, true, true, false, false],
               [true, false, true, true, true, false, false, true, true, true, false, false],
               [true, false, true, true, true, false, false, true, true, true, false, false],
               [true, false, true, true, true, false, false, true, true, true, false, false]];

for (i = 0, i < cadeiras.length, i++){
for (j = 0, j < cadeiras[i].length; j++) {
    if([i][j]){
    var reserva = confirm("A cadeira " + (j+1) + " na fila " + (i+1) + " está disponível. Deseja reservá-la?");
        if(reserva){
            document.getElementById("assento" + numeroCadeira).src = "img/cadeira-tulipa-reservada.jpg"
            document.getElementById("assento" + numeroCadeira).alt = "reservada"
            document.getElementById(numeroCadeira).classList.remove("panel-default");
            document.getElementById(numeroCadeira).classList.add("panel-success");
            alert("A cadeira " + (j+1) + " na fila " + (i+1) + " está reservada.");
            break;
        }
    }
}

}
O objetivo é verificar se a cadeira está livre e caso esteja livre dar ao usuário a opção de aceitá-la.
Caso seja aceita, o loop deve ser interrompido.
Desde já agradeço a ajuda.
Comment: E qual o problema? Aparentemente o código já esta fazendo esse trabalho.
Comment: O código, como estava, não estava rodando por conta dos problemas de ponto e vírgula e do break que não estava sendo usado de forma correta.

Obrigado pelo seu comentário.
Comment: Não tinha reparado. De nada, precisando só chamar.
Answer: Primeiramente, corrija a sintaxe do for substituindo , por ;
Depois, para sair de ambos os loops ao mesmo tempo, o break não resolverá. Encapsule tudo dentro de uma function, e ao reservar a cadeira, chame return para sair de ambos os loops.
function reservarCadeiraDisponivel() {
    for (i = 0; i < cadeiras.length; i++) {
        for (j = 0; j < cadeiras[i].length; j++) {
            if ([i][j]) {
                var reserva = confirm("A cadeira " + (j + 1) + " na fila " + (i + 1) + " está disponível. Deseja reservá-la?");
                if (reserva) {
                    document.getElementById("assento" + numeroCadeira).src = "img/cadeira-tulipa-reservada.jpg"
                    document.getElementById("assento" + numeroCadeira).alt = "reservada"
                    document.getElementById(numeroCadeira).classList.remove("panel-default");
                    document.getElementById(numeroCadeira).classList.add("panel-success");
                    alert("A cadeira " + (j + 1) + " na fila " + (i + 1) + " está reservada.");
                    return;
                }
            }
        }
    }

  alert("Nenhuma cadeira disponível");
  return;
}

Comment: Obrigado alvarodms.
O problema era exatamente esse.
Answer: A syntax do seu for esta errada, se usa ; e não ,, fiz um exemplo que retornará todos os valores, dentro do if basta colocar a ação se a cadeira estiver vaga:

var cadeiras = [
  [true, false, true],
  [false, false],
  [true]
];

for (i = 0; i < cadeiras.length; i++) {
  for (j = 0; j < cadeiras[i].length; j++) {
    console.log(cadeiras[i][j]);
    if (cadeiras[i][j]) {
      var reserva = confirm("A cadeira " + (j + 1) + " na fila " + (i + 1) + " está disponível. Deseja reservá-la?");
      if (reserva) {
        // faça algo se for reservado.
        return false; // saia do loop.
      }
    }
  }
}

Veja funcionando no: JsFiddle
Comment: Perfeito Gabriel.
Muito obrigado pela resposta.
Answer: Me parece algo muito simples, segue um exemplo:
Considere que uma matriz percorre os elementos através de um axis:
+------------------> x
|[true, false, ...]
|[true, false, ...]
|[true, false, ...]
v
y

Para percorrer em javascript, basta fazer algo assim, e armazenar os dados em um objeto.
 var cadeiras = [
                 [true, false, true, true, true, false, false, true, true, true, false, false],
                 [true, false, true, true, true, false, false, true, true, true, false, false],
                 [true, false, true, true, true, false, false, true, true, true, false, false],
                 [true, false, true, true, true, false, false, true, true, true, false, false]
                ];
     var free = {"acesso":false};
    for (var y in cadeiras) {
          var x = 0;
          //percorre enquanto for indisponível
          while (cadeiras[y][x] === false) {
            x++;
          }
           //sai quando achar o disponível
           free = {"acesso":cadeiras[y][x], "x":x, "y": y};
          break;
    }
console.log(free); //a saída será: {acesso: true, x: 0, y: "0"}

Depois é só exibir o objeto:
alert("A cadeira "+free.x+" da fila "+free.y+" está "+((free.acesso) ? 'livre' : 'indisponível')+"!");

Comment: Obrigado pela resposta Ivan.
Answer: Situação
Pelo que notei esta é uma rotina que você ira chamar varias vezes, ou seja se deve atualizar o valor das cadeiras.
Problemas

Como ja apontados pelas demais respostas, você esta usando , no lugar de ; nas divições do for.
Sua verificação esta if([i][j]), não sei qual array ele esta comparando aqui, diria um dado aleatório.
você nao esta ajustando o valor da cadeira.
Para sair de uma iteração em javascript se usa return não break.

Codigo
var cadeiras = [
    [true, false, true, true, true, false, false, true, true, true, false, false],
    [true, false, true, true, true, false, false, true, true, true, false, false],
    [true, false, true, true, true, false, false, true, true, true, false, false],
    [true, false, true, true, true, false, false, true, true, true, false, false]
];

function reservar(){
    for (i = 0; i < cadeiras.length; i++){
        for (j = 0; j < cadeiras[i].length; j++) {
            if(cadeiras[i][j]){
                if(confirm("A cadeira " + (j+1) + " na fila " + (i+1) + " está disponível. Deseja reservá-la?")){
                    console.log("A cadeira " + (j+1) + " na fila " + (i+1) + " foi reservada");
                    cadeiras[i][j] = false;
                    return;
                }
            }
        }
    }
}
reservar();
reservar();

OBS
Eu faria em uma função encapsulada, para não usar variável global.
Comment: Ótimo Guilherme.
Muito obrigado pela resposta.
Na verdade esse é só um trecho de um código maior.
Tudo está em um IIFE. Mas mesmo assim obrigado pela dica.

Array Bidimensional


Como recuperar dados do componente Route do Angular?

Question: Vi na documentação do Angular que é possível recuperar dados armazenados na propriedade date (que recebe um objeto) de uma route. Tenho, nesse caso uma aplicação com as seguintes rotas:
const routes: Routes = [
  {
    path: '',
    component: UserComponent,
    data: {
      title: 'Home'
    }
  },
  {
    path: 'bank-accounts',
    component: BankAccountsComponent,
    data: {
      title: 'Contas correntes'
    }
  },
];

Como eu posso recuperar esses dados (o título, no caso) em uma rota?
Answer: Oi,
Para recuperar os dados siga o exemplo abaixo:
BankAccountsComponent:
class BankAccountsComponent {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route
      .data
      .subscribe(v => alert(JSON.stringify(v)));
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

Para mais detalhes veja o doc do Angular https://angular.io/guide/router#fetch-data-before-navigating
Veja tambem https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
Comment: Para recuperar os dados voce deve armazenar a variavel v em uma variavel interna.
Editei a resposta para dar um alerta mostrando o valor recuperado.
Comment: depois eu pego a propriedade `sub` e faço `this.sub.title` para recuperar os dados, isso?


Select from two tables, based on 2 columns one of which must not be distinct

Question: Say I have 2 tables, one storing info on items, and second one used for tracking various quantities linked to said item.
My item has an order number, id number and an lot number. The quantities from second table I'm interested in are "quantity ready" (how many I have in stock), "quantity ordered" (how many clients have ordered) and "quantity shipped" (how many I sent already). Both tables have more data, but I don't need it for this query.
What I want: a query that will return to me all order numbers which contain items that have more than one lot number (so if an item has only a single distinct lot number, I don't want it in results), which I already have some of (so qty_ready > 0) and which I shipped some, but not all of my order (so qty_shipped < qty_ordered).
Example:
Table Item:
+-------+--------+------------------+
| IdNum | LotNum | Someothercolumns |
+-------+--------+------------------+
|     1 | 10-00  |              123 |
|     2 | 10-01  |              123 |
|     2 | 10-02  |              123 |
|     3 | 10-03  |              123 |
|     3 | 10-04  |              123 |
+-------+--------+------------------+

Table ItemQty:
+----------+---------+-----------+-------------+-------------+-----+
| orderNum | idNum   | qty_ready | qty_ordered | qty_shipped |other|
+----------+---------+-----------+-------------+-------------+-----+
| O1       |       1 |        10 |           5 |           3 | 123 |
| O2       |       2 |        10 |          10 |          10 | 123 |
| O3       |       2 |        10 |           5 |           3 | 123 |
| O4       |       3 |         0 |          10 |           5 | 123 |
| O5       |       3 |         0 |           5 |           5 | 123 |
+----------+---------+-----------+-------------+-------------+-----+

Here I would want only O3 and it's data returned, since:

O1 - item 1 has only a single lot associated with it
O2 - item 2 has more than one lot, but the order is already completed
(10 ordered and 10 sent)
O4 - item 3 has more than one lot, but
qty_ready is not > 0
O5 - item 3 has more than one lot, but
qty_ready is not > 0 and it is already completed (5 ordered and 5
sent)

Here is my try at the query - although it returns the data, it does return many duplicate rows (if an item has 4 lots, I would get each result 4 times, so 16 rows). I suspect my joins are the problem, but I can't seem to find it:
;with noo as (select count(LotNum) over(partition by LotNum) as temp,  Item.*
from Item
inner join ItemQty on ItemQty.idNum = Item.idNum
where Item.idNum in
(select t1.idNum
from Item t1
inner join Item t2 on t1.idNum = t2.idNum
where t1.LotNum <> t2.lotNum) and qty_shipped < qty_ordered and qty_ready > 0)
select * from noo where temp > 1
order by idNum desc

Answer: select * from itemqty
where idnum in
(select idnum from item group by idnum having count(*) > 1)
and qty_ready > 0
and qty_ordered > qty_shipped
and qty_shipped > 0

sqlfiddle


How to change UIDatePicker to a specific time (in code)

Question: I need to change the UIDatePicker to a specific dynamically.
My date picker is set to time mode only.
i can set the time with
timePicker.setDate(NSDate(), animated: false)

but i cant figure out how to change it to a different time and not to
current time.
So how do i change it?
Thanks
Answer: You've to change the time, you can do it using NSDateComponents and set the modified date to your DatePicker
var calendar:NSCalendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit, fromDate: NSDate())
components.hour = 5
components.minute = 50
datePicker.setDate(calendar.dateFromComponents(components)!, animated: true)

Comment: Please don't ever do this if the `UIDatePicker` is in time only mode. The reason is that, imagine the above code is executed  in New York at 14 March 2021. If the code trying to change the hour = 2. It will be very wrong. Due to Day Light Saving, there is no 2am in 14 March 2021. A correct way is to hard coded a timezone without DST like GMT, so that user can read/ write time only information to DatePicker without the above mentioned issue.
Answer: Swift 3 and 4:
extension UIDatePicker {

   func setDate(from string: String, format: String, animated: Bool = true) {

      let formater = DateFormatter()

      formater.dateFormat = format

      let date = formater.date(from: string) ?? Date()

      setDate(date, animated: animated)
   }
}

Usage:
datePicker.setDate(from: "1/1/2000 10:10:00", format: "dd/MM/yyyy HH:mm:ss")

Comment: Perfect Solution, Thanks @Zombie checked in Swift 4
Answer: Swift 5
let calendar = Calendar.current
var components = DateComponents()
components.hour = 5
components.minute = 50

timePicker.setDate(calendar.date(from: components)!, animated: false)

Answer: To set the date pick (time only) to a specific time such as "09:00" I would set the NSDateComponents and picker like this.
let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.hour = 9
components.minute = 0
timePicker.setDate(calendar.dateFromComponents(components)!, animated: true)

Comment: Useful for setting UIDatePicker when using datePicker.datePickerMode = UIDatePickerMode.CountDownTimer
Answer: You can customize it by formatting your Date and Time this way:
let dateString = "12-11-2015 10:50:00"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let date = dateFormatter.dateFromString(dateString)

timePicker.setDate(date, animated: false)

Comment: i need to set a UIDatePicker not a textfield
Comment: format Date and Time is not the answer for setting date and time for UIDatePicker
Comment: Updated: Divi I see what you try to do and could've made more clear by adding more code to yours. I try to undo vote but couldn't.
Answer: you can use it like this
timePicker.setDate(NSDate(timeInterval: 60, sinceDate: NSDate()), animated: false)

or
timePicker.setDate(NSDate(timeIntervalSinceNow: 60), animated: false)

it would set date with difference of 1 minute from current date.
Comment: I need to change to a totally different time. i get a time from server in "HH:mm" format and i need to show it in date picker
Answer: If u do not want to type multiple lines of code each time when you want Date or Time from string
U can copy below function and use as
let DateVar = DateTimeFrmSrgFnc("31/12/1990",FmtSrg: "dd/MM/yyyy")

timePicker.setDate(DateVar, animated: false)

func DateTimeFrmSrgFnc(DateSrgPsgVar: String, FmtSrg FmtSrgPsgVar: String)-> NSDate
{
    // Format: "dd-MM-yyyy HH:mm:ss"

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = FmtSrgPsgVar
    return dateFormatter.dateFromString(DateSrgPsgVar)!
}


If a number is not divisible by 2, 3 and 5, is enough to say that number is prime?

Question: I'm Computer Science student. Last day, my teacher say this to the class room: "If a number is not divisible by 2, 3, and 5, mean that number is prime. This because odd numbers are divisible by 3 or 5, and even numbers by 2".
That can be true? If it's or not, why?
Edit: I'm not an mathemathician. I necer belive the words of my teacher. I just want an professional clarify.
Comment: I'm voting to close this question   because I think it's one you should have been able to answer for yourself with a little thought about what "prime" means and a little arithmetic on numbers less than $100$. Did your teacher really say this seriously?
Comment: I wonder if this is a serious question. I don't believe that you really think any odd number is divisible by 3 or 5. I'm sure you know that $49=7^2$.
Comment: I would be interested in the sentence or two that your teacher said before or after those sentences. Perhaps you missed words like this: "Is the following true?" Even if not, a much, much better alternative (than coming to this web site) would have been to raise your hand and say "That is not true".
Comment: I swear. And make a little function in Python to "prove" this. 3 simple conditionals: if n mod {3, 2, 5} is not 0, then is prime.
Comment: You may be interested to read about the [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), a (*tedious*) way of finding all prime numbers within a certain range.  The claim that all numbers not divisible by $2,3,5$ are prime should be obviously false.  Those numbers which are not divisible by $2,3,5$ are simply those numbers still left in the sieve after the first three iterations of the algorithm, but there are still many more steps left to perform in the algorithm (*getting rid of all proper multiples of $7$, all proper multiples of $11$, etc...*).
Comment: For small counterexamples of numbers which are divisible by none of $2,3,5$ but which are not prime, consider $7\times 7 = 49, 7\times 11 = 77, 7\times 13 = 91, 11\times 11 = 121,\dots$
Comment: A correction to the statement that will make this true: "*If $x$ is a natural number between $2$ and $48$ and $x$ is not divisible by any of $2,3,5$ then $x$ is prime.*"  Once the upper bound on $x$ is removed however, this as mentioned is false.  We also needed the lower bound since $1$ is not considered a prime number.  (*Note: $x$ is a composite number if and only if there is some prime $p$ which divides $x$ such that $p\leq \lfloor \sqrt{x}\rfloor$, i.e. when searching for divisors, we need not look any further than the square root.*)
Comment: @Mark I never belive that. I always think that need to do a brute force algorithm to check all numbers above the possible prime. I only wanted to a real mathemathician clarify me.
Comment: And I just get -3 point. Ok. Thanks to all that response me with fundament.
Answer: $49$ is not divisible by any of those number but it is not a prime.
In general, take a prime number that is not $2,3,$ or $5$, consider $p^n$ where $n \ge 2$ works as a counter example.


Could not copy the file "..\HiQPdf.dep" because it was not found

Question: I get this build error after trying to use HTML to PDF Converter Library for .NET. I copy over the dll, dep and xml files from the ZIPped folder downloaded from the website but when I compile my code, the HiQPdf.dep disappears.
The FAQs from the website say to change the execute permissions of the HiQPdf.dep file but after i do this, it still doesn't work.
How can i get rid of this error?
Answer: I resolved this by changing the execute permissions on the HiQPdf.dep file and then changing it to read-only. I don't see how this is a stable or logical fix but it is working now.
Answer: I solved this issue by just removing & re-adding the dll.


Generate Plugin .dat File when Building JAR with Gradle

Question: I have a JAR that I have created with a few custom plugins that I would like to use in other projects. For some background, I have attempted to use <Configuration packages="com.package.with.custom.appenders"> in the log4j2.xml for the application consuming my JAR with the custom plugins, however when the EAR file is built for that app and deployed to WebSphere the plugins are not found (see following excerpts from system logs):
[9/24/20 13:46:25:565 CDT] 000000e2 SystemOut     O 2020-09-24 13:46:25,565 server.startup : 0 DEBUG PluginManager 'Core' found 122 plugins
...
[9/24/20 13:46:17:734 CDT] 000000e2 SystemOut     O 2020-09-24 13:46:17,733 server.startup : 0 ERROR Appenders contains invalid attributes "CustomAppender1", "CustomAppender2"

Note that when I run unit tests or start the app locally from an IDE, 127 plugins are discovered for Core (this includes my 5 custom plugins).
I would like to try building the .dat file for my JAR with the custom plugins, however I can't seem to find how to do this. I am using Gradle to build my JAR, is there any configuration I need to add so that the .dat file is created for my plugins?
For reference, I'm going off of this answer.
Answer: It ended up being a matter of adding this to my Gradle dependencies:
annotationProcessor('org.apache.logging.log4j:log4j-core:2.13.3')


Vocabulary terms deleted but still visible

Question: I work on a D7 website where some taxonomy terms were created and then deleted.
I've build a search form with views based on taxonomy terms (filter criterion: Content: Term name (field_term_name)) and i see some "deleted" terms in filter exposed to visitor.
I've check directly in DB and it appears that these datas (which should be completely deleted) are still in taxonomy_term_data.
I do not see these terms in the Drupal admin but I can however still see them in the database, and I can open them directly using the tid in the Drupal interface.
My experience with Drupal let me think that is not a good idea to delete them directly in DB. So how can I proceed ?
Answer: taxonomy_term_data is the canonical location for term data so it sounds like there might be other issues going on (a broken admin display, caching, DB corruption via orphaned parent/child term, we can only guess).
If you want a safe way to remove taxonomy, invoke the taxonomy API functions (they are the same tools the admin interface is using) via Devel, drush eval, or some other dev tool where you can execute arbitrary PHP that uses these functions to remove your desired terms:
For example:
$my_bad_tids = [1, 2, 3];
$terms = taxonomy_term_load_multiple($my_bad_tids);
foreach ($terms as $term) {
  taxonomy_term_delete($term->tid);
}


Creating a perfect "practice corner"

Question: Only few of us are lucky enough to have studio or some other dedicated place to practice. I think most of the time, musicians are going through their daily practice routines at home.
I'm thinking of changing a few thing around in my apartment, and came up with a question about designing a dedicated "corner" for practicing music. I think anybody will agree, that an environment around you, can affect effectiveness of your practice time just as much, as the instrument you play, or your practice schedule quality.
For example, I've noticed, that when I play in the kitchen, my acoustic guitar sounds much fuller, because sound is reflected from the tile, as opposed to my usual practice place in the bedroom, where I sit next to a bookshelf, and all the sound gets "sucked in".
I know, the question might sound subjective, but I am looking for solid tips on creating a good place for everyday practice. What should it have, what shouldn't? What is the best place in the apartment? Any tips on the acoustics, isolating and atmosphere related improvements? A picture of your "practice corner" with an explanation would be great.
I play an acoustic and electric guitars, but tips for other kind of instruments are welcome as well.
Comment: I say don't mess with success.  Set up in the kitchen!
Comment: don't set up in the kitchen. Do you really want an aerosol of cooking grease and water vapor settling on your equipment 2-3 times a day?
Comment: Maybe you could set up the practice corner with ceramic tiling...
Comment: I think you've found one of the main points: it's all about the sound. That's what you want, so you should make sure you get it. Motivation is #1, rest follows. :)
Answer: What should it have?-

A place for each guitar. You shouldn't have to move half a dozen other things to reach a guitar.
A table. Personally, I cannot stand having extra things on the floor. These things make a very handy place to put books, instruments, etc while you're using them.
Specified places for extra picks, strings, and other little things. Losing that brand new set of guitar strings behind the pile of books is no fun.
A clock. Keeping track of time is important to being productive.

Location-

Since, you're in an apartment, a corner area of the building or another secluded spot would be preferable. Under, most circumstances, fellow occupants will not be wanting to hear you to all hours of the day (and night).
Another advantage of a secluded spot is that you won't have to hear others' din while you're playing.
Everything should have its own place in the room. However, don't try to keep to much in a small room. A cluttered room makes practicing hard.
Near a faucet. I play wind instruments and I don't like having to go to the other side of the building whenever I need a drink. I don't know if this one applies when playing guitars, though (unless you sing while you're playing).

Acoustics-

If you have a large room, with many furnishings, eg. curtains, shelves, and sofas, it will mute the reverberations somewhat. On the other hand, few furnishings, eg. an unfinished basement, will let the music resound.
No matter how few furnishings are in your room, a small room will always give a muted sound. You know the room's too small when you're playing to a wall whichever way you turn.
If you like the sound of the kitchen, why not 'recreate' the kitchen. Use tiling on the walls and floor. Be creative.

Atmosphere-

A lightly colored room provides a bright, vivid mood.
Likewise, a dark colored room tends to lend itself to a subjected, depressed mood.
More on colors- How colors affect your mood and abilities
Obviously, a well lighted area is desirable for reading music.
In my opinion, daylight is better than artificial light. It gives the area a fuller, less drab appearance and lowers the electric bills. However artificial light is necessary, obviously, on cloudy days.

You should be comfortable with the finished result. If it's distracting, its probably not doing you a favor. You're not going to have the chance to redo the area again anytime soon (most likely). You'll be living with the setup for a while.
Comment: but the OP said he/she likes the sound on the kitchen, reflected by the tiles... I realise your answer has some good tips, but almost seems taken from a text-book (seems more related to building a studio). I was hoping to see some answers dedicated to the OP's particular need.
Comment: About color: Yellow is regarded to be a "creative/inspirational" color, so that would be a good starting point.
Comment: However, in addition to the above mentioned attribute, many sites state "Yellow has been known to be a frustrating color to work in". Orange on other hand, "conveys an air of exhilaration, cheerfulness, and a burst of the creativity. It evokes excitement, enthusiasm and energy."
Answer: A perfect practice area is really quite a personal space, designed around your personal learning style and really around your general psyche as a whole. It is really a reflection of who you are as a music student and your understanding of yourself and your learning needs.
As far as what the best place or area for a specific person in their home, I doubt anyone can really give an accurate answer because, above all else, your practice area has to be tailored to YOU.
What I will say is that your practice area should be an area that promotes relaxation, focus, concentration, physical comfort, and the ability to accurately hear what you are playing.
Relaxation helps to prevent physical tension, which can be harmful to developing a strong technique. Your practice environment should be a place where you feel relaxed or at ease.
Physical comfort is critical, as many of the worst technical habits on any instrument come from playing in an unsuitable physical environment. In other words, make sure you have a comfortable chair at an appropriate height (if you use a chair).
Focus/concentration is necessary to be able to get the greatest benefit out of your practice session. What this means depends on you - if extraneous noise distracts you, find a quiet place to practice. If visual motion distracts you, face away from windows, etc.
Auditory characteristics are important because the sound should be one of the most important indicators of your progress. However, I would personally shy away from practicing in an area that adds acoustic flavor to the music. For example, playing acoustic guitar in a bathroom can sound awesome, but this is partially because the reverb in the bathroom can mask some of the inconsistencies in your playing. To be able to truly critique your own sound while you play, it is better to shoot for an acoustically "dry" area. In addition, record yourself as much as possible for your "post-practice" review.
If there is any main point to my post that you should take away, it is that the only way to truly set up your perfect practice environment is to take the time to understand yourself, and what issues help or hinder your practice.  What works for me may not work at all for you, and vice versa. Understand what you, personally, need from your practice environment and try it out, one thing at a time, until you feel you are truly able to phase everything else out.
One final thing I would suggest for any practice regimen - keep a timer handy. You will progress further and faster if you take regular breaks in your practice. This helps you maintain your mental focus while allowing you a physical rest period. I try to practice for 25 minutes, then rest for 5 - pomodoro style.
Comment: Do see your point on dry acoustic environments but remember watching one documentary where a musician was recommending practice in areas with a lot of resonance because it gives a lot of feedback to the musician and confidence to make a stronger sound.
Answer: I think these other folks made some great points. I would add that you should be careful what you keep in the immediate vicinity of your practice space. Don't keep anything that could be distracting you from what you're there to do. However also make sure to keep anything you use regularly during your practice sessions. Anything I use at least every other session is within arms reach. I do this because if I have to get up to get something from somewhere else, the likelihood of me getting distracted (especially by family) is much higher.
Answer: Generally, a good practice space has the following things:

Isolation. No matter how good you are, if you live with anyone else, they probably do not want to listen to you practice the same lick for 2 hours. Find a space where you can shut a door and not be easily heard by housemates, neighbors, etc. This is more difficult with wind and brass instruments, which are designed to be loud without any amplification, and bass instruments, whose low frequencies are more omnidirectional and more easily transmitted through materials that will absorb higher frequencies. Instruments that are normally amplified like keys, guitar and bass are easiest to isolate; invest in a setup that will allow you to hear the instrument through headphones, optionally with an auxilliary input such as a music track from a CD player or computer.
Comfort/Ergonomics. You want to practice. You will thus want to spend time in your practice space. Ergo, your space should be inviting to you in many ways. Enough room to stretch out or even dance around, nice comfy chairs and furnishings to sit in while practicing, listening, making notes, etc, a few decorations to make it look lived in, and generally good layout to avoid having to contort yourself to make adjustments to something you're using, will all contribute to good practice sessions.
Few or no distractions. You're there to practice, not to fiddle with things. If the space has a window, close the blinds enough that you can't see what's going on outside. If you have recording or other audio equipment, maintain it outside your normal practice time, and make sure it's always ready to turn on and go without a fuss. If the equipment includes a computer, I would try to avoid having games, IM software or even e-mail installed on it. I would also generally recommend not having a phone in the room, but sometimes you just have to have some way for people to contact you. For long sessions, keep some food and drink handy, but avoid succumbing to the munchies during your practice time. The general point is to keep you focused on what you're doing, so you should minimize the number of things you might need to do during your practice time other than practicing.
Acoustic returns comparable to your normal performance space. If you don't isolate the space using headphones, you will need to craft the space for desirable natural acoustics. But you have to be careful; what you want is not necessarily a very lively space where everything you do reverberates and sounds great, but a space that sounds as close as you can get to where you normally perform. A symphony hall has great acoustics, but any returns you get back without a PA system and monitors will be off of a lot of people and cushy chairs, and so it won't have the acoustics of your tiled kitchen or bathroom. In fact for many such spaces you'd be lucky to get anything back. For this reason, an acoustically "dead" space is generally preferred for a combination of isolation and acoustics approaching the average performance space. However, getting the acoustics 100% right is probably the least important aspect of a good practice space, and more often than not the acoustics you'll want is simply a question of "comfort"; being somewhere where you sound good is conducive to you wanting to continue to practice.
Answer: I keep thinking about this question, and I think many of your sub-questions are a matter of personal preference.
How casual or serious is your practice?  Do you already have an established regimen?
For many of us, playing and practicing music is relegated to free time.  I go through periods of not playing any of my guitars at all.  I just went through one such period and started playing again a few weeks ago.
Oddly enough, I had one of my classicals out in the living room on a stand.  I spend a great deal of my free time at my desk at home, which is also in the living room, but out of reach of that classical.  After the first or second day of picking it back up just because I was compelled to for one reason or another, I moved the stand to be within reach of my desk chair.  I've played every day since then, and got my foot rest out a few days ago.
To make a long story interminable, you should set up wherever is most attractive to you.  If you find that place to be the kitchen, that is wonderful.  If you are worried about kitchen detritus, you could keep the guitar in a case in the kitchen rather than on a stand.
As far as what you should have there, others have covered this pretty well.  I do want to suggest that you don't try to make it perfect prior to using it.  Build your space gradually and let it be dynamic.

Creating a perfect "practice corner"


How to learn Jazz Bass Guitar?

Question: I have been learning bass guitar for one year. I have the basic in the major and minor scales. Basically, I am able to figure out the bass line of a song I hear, like pop song or rock song. But, when it comes to the Jazz song, it will be hard for me to figure out the bass line.
So, how to learn jazz music from the basic? And how do I should learn/do first in order for me to get the jazz stuff? And Which scales should I learn first for playing Jazz?
Comment: It is very hard to "fake" jazz bass. Even if it might sound like the bass is merely playing some standard patterns, there's a lot more behind it. The bass also needs to adjust to a soloist for good results. So like the other answers indicate, it will take a lot of theoretical study and practice.
Answer: Full disclosure up front: I'm a guitarist who plays some solo/accompanying gigs, so a proper bass player I ain't. That said, I've doubled on bass on a gig or two, and I've spent a fair amount of time on the theory. The following is basically how I learned to do what I'm able to do.
If you want to get into jazz, I'd say first thing to do is get a good fake book. I like The Real Book a lot myself, and around these parts it's the go-to book for gigs. Everybody shows up carrying one of these. There is a bass clef edition of the book which might come in handy for you, but you're not really in this for the melody. What you want is a book of different chord progressions to practice improvising on, and the treble clef edition will serve that purpose just as well. Just steer clear of Eb or Bb editions, as those are for horn players and they'll land you in strange keys.
I'd also grab some backing tracks (this question asks about jazz piano but my answer applies to you as well). They're a great practice tool.
Once you've got your book and tracks, I'd spend some time tinkering with tunes. Find one that looks a little simpler ("Autumn Leaves" and "Blue Bossa" are great starter tunes, for example) and play! Easy, right?
Okay, I'll elaborate. There are a few main categories of things you'll need to learn.
Rhythm:
There's a lot to learn about rhythm, but if you're trying to learn jazz I'd start with swing type tunes. In those cases, usually, the bass player will be be playing "in two" or "in four". "In two" means playing the first and third beats of the measure. "In four" means playing on each quarter note. Try to wrap your ears around that listening a bit, and try playing the rhythm a bit too, without worrying too much about notes. I like to practice with a metronome set to half my desired tempo, and play as if it's hitting the 2 and 4 (like most jazz drummers will do). Think "One, beep, three, beep, one, beep, three, beep."
The bass player tends to drive the rhythm of a jazz group more even than the drummer, so try to get your ears around that rhythmic feel as best you can.
If you want to grow into fusion- or funk-influenced playing, there are a lot of resources out there that can help you learn about syncopation. I honestly did it more by feel, listening to players I liked and copping their licks. Listen to lots and lots of recordings!
Harmony:
Bass players don't need to know about chords, right? Wrong!
I found that learning to play bass lines was the greatest single thing I could have done for my music theoretical knowledge. Not only do you have to be able to follow "the changes" (that is to say, the chord changes. Following, of course, the appropriate harmonic rhythm), you need to know about chord tones and chord-scale relationships in order to "walk" convincingly.
Start by playing only the root notes of the chords as written. C for Cm, D for Dm7b5, G for G7#5 and so on. If you don't know your way around the fretboard well enough to pick those notes out, that's going to be a bit of a project, but it's a necessary step. There are a great many different resources out there for that, from charts to wacky mnemonic systems to video lessons. Find what works best for you and learn it!
You'll want to learn how to construct chords. Bass players often spend a lot of time bouncing between the 1 and the 5 of a chord (that is, the root of the chord and the note a fifth up from that root). On a normal major or minor chord, that's no problem. But the 5 of a half-diminished chord is flatted! And the 5 of an altered dominant chord might be flatted or sharped. What does that mean?
Chord-scale relationships are also really important. What does a Dm7 imply? Usually the D Dorian mode, and it usually leads to a G7 (usually G Mixolydian), which usually leads to a C major (usually C Ionian). All those are actually modes of the C major scale. These things are important to know, and while they seem incredibly daunting at first, learning them will make quick work of the meatier tunes down the road.
A further note about scales: The bulk of jazz harmony is based on four scales. They are, in roughly descending order of importance, the major scale, the melodic minor scale, the diminished scale, and the whole tone scale. The modes of these scales are also used, so it's important to know those. "D dorian" means the second mode of the C major scale. "G altered" means the seventh mode of the Ab melodic minor scale. And so on and so forth... There are also pentatonic scales, which have only five notes and are generally formed of a subset of one of the above scales or modes. Bebop scales are derived from the above modes but with an extra note stuffed in between a couple of the others as a passing tone. There's also the blues scale, with a similar addition to the minor pentatonic scale. I personally prefer to identify a chord with one of the first four scales, then to make note choices with the latter scales in mind. Your mileage may vary.
Substitutions are also useful to know. Look up and learn what a tritone substitution is. The Tadd Dameron turnaround is a related concept, and very useful. If you're feeling ambitious, try to figure out how Bird changes are related to a twelve-bar blues, or start digging into Coltrane changes.
With regards to harmony, Jamey Aebersold's reference sheets "Jazz Nomenclature" and "The Scale Syllabus" will be good resources for you. I printed copies and kept them handy for years. I'd also highly recommend Mark Levine's "The Jazz Theory Book".
Melody:
Once you've learned a little about the theory behind what notes you can play, you'll have to choose the notes you want to play. Smooth transitions are nice. In the first couple bars of a blues progression, for example, moving from a Bb7 chord to an Eb7 chord, you might transition to the Eb7 from the third of the Bb7 chord, a D. Slide in from a half-step below, like. Or you could jump up to the 5th of the Bb7 chord, an F, and drop in stepwise from above. Or you may want to remain static while the rest of the band moves around you, playing a pedal point. Or you could employ sequencing to give a structured feel to notes that don't actually belong to the chord or key you're playing in at all. The sky's the limit.
Much of this will come from listening, and much of this will come from practice. You're going to make mistakes, and you're going to discover beautiful things.
In Summary:
There's a lot to digest here, I know, but always remember, it's very possible to learn this stuff. People have done it, and will continue to do it for years to come. Listen to and play along with as many recordings as you can. Good traditional bass players to listen to include Charles Mingus, Paul Chambers, or Ray Brown. On electric bass, you can hardly go wrong with the likes of Jaco Pastorius, Stanley Clarke, or Steve Swallow.
Start with simple tunes like "Blue Bossa", "Autumn Leaves", blues tunes like "Straight, No Chaser", "Blue Monk", "Mr. P.C.". Work your way up to some ballads (they're slower, but tend to have more difficult chord changes) like "Body and Soul", "Misty", or "God Bless The Child". If you want to play groovier stuff, think about tunes like "Cantaloupe Island", "Mercy, Mercy, Mercy", and "The Chicken".
And always always follow your ears. If you hear somebody whose sound you like, there's a good chance they played on a whole bunch of albums. Ron Carter, for example, has appeared on over 2,500 albums. Listen, try to play along when you can, try to understand what they're doing.
Answer: Your question is not very well-formed, but try this:  in many forms of jazz, it's up to the bassist to  both maintain a rhythm and support the chord progression.  To do so, he must select notes which anchor (or float, some of the time) the chords in play.
In fact, a rock bassist does pretty much the same thing, but in a more confined environment so far as note selection goes.
Overall, to learn jazz bass, you'll have to learn a decent amount of music theory.
Answer: This is pretty wide, but here are some tips:

What you need to note about jazz bass guitar is that the bass isn't
   a riff like it is in rock/pop music.
The jazz bass guitar is called "Walking Bass" and it (usually) is
improvisation.
Apart from scales you'll have to learn modes as well, as many jazz
songs are modal.
You will need to learn really good music theory. This will help you understand why the chord progression is the way it is and the same with the melody. You will need to understand those in order to improvise and sound like you know what you are doing.
Also note that usually the Walking Bass is quarters (quite simple rhythmic, but really complex musically)

Here is a good example of Walking Bass:

How to learn Jazz Bass Guitar?