maior/menor em vetores

Question: Fiz algumas modificações mo meu codigo, ele se apresenta em modificações no fim do post la irei modificar quando achar necessario.
olá, estou fazendo um exercicio da faculdade, ele é bem simples, porem, estou tendo certa dificuldade nele, o exercicio pede para escrever dois vetores de 5 possições e imprimir um vetor resultante ordenando os elementos em ordem decrescente (elementos são do tipo int), abaixo o codigo:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int vet1[5], vet2[5], rvet[10];
    int i, j, k, n1=0, n2=0;

    for(i=0; i<=4; i++)//Lê o vet1
    {

        printf("Digite para posicao %d do vet1:\n", n1++);
        scanf("%i", &vet1[i]);
    }

    printf("Obrigado, agora:\n");

    for(j=0; j<=4; j++)//Lê vet2
    {
        printf("Digite para posicao %d do vet2:\n", n2++);
        scanf("%d", &vet2[j]);

    }

    i=0;
    j=0;
    for(k=0;k<=9;k++)//Ordena os vetores
    {
        rvet[k]=i>j ? vet1[i++] : vet2[j++];

            printf("vet[%d]:%d\n", k, rvet[k]);
    }

    return 0;
}

minha maior dificuldade é no for da linha 28(ou o 3º for), não consigo pensar em um algoritmo melhor, então postei uma impressão que alinha primeiro o vet2 e depois o vet1.
Eu estava pensando em fazer menor e maior porem quando eu modifico o algoritmo ele sempre perde os dados guardado no vetor 1 e 2 e ai aparece outros numeros aleatorios.
se alguem puder me ajudar obrigado... meu programa não tem errors e nem warning testei no code::blocks e no dev C++
MODIFICAÇÕES:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int vet1[5], vet2[5], rvet[10];
    int i, j, k, x, y, n1=0, n2=0, aux=0;

    for(i=0; i<=4; i++)//Lê o vet1
    {

        printf("Digite para posicao %d do vet1:\n", n1++);
        scanf("%i", &vet1[i]);
    }

    fflush(stdin);
    system("cls");
    printf("Obrigado, agora:\n");

    for(j=0; j<=4; j++)//Lê vet2
    {
        printf("Digite para posicao %d do vet2:\n", n2++);
        scanf("%d", &vet2[j]);

    }

    fflush(stdin);
    system("cls");

    for(k=0; k<=4; k++)//preenche as 5 primeiras possições com vet1;
    {
            rvet[k]=vet1[i++];
    }

    for(k=5; k<=9; k++)
    {
        rvet[k]=vet2[j++];
    }

    for(y=0; y<=9; y++)//coloca em ordem decrescente
    {
        for(k=x+1; k<=9; k++)
        {
            if(rvet[k]<rvet[x])
            {
                aux=rvet[x];
                rvet[x]=rvet[y];
                rvet[y]=aux;
            }
        }
    }

    for(k=0; k<=9; k++)
    {
        printf("%d->%d\n", k, rvet[k]);
    }

    return 0;
}

aqui eles imprime primeiro o vet1 e depois o vet2.
Comment: Você quer que o rvet, fique ordenado de forma decrescente?
Comment: isso mesmo diego
Answer: Para isso, creio que a forma mais eficiente seria criar um terceiro vetor com tamanho 10, inserir os valores dos 2 vetores anteriores neste terceiro, e então realizar a ordenação.
Para isso:
#include <stdio.h>
#include <stdlib.h>

int main()
{
int vet1[5], vet2[5], rvet[10], n1=0, n2=0, aux=0;

for(int i=0; i<=4; i++) //Lê o vet1
{

    printf("Digite para posicao %d do vet1:\n", n1++);
    scanf("%i", &vet1[i]);
}

printf("Obrigado, agora:\n");

for(int j=0; j<=4; j++)//Lê vet2
{
    printf("Digite para posicao %d do vet2:\n", n2++);
    scanf("%d", &vet2[j]);

}

//intercalando os vetores aqui
for(int k=0; k<=4; k++)
{
rvet[k] = vet1[k]; //preenche as primeiras 5 posições
}

for(int k=5; k<=9; k++)
{
rvet[k] = vet2[k-5]; //preenche as próximas 5.
}

//Ordenação bubble sort
 for(int x = 0; x <= 9; x++ )
 {
   for(int y = x + 1; y <= 9; y++ ) // sempre 1 elemento à frente
    {
     // se o x for menor que a próxima posição do vetor, o x passa pra frente (ordem decrescente)
     if (rvet[x] < rvet[y] )
     {
      aux = rvet[x];
      rvet[x] = rvet[y];
      rvet[y] = aux;
     }
    }
  } // fim da ordenação
printf("*** VETOR ORDENADO ***\n");

for(int i=0; i<=9; i++)
{
  printf("%d\n", rvet[i]);
}

return 0;
}

Dica: quando for utilizar uma variável somente para percorrer o for, declare-a desta forma for(int var=0; var<=x; var++). Assim, quando o loop acaba, a variável deixa de existir, ou seja, não é necessário atribuir 0 à mesma.
@LeonardoV.DeGasperin nas últimas alterações feitas percebi os seguintes erros no seu código:
1 - Os vetores vet1 e vet2 foram preenchidos nos índices: 0, 1, 2, 3 e 4 (5 índices, lembrando que o 0 também conta). Você zerou as variáveis i e j, e depois começou a percorrer o vetor assim: vet1[i++], lembrando que se i começa com 0, i++ automaticamente será 1, ignorando o índice 0. Desta forma, você passa pelos índices: 1, 2, 3, 4 e 5, sendo que no índice 5 não há nada. Olhe para o código que postei acima na parte que intercalo os vetores e perceberá a diferença.
2 - Depois que você preencher o vetor rvet[] não basta fazer um if para ordená-lo. A partir daqui, esqueça os vetores vet1[] e vet2[]. Para ordenar e exibir em ordem decrescente, e necessário percorrer todo o vetor rvet[] e organizar os números que estão dentro dele, e algo que auxilia nessa tarefa é um algoritmo chamado algoritmo de ordenação. Sem o uso deste algoritmo, dificulta-se a ordenação. O que utilizei no meu código (e creio que seja o mais simples de compreender) é o bubble sort, mas depois recomendo a você pesquisar sobre os outros também, é interessante.
Aqui você pode consultar o que eu utilizei para fazer essa ordenação..
3 - Por último, para imprimir todo o vetor ordenado de uma vez, e necessário criar outro for, como consta no código acima.
Qualquer dúvida, não hesite em perguntar. Abraço!
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/16283/discussion-between-victor-alencar-santos-and-leonardo-v-de-gasperin).
Comment: hmm irei ver, só fazendo um adendo apos o j=0; nao necessita declarar rvet[10] pois ele ja foi declarado, mas obrigado se der certo irei marcar a sua resposta =) caso contrario irei add outro comentario falando sobre os erros que acontece obrigado.
Comment: @Vitor, o seu programa intercala, mas não ordena o vetor como o OP pediu.
Comment: @Kyllopardium Obrigado pela observaçao, já alterei.
Comment: @kyllopardium eu fiz algumas alterações no post coloquei modificação abaixo dele um codigo novo porem com problema eu ainda to tendo complicações com ele caso algum dos dois puderem me ajudar, o problema conciste ainda em se os elementos do vetX for maiores q os elementos do vetY ira imprimir primeiro o vetorX na ordem dele e a seguir idem com o vetY
Comment: @VictorAlencarSantos o comentario a cima leia caso puder =) obrigado
Comment: @LeonardoV.DeGasperin consulte a resposta, alterei algums coisas
Comment: @LeonardoV.DeGasperin, olhe na linha que coloquei o comentário e faça a alteração que sugeri lá.
Comment: então @VictorAlencarSantos eu fiz aqui ta igual o seu porem ele imprime o vet1 na ordem do vet1 e depois o vet2 na ordem do vet2, e nao ordena os numeros, mas obrigado eu vou postar o codigo novo na area notificações do meu post caso queira dar uma olhada
Comment: @LeonardoV.DeGasperin amigo, seu código editado ainda está incorreto. Tente copiar todo o código que postei acima e colar na sua aplicação e rodar.
Comment: @VictorAlencarSantos quando compilei levei um susto tinha 14 erros, mas era a declarações das variaveis dos loop dos `for` ai modifiquei a declaração e funcionou, obrigado vou estudar o codigo que você fez e tentar fazer um sozinho
Comment: @LeonardoV.DeGasperin Por nada! Alguns compiladores como o Dev C++ não são tão 'amigáveis' com variáveis declaradas dentro de loops, mas é uma ótima prática para casos como este, pois economiza espaço em memória.
Comment: @VictorAlencarSantos essa parte eu nao intendi muito bem `aux = rvet[x];
      rvet[x] = rvet[y];
      rvet[y] = aux; `
Comment: @LeonardoV.DeGasperin o chat não vai funcionar pra mim, então:

Esta parte é onde organizamos os números dentro do vetor. Se  o valor contido na posição atual (`rvet[x]`) for menor que o valor contido na próxima posição (`rvet[y]`), o maior valor passa para cima. Este trecho de código apenas está mostrando que caso o número maior esteja vindo depois, ele passa a vir antes.

[este artigo](http://blogdecodigo.wordpress.com/2011/11/08/bubble-sort-de-um-jeito-bem-diferente-video/) tem uma explicação bem clara sobre isso.
Comment: @VictorAlencarSantos muito obrigado
Answer: Você não fez nada com o i e com o j no seu último for e repare que mesmo que estivesse o que acredito que estava pensando em fazer estaria errado:
v1 : {2,5,20}  v2: {44,34,23}
v1[i]>v2[j]  => vres = [v2[j++]]

o problema é que como os vetores v1 e v2 não estão ordenados, eles vão ter resultados inesperados principalmente se o valor do lixo da memória for ainda inferior a um dos valores usados.
Dicas quanto ao código:
Use #define para não ter que escrever os valores em todos os lugares (fica bem mais fácil para modificar posteriormente).
faça a ordenacão após concatenar os dois vetores.
#include <stdio.h>
#include <stdlib.h>
#define MAXVETOR 5
#define MAXRESULTADO MAXVETOR*2

void ordena(int* vetor , int tamanho){
int c,d,swap;
for (c = 0 ; c < ( tamanho - 1 ); c++)
  {
    for (d = c ; d < tamanho - c - 1; d++)
    {
      if (vetor[d] > vetor[d+1]) //Troque de > para < para alterar a forma de ordenação.
      {
        swap       = vetor[d];
        vetor[d]   = vetor[d+1];
        vetor[d+1] = swap;
      }
    }
  }
}
void imprime_vetor(int *vetor,int tamanho){
    int i=0;
    printf("[");
    for(;i<tamanho;i++){
        if(i==tamanho-1){
            printf("%d]",vetor[i]);
        }
        else{
            printf("%d,",vetor[i]);
        }
    }
}

int main()
{
    int vet1[MAXVETOR] = {1,4,28,34,2}, vet2[MAXVETOR]={99,23,6,3,7}, rvet[MAXRESULTADO];
    int i, j, k, n1=0, n2=0;

/*
    for(i=0; i<MAXVETOR; i++)//Lê o vet1
    {

        printf("Digite para posicao %d do vet1:\n", n1++);
        scanf("%i", &vet1[i]);
    }

    printf("Obrigado, agora:\n");

    for(j=0; j<MAXVETOR; j++)//Lê vet2
    {
        printf("Digite para posicao %d do vet2:\n", n2++);
        scanf("%d", &vet2[j]);

    }
*/
    i=0;
    j=0;
    for(k=0;k<MAXRESULTADO;k++)//Intercala os vetores
    {
        rvet[k] = vet1[k];
    }
    for(k=MAXVETOR;k<MAXRESULTADO;k++)//Intercala os vetores
    {
        rvet[k] = vet2[k-MAXVETOR];
    }
    ordena(rvet,MAXRESULTADO);
    imprime_vetor(rvet,MAXRESULTADO);
    return 0;
}

maior/menor em vetores


as a domain member, 'run with administrative privileges' always asks for hostname

Question: Since we run Windows 7-clients in our windows-server domain I have a specific use case that has become more inconvenient:
On the client-site, being logged-on as an user with restricted rights and having the user account control (UAC) activated on the highest level, you can run an application with administrative privileges by right-clicking onto it and choosing "Run as administrator".
After that, a popup window is shown and asks for the username and password.
As a domain member you now have to enter your full hostname with a backslash following and the user name with administrative privileges (e.g. Administrator) in order to authenticate as local administrator.
On XP-machines you simply had to type in "Administrator" for the username.
That makes administration more inconvenient if you run various Windows-7 clients in a company, because you always have to lookup the hostname for the machine on which you want to run something with administrative privileges.
Is there a registry setting or a good workaround that lets you authenticate as administrator without having to enter the hostname for the machine, but not using tools like "RunAsSPC" or "Steel RunAs"?
Comment: This isn't really an answer to your question, but rather an alternative. In a domain, I would typically not use a local account for administration, but instead a domain account that has administrative rights over the computer.
Comment: sure, but I can not use a shared domain account (which could be in the local group of administrators), because every machine's administrator password shall be different from the other's
Comment: The way I've always seen it done is you create a domain group called "computer admins" or whatever, put all of the accounts that need to administer computers in it, then that domain group goes into the local admin group on each computer via group policy/etc.
Comment: that would be fine. but if I would do it by using domain groups, every member in that group could administrate every computer having it added to the local admin group.  The sense behind "every machine's administrator password shall be different from the other's" is not to allow everybody to administrate each employees machine
Answer: I put the same question on SuperUser.com and I got an answer:

When you want to authenticate to the local computer, you can use a dot instead of the hostname. This doesn't make the issue go away entirely, but at least it prevents you from having to look up hostnames since . works everywhere.
Username: .\Administrator
Password: * * * * * * *
In certain contexts, localhost will work instead. I haven't yet found a situation where either . or localhost doesn't work, but I'm sure there is one somewhere.

Stephen Jennings


REGEX URL regular expression

Question:
Possible Duplicate:
Regular expression for browser Url

Is this regex perfect for any url ?
preg_match_all(
 '/([www]+(\.|dot))?[a-zA-Z0-9_\.-]+(\.|dot){1,}[com|net|org|info\.]+((\.|dot){0,}[a-zA-Z]){0,}+/i',
 $url, $regp);

Comment: `[www]` is not what you think it is. Read about [character classes](http://www.regular-expressions.info/charclass.html)
Comment: Did you write that by yourself? And what do you mean by any URL?
Comment: `museum` is a valid top level domain name like `com`, `net` etc
Comment: Underscore `_` is not a valid character in domain names.
Comment: `[a-z0-9.-]+` matches `-a...com.` among other things
Comment: this regex is not even close to perfect, its highly flawed. look at my post for a valid regex.
Comment: What's up with `{1,}` and `{0,}` quantifiers? Why are you using capital-case ranges with `i` flag? It's just sheer non-sense.
Comment: @SilentGhost: The flag for case insensitive matching does not just affect character classes but also literal characters. In this case `dot` will also match `dOt`, `DOT`, etc.
Comment: @Gumbo: yeah, I don't understand why there is `dot` in there to begin with. But surely `A-Z` in the character classes is excessive.
Comment: I get the feeling this is for scraping pages where people have tried to slightly obscure the web address by typing `w w w  dot wobble dot comm` rather than a well formed URL
Answer: Don't use regex for that. If you cant resist, a valid one can be found here:
What is the best regular expression to check if a string is a valid URL?
but that regex is ridiculous. Try to use your framework for that, if you can (Uri class in .net for example).
Answer: No. In fact it doesn't match URLs at all. It's trying to detect hostnames written in text, like www.example.com.
Its approach is to try to detect some common known TLDs, but:
[com|net|org|info\.]+

is actually a character group, allowing any sequence of characters from the list |.comnetrgif. Probably this was meant:
((com|net|org|info)\.)+

and also [www] is similarly wrong, plus the business with dot doesn't really make any sense.
But this is in general a really bad idea. There are way more TLDs in common use than just those and the 2-letter CCTLDs. Also many/most of the CCTLDs don't have a second-level domain of com/net/org/info. This expression will fail to match those, and will match a bunch of other stuff that's not supposed to be a hostname.
In fact the task of detecting hostnames is basically impossible to do, since a single word can be a hostname, as can any dot-separated sequence of words. (And since internationalised domain names were introduced, almost anything can be a hostname, eg. 例え.テスト.)
Comment: An IP address is also a valid host: `http://127.0.0.1/` is a valid absolute URL.
Comment: ...not to mention IPv6 addresses! Trying to match hostnames/IP addresses in text is never going to be reliable.
Answer: 'any' url is a tough call.  In OZ you have .com.au, in the UK it is .co.uk Each country has its own set of rules, and they can change.  .xxx has just been approved. And non-ascii characters have been approved now, but I suspect you don't need that.
I would wonder why you want validation which is that tight?  Many urls that are right will be excluded, and it does not exlude all incorrect urls.  www.thisisnotavalidurl.com would still be accepted.
I would suggest
A) using a looser check , just for ([a-zA-Z0-9_.-].)*[a-zA-Z0-9_.-] (or somthing), just as a sanity check
B) using a reverse lookup to check if the URL is actually valid if you want to only allow actual real urls.
Oh, and I find this: http://www.fileformat.info/tool/regex.htm  to be a really useful tool if I am developing regex, which I am not great at.
Comment: Can i have and .com URL that can bypass this regex ?
Comment: can I have any .com url that can by pass this REGEX preg_match_all(
 '/([www]+(\.|dot))?[a-zA-Z0-9_\.-]+(\.|dot){1,}[com|net|org|info\.]+((\.|dot){0,}[a-zA-Z]){0,}+/i',
 $url, $regp);
Answer: [www]+ should be changed for (www)?
(\.|dot){1,} - one and more? mayby you wanted to do ([a-zA-Z0-9_\.-]+(\.|dot)){1,}
Answer: A URL also has a protocol like http, which you're missing. You're also missing a lot of TLDs, as already mentioned.
Something like an escaped space (%20) would also not be recognized.
Port numbers can also appear in an URL (e.g. :80)
Comment: A URL can also be relative. Even an empty string is a valid URL.
Comment: Depending on how pedantic you want to be, a relative *URI* doesn't class as a *URL*.
Comment: @bobince: It all depends on what specifications your terms are derived from: RFC 1808 states *URL* to be the most common term of a resource locator while RFC 3986 uses the term *URI-reference*.
Answer: No, and you can't create a REGEX that will parse any URI (or URL or URN) - the only way to parse them properly is to read them as per the spec of RFC-3986

REGEX URL regular expression


Ebean missing from Play 2 Module for Java

Question: I created a new project in IntelliJ 13 using the Play 2 Module for Java project template and noticed that the # Ebean configuration is missing from conf/application.conf.
Being new to both Play Framework and IntelliJ I tried following the Play introductory video and got stuck where I need to extend the Ebean Model class. The problem is that the class doesn't appear in the Import class dialogue.
I've tried adding the source directory to these files to File → Project Structure → Libraries but that didn't work.
If import play.db.ebean.Model; is added IntelliJ complains with cannot resolve symbol 'db'.
What do I need to do to have my project include the Play Ebean classes?
Answer: The method to enable ebean support has changed in play framework. Now it is done using an external dependency. From the documentation:
To enable it, add the Play Ebean plugin to your SBT plugins in project/plugins.sbt:
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0")

And then modify your build.sbt to enable the Play Ebean plugin:
lazy val myProject = (project in file("."))
  .enablePlugins(PlayJava, PlayEbean)

Comment: This is described in the migration guide for Play 2.4 https://playframework.com/documentation/2.4.x/Migration24
Answer: Inside the build.sbt file make sure "javaEbean" is listed like the following:
libraryDependencies ++= Seq(
  javaJdbc,
  javaEbean
}

Then, run "play clean compile" and "play idea" consecutively.
Comment: Thank you! Could you please assits, where I can read information about build.sbt and what should be in it?


Busca de maior data por um ID especifico

Question: Estou com um problema em uma SQL onde necessito buscar a maior data de um ID especifico, onde tem vários registros deste mesmo ID:
Dados:

ID - data - nome
2 - 10/10/2004 - cesar  5 - 10/10/2008 - joana  4 - 10/10/2002
  - maria  1 - 04/01/2017 - paulo  1 - 12/12/2017 - paulo  4 - 10/10/2000 - maria  5 - 10/10/2017 - joana

Neste exemplo gostaria de buscar o ID = 1 que corresponde ao nome paulo e necessito da maior data em especifico, a seguir segui minha SQL onde busco a maior data, mas o nome vem outro e não do ID referente.
SELECT MAX(data) as data, nome FROM teste WHERE id = '1'

Resultado ... 1 - 12/12/2017 - cesar
Esperado  ... 1 - 12/12/2017 - paulo

ou seja, percebi que me retorna o primeiro nome do Banco, e não é o que necessito.
Comment: tentou agrupar? algo assim: `SELECT MAX(data) as data, nome FROM teste WHERE id = 1 group by id`
Comment: sim, ae traz todos com ID 1
Comment: Faz ao contrário, primeiro vai buscar todos os registo com id = 1 e depois vê qual desses é o maior
Answer: Voce pode resolver tudo com apenas uma consulta fazendo:
SELECT data, nome FROM teste WHERE id = '1' order by data desc limit 1;

Answer: Você pode resolver isso fazendo primeiro a query ordenando pela data depois outra query limitando a 1.
CREATE TABLE `teste` (
  `id` int(11) NOT NULL,
  `data` datetime DEFAULT NULL,
  `nome` varchar(25) DEFAULT NULL
)

INSERT INTO testeVALUES('2','2004-10-10','cesar'),('5','2008-10-10','joana'),
('4','2002-10-10','maria'),('1','2017-01-04','paulo'),('1','2017-12-12','paulo'),
('4','2000-10-10','maria'),('5','2017-10-10','joana');

SELECT
    aux.*
FROM(
SELECT
    data as `data`,
    nome
FROM teste WHERE id = '1'
ORDER BY `data` DESC
) AS aux
LIMIT 1
;

Comment: Não funfa a query: MSG mysql ( cada tabela derivada deve ter seu proprio alias  )
Comment: coloquei um alias -> as resultado ..... e exibe o mesmo resultado 1 - 12/12/2017 - cesar
Comment: Ops, desculpa, faltaram algumas coisas ali, vou editar, eu tinha deixado o MAX sem quere, ai o resultado era o mesmo.
Comment: @ThiagoLopez, se quiser testar agora!
Comment: Não houve mudança :/
Comment: Adicina um um DESC depois do ORDER BY data, ali
Comment: Nada amigo, continua retornando a data correta, porem o nome é o primeiro da tabela !!
Comment: Sinceramente, inseri os mesmos dados na tabela, que você passou, executei a query e o resultado veio correto
Comment: aqui nao ta funfando !
Comment: Na verdade, agora que reparei direito .... esta vindo o primeiro registro da taela, nem esta pegando a maior data !!
Comment: alguem ae faz um teste por favor .... não tem como uma query ter dois coportamentos em pcs diferentes.
Answer: Após muita pesquisa encontrei a solução do meu problema e vou repassar a solução !!

SELECT * FROM teste WHERE data = ( SELECT max(data) FROM teste WHERE
  id = 1 )

Obrigado a todos pela cooperação.


How to get total number of results in Search API View?

Question: How can I get the total number of results on a Search API View that has a limit of 5 results to display?
Some more info:
I have to make a bit more complex search where several attachments are combined on a page as a groups of results. Every group should show just the first 5 results, but also a link "see all XX results". I'm using Search API + Solr, Views with exposed fulltext search.
If I use "Global: Results summary" in header or footer, it will show maximum the limit of 5 as a number.
edit 1
Search API Solr returns 'numFound' which is what I need, but how do I use it in Views?
Comment: I don't know if it will work on groups or totals like the Global, but you could look at Views Calc module (https://www.drupal.org/project/views_calc)
Comment: Unfortunately, Views Calc cannot do the job.
Comment: Couldn't this be done with the "Pager" option?
Comment: @Beebee Unfortunately no, as this is already an attachment and it doesn't allow its own pager.
Answer: So after a day, here's the result:
As J. Reynolds suggested, I finished up using $view->total_rows, but:

To populate $views->total_rows, you have to use a pager in your view - that was not an option with the attachments.
If you don't use a pager, you could force populating $view->total_rows by altering the View query before its execution like this:

    function mycustommodule_views_pre_execute(&$view) {
      $view->get_total_rows = TRUE;
    }

And after that you have that $view->total_rows!
Answer: Try with this type of code. You can select either attachment_before or attachment_after, and if the placement is not to your liking you may alter the views template to suit. I know this works with a normal view and I don't see why it would not work with a Search API result. And I think you can place it in a theme's template.php file if you prefer rather than a module.
function MYMODULE_views_post_execute(&$view){
    if ($view->name == "MACHINENAME_OF_VIEW") { // can slso check for display if need be
        $view->attachment_before .=
$view->total_rows

    }
}

Comment: Thanks for the suggestion, but $view->total_rows appears to be empty :(
Answer: By configure  Views Global result summary  in header or Footer, we can display Total number of results.
Search with result summary in Header and pass the tokens,
@start -- the initial record number in the set
@end -- the last record number in the set
@total -- the total records in the set
@label -- the human-readable name of the view
@per_page -- the number of items per page
@current_page -- the current page number
@current_record_count -- the current page record count
@page_count -- the total page count


Download Amazon-RDS (SQL-Server) Backup or Snapshot

Question: I want to download one of my backups and restore it on my laptop for testing a web app locally.  I'm using SQL Express.
This is similar to this MySQL question. Can I just run a backup using T-SQL? And then somehow direct it to S3?
Comment: One-command-answer here: https://serverfault.com/questions/302680/how-to-create-a-local-backup-of-a-remote-amazon-rds-mysql-database
Answer: This is super easy to do if you follow the steps Importing and Exporting SQL Server Databases
Key steps being:

Create S3 bucket
Create options group with IAM Role to that bucket, being sure to select the "SQL_SERVER_BACKUP_RESTORE" option.
Assign options group to the RDS instance

Go to RDS dashboard showing your instances.
Click your RDS instance to view the details screen.
Click the Modify button in the top right.
Scroll way down to "Database options" -> "Options group"
Select your newly created option group that has the backup & restore option.
Save / Continue. It may take several minutes for this change to take effect, even if you select to apply it immediately. I personally did not experience downtime, YMMV.

Run the backup script:

exec msdb.dbo.rds_backup_database
     @source_db_name='database_name',
     @s3_arn_to_backup_to='arn:aws:s3:::bucket_name/file_name_and_extension',
     @overwrite_S3_backup_file=1;

That script will return to you a task #. You can use the following script to track the progress:
exec msdb..rds_task_status @task_id= <your task #>

Once you've done that then you can download the .bak file and restore locally (assuming same sql server versions running, etc)
Comment: That is not super easy. Super easy would be clicking a download button somewhere.
Comment: Thanks, I will when I can, and come back and mark answer.
So the above is to be run in SSMS? Not Windows command line, right?
They made their own backup stored proc?
Comment: Yes, that is correct


Unable to access the phpmyadmin on xamp server

Question: occurred: Tried to change the privilege on database.
issue one : i don't know what i did on Privilege window after that i con't able to  run mysql on xamp so i tried to find a solution on internet so got the solution is if i replace\copy the files form "xampp\mysql\backup" to 'xampp\mysql\data" folder it will resolve so i did same and now i am able to run a mysql on xamp but now i con't access the "http://localhost/myphpadmin.php" page.
enter image description here
Comment: sounds like your mysqld is not running.
Answer: I don't know anything about what's in your xampp\mysql\backup folder, but moving anything around in the MySQL datadir (your xampp\mysql\data) while the server daemon/service is running is going to cause you trouble. The MySQL server uses various files in there while it's running and even moving around folders within that folder (such as trying to copy a database from one system to another) won't work properly because (generally) all the files and folders are related (such as the ibdata1 file, which is sort of the glue that holds together all of your databases and users).
It's pretty unclear what's going on. From the error message, for some reason MySQL rejected the connection. Perhaps your user accounts were corrupted when you copied the folder. Perhaps you changed your user's permissions and now can't log in because the user doesn't have proper permissions or the password is changed. In particular, the "Invalid settings" error suggests that there could be a problem in your phpMyAdmin configuration file, config.inc.php that is improper. Have you made any chances to that since you were able to log in?
You could try to reset the permissions and, once you have access, repair the damage to your other user accounts. If you would be so kind as to tell me your operating system, I'll paste the relevant directions here; the page is rather long to paste the entire contents here.
In addition to your main user not being able to log in, phpMyAdmin has an optional secondary user that is used for administrative tasks to enable advanced features, such as bookmarking queries, hiding databases or tables, and managing user groups. That user is called the controluser, and that account isn't able to log in, either. Once you regain control, you can either recreate that user (you can find the full directions at https://docs.phpmyadmin.net/en/latest/setup.html#manual-configuration but because the Stack Exchange network likes to have all the information here, I'm going to copy and paste the commands below). You could also disable the controluser, if you edit config.inc.php you can comment out or remove the two lines for $cfg['Servers'][$i]['controluser'] and $cfg['Servers'][$i]['controlpass'].
To create the phpMyAdmin control user:
For any MariaDB version:
CREATE USER 'pma'@'localhost' IDENTIFIED VIA mysql_native_password USING 'pmapass';
GRANT SELECT, INSERT, UPDATE, DELETE ON `<pma_db>`.* TO 'pma'@'localhost';

For MySQL 8.0 and newer:
CREATE USER 'pma'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'pmapass';
GRANT SELECT, INSERT, UPDATE, DELETE ON <pma_db>.* TO 'pma'@'localhost';

For MySQL older than 8.0:
CREATE USER 'pma'@'localhost' IDENTIFIED WITH mysql_native_password AS 'pmapass';
GRANT SELECT, INSERT, UPDATE, DELETE ON <pma_db>.* TO 'pma'@'localhost';

Note that MySQL installations with PHP older than 7.4 and MySQL newer than 8.0 may require using the mysql_native_password authentication as a workaround.


If $X$ is independent of $Y$ and $Y$ is independent of $Z$, is $X$ independent of $Z$?

Question: If $X$ is independent of $Y$ and $Y$ is independent of $Z$, is $X$ independent of $Z$? In other words, is independence transitive?
Comment: FAQ.  For much more on this, [here is a focused site search](https://stats.stackexchange.com/search?q=dependent+independent+-sample+-regression+prob*+-disjoint).
Answer: No. in the extreme case, take for exammple $X=Z$.
Answer: You may also think about real life example:

$X$ - You find a lottery ticket on the street
$Y$ - You flip a coin and get a head
$Z$ - You win the lottery.

$X$, $Y$ and $Y$, $Z$ are independent, but lottery ticket for sure help you to win some extra cash.


Data frame subset according to matching values in R

Question: I have a data.frame with information on racing performance on horses. I have a variable Competition.year that has a "Total" row and then a row for each year the horse competed. I also have a variable Competition.age that describes the age the horses were in each specific year they competed.
I am trying to create a subsetted df based on their best racing times and the age they were when they achieved it. In the "Total" row, the racing time included is their best one. So, I need to figure out how to tell R that, when the race time in Total row is equal to whenever it is they actually achieved that time, include the age they were then in the new data frame. I am super new to R so I have no idea where to even begin doing this, I've tried some stuff I've seen on other questions but I can't get it right. Any help would be much appreciated!
My df looks like this:
travdata <- data.frame(
"Name"=c(rep("Muuttuva",3),rep("Pelson Poika",7),rep("Muusan Muisto",4)),
"Competition.year" = c("Total",2005,2004,"Total",2003,2004,2006,2005,2002,2001,2008,2010,"Total",2009),
"Time.record.auto.start"=c(93.5,NA,93.5,96.5,NA,NA,104.2,96.5,NA,96.6,NA,NA,NA,NA),
"Time.record.volt.start"=c(92.5,98.4,92.5,94.3,NA,105.3,98.3,94.3,102.1,99.1,107.5,NA,107.5,NA),
"Competition.age"=c(NA,6,7,NA,4,5,6,7,8,9,NA,5,6,7))

The desired df should have 223 rows (since that is the total amount of horses I have) with columns Name, Competition.year=="Total", Time.record.auto.start, Time.record.volt.start and Competition.age
Comment: please make a minimal example to visualize your problem. With example and desired outcome.
Comment: Your example data frame is problematic. There sims to be 15 observations in the `Competition.age` column, while all the other columns have 14 observations. Please fix that.
Comment: Possible duplicate of [Inner Join with conditions in R](https://stackoverflow.com/questions/31179805/inner-join-with-conditions-in-r)
Comment: I corrected everything now based on the answer @meenaparam gave me, sorry for the trouble! I've only started writing code and working with statistics so I'm very green :)
Answer: Firstly, I had to change your sample data to make sure all 5 variables only had 14 observations each. I did this by removing the final NA in the Competition.age variable. I also had to swap around the 94.3 and 98.3 values in the Time.record.volt.start variable so that the values lined up with what was expected in the Total column for the horse with Name equal to Pelson Poika.
Here is the corrected data:
travdata <- data.frame(
"Name"=c(rep("Muuttuva",3),rep("Pelson Poika",7),rep("Muusan Muisto",4)),
"Competition.year" = c("Total",2005,2004,"Total",2003,2004,2006,2005,2002,2001,2008,2010,"Total",2009),
"Time.record.auto.start"=c(93.5,NA,93.5,96.5,NA,NA,104.2,96.5,NA,96.6,NA,NA,NA,NA),
"Time.record.volt.start"=c(92.5,98.4,92.5,94.3,NA,105.3,98.3,94.3,102.1,99.1,107.5,NA,107.5,NA),
"Competition.age"=c(NA,6,7,NA,4,5,6,7,8,9,NA,5,6,7))

And here is a simple dplyr solution, which I think does what you want.
library(dplyr)
df1 <-
    travdata %>% group_by(Name) %>% filter(Competition.year == "Total") %>% select(Name, Time.record.auto.start, Time.record.volt.start)
df2 <- travdata %>% filter(Competition.year != "Total")
df3 <-
    inner_join(
        df1,
        df2,
        by = c(
            "Name" = "Name",
            "Time.record.auto.start" = "Time.record.auto.start",
            "Time.record.volt.start" = "Time.record.volt.start"
        )
    )

The dataframe df3 should return what you were after.
Comment: Hey! Thanks a lot for the answer and sorry about the faulty writing of the `df`, I'm a super noob in this world of statistics and code writing. If I correctly understood what you did, now in  `df3`, `Competition.year` tells me the year they achieved their best time and matches it with the age they were, right? :)
Comment: @LauraBas No problem, and yes, the `Competition.year` column in `df3` shows the year that was in that horse's `Total` row. Note that the third horse didn't have any age data for the year that they did their best race in. If this happens frequently in your data, we might be able to figure out a way to manually calculate the age of best race by using another year that does have the age in it.
Comment: Hey! The only reason that ocurred I think is because of how I wrote the `data.frame` example; when I applied it to my complete data it worked perfectly. I've calculated a bunch of different age variables using the `eeptols` package based on different conditions and they all work fine. I just needed to have an idea of at which age they usually achieve their best times and I got that now. Thanks again!!


Multilevel joint analysis of binary outcomes or Binary GEE?

Question: I have repeated measures of systolic blood pressure for approximately 200 different kidney donors, taken at random times from nurses in the withdrawal from treatment to death period (which generally doesn't last longer than 4 hours). This has led to highly unbalanced and unequally spaced data. There is a minimum of 2, maximum of 50 and mean of 13 repeated measures.
I want to know whether different characteristics of these blood pressure trajectories are predictive of whether the recipients are likely to incur delayed graft function (a binary response variable that I have, indicative of successful transplant outcome). I want to adopt a formal modelling approach, but am not sure which would be more appropriate.
An extra complication to the correlation structure is the recipient centre variable that I have, which contains 22 levels.
I would be very grateful if someone could give me some hints to the following:

Is it possible to use a Multilevel Joint model for longitudinal and binary outcomes for this sort of data, as described in http://d-scholarship.pitt.edu/16754/1/SeoyeonHong_11262012.pdf   ?
If so, is there any package for implementing this sort of model in R?
Is there any other type of model that one could recommend to be more appropriate for this analysis (such as Binary GEE)? (As I have not found much literature behind the Joint model for longitudinal and binary data).
Answer: A joint model which i built using a mixed model and a logisitc regression is a possible way to do it, there is no pacakge available to apply it but it is easy to program it your self using R or winbugs .
Comment: As this stands it is more of a comment, on this site we prefers longer answers.  Maybe you can extend on the answer, maybe with some code, or we can convert this to a comment.


Proof verification: All metric spaces gave the "Hausdorff property".

Question: I am currently studying an introductory book to complex analysis. Within the first chaper the complex numbers are presented in various ways aswell as their structure regarding to different points of view $($e.g. as a vector space, in polar form, as group, etc.$)$.
However, I am having a hard time understanding the concept of topology which is also used there. Especially I am not quite sure whether I have fully understood the idea behind the proofs. Therefore $-$ and moreover in order to pratice proof writing $-$ I picked out a theorem and tried to prove it all by myself. Nevertheless I am not sure if I have managed to work out a sufficient proof or if I missed a crucial point.

Currently I am dealing with topological spaces, metric spaces, and their properties aswell as their relations. Firstly define a topological spaces as a metric space:

All metric spaces are topological spaces
  Every metric space $X$ is a topological space, where an open set is defined as the following: a set $M\subset X$ is called "open" if there exists for every $x\in X$ an $\varepsilon>0$, such that the "$\varepsilon$-environment" $$U_{\varepsilon}(x_0):=\{x\in X:d(x,x_0)<\varepsilon\}$$ is completely within $M$.

Here $d(x,y)$ denotes the specific metric of the metric space. Secondly there is a so-called "Hausdorff property" stated as:

"Hausdorff property"
  A topological space $X$ is a Hausdorff-space, if there exist for every distinct pair of points $x\ne y$ enviroments $U=U(x)$ and $V=V(y)$ such that $U\cap V=\emptyset$.

My aim is to prove that every metric space satisfies the "Hausdorff-property".
Proof
Assume there exists an point $y$ such that $y\in U_{\varepsilon}(x)$ and $y\in V_{\varepsilon'}(x')$ where $x\ne x'$. By definition the enviroments  $U_{\varepsilon}$ and $V_{\varepsilon'}$ are defined as
$$\begin{align}
U_{\varepsilon}(x)&=\{y\in X:d(y,x)<\varepsilon\}\\
V_{\varepsilon'}(x')&=\{y\in X:d(y,x')<\varepsilon'\}
\end{align}$$
From $x\ne x'$ we can conclude that $d(x,x')>0$. Furthermore the triangle inequality states that $d(x,x')\le d(x,y)+d(x',y)$. Consequently this leads to
$$\begin{align}
d(x,x')&\le d(x,y)+d(x',y)\\
0<d(x,x')&\le d(x,y)+d(x',y)\\
0&< d(x,y)+d(x',y)\\
0&< d(x,y)+d(x',y)<\varepsilon+\varepsilon'
\end{align}$$
Since $\varepsilon,\varepsilon'$ are choosen to be small numbers $($?$)$ this further yields to the contradiction
$$0<d(x,y)+d(x',y)<0$$
From where can conclude that $d(x,y)=d(x',y)=0$. Since $d(x,y)$ only equals $0$ iff $x=y$ it follows that $x'=x=y$ which contradicts our assumption.$\small\square$

As marked within my proof I am not sure whether my argumentation about the $\varepsilon,\varepsilon'$ is valid. Anyway I do not know how to finish the proof otherwise.

Is this proof legitimate or not? In the case this is right, what can be improved? In the case it is not, where have I gone wrong? I would appreciate if you could follow my own attempt, i.e. by using the metric of the space in order to prove the "Hausdorff-property". Anyway if this is an impractical approach I am open for different ways of showing the given thereom.

Thanks in advance!
Comment: Your idea is correct. But you will have to "choose" such $\epsilon$ and $\epsilon '$. You actually have to give them. Can you think of their values? Can you see how these $\epsilon$ environments actually look like in metric space? Try to visualise it, you may find such $\epsilon$ and $\epsilon '$. Another hint is that you need not even find two values. One value will be sufficient.
Comment: By the way, do you already know that open balls $U_\epsilon(x)$ are indeed open? It's an immediate consequence of the meric axioms, but you need to show that it contains a ball around each of its points, not just $x$
Comment: @HagenvonEitzen I would rather see this as a definition in this case than an assumption.  The inclusion of the first statement was just to add the connection of the metric space and the topological space by the "$\varepsilon$-enviroment" which I tried to use. Would it be an important point in order to just show that a metric space fulfills the "Hausdorff property", or can it be
neglected in  this case?
Answer: The main issue with your proof is that you haven't actually said what $\varepsilon$ and $\varepsilon'$ are before they're used, and then later on you say they're "small numbers", but again this is too vague.
You then conclude that $d(x,y) + d(x',y) < 0$, but this conclusion is erroneous for two reasons:

$\varepsilon$ and $\varepsilon'$ are (or, rather, should be) fixed from the start, and so you can't jump from $d(x,y) + d(x',y) < \varepsilon + \varepsilon'$ to this conclusion.
Even if you had proved that $d(x,y) + d(x',y) < \varepsilon + \varepsilon'$ for all $\varepsilon,\varepsilon' > 0$ (which you can't, since they're supposed to be fixed), the conclusion that you'd actually end up drawing is that $d(x,y) + d(x',y) \le 0$. But this is a moot point, as I mentioned.

Here's how I'd suggest to fix your proof. Take $x,x' \in X$ with $x \ne x'$. Then $d(x,x') > 0$, and so you can let $\varepsilon = \dfrac{d(x,x')}{2}$, which is positive (and is now fixed!).
Use a proof strategy similar to what you already tried, in order to prove that $U_{\varepsilon}(x)$ and $U_{\varepsilon}(x')$ are disjoint open neighbourhoods of $x$ and $x'$, respectively.
Comment: Just as a clarification for myself: By actually choosing $\varepsilon=\varepsilon'=\frac12d(x,x')$ I will get the inequality chain $$d(x,x')\le d(x,y)+d(x',y)< d(x,x')$$ but how exactly can I conclude from hereon that this contradicts my assumption? I mean indeed this seems to me already to be a contradiction since the sum of the two inner distances cannot be less or equal and greater than the distance between $x$ and $x'$ at the same time from where I can conclude that they both have to be zero. Or am I mistaken?
Comment: That's not the inequality chain you'll get. Assume $y \in U_{\varepsilon}(x) \cap U_{\varepsilon}(x')$. Then $$d(x,x') \le d(x,y) + d(y,x') < \varepsilon + \varepsilon = 2\varepsilon = d(x,x')$$ So the contradiction you get is that $d(x,x') < d(x,x')$.
Comment: It was just a typo, sorry for that. Nevertheless now it is clear. I am only a little bit curious about the choice of $\varepsilon$ and $\varepsilon'$; it seems to me like some kind of "cheating" to choose the value in order to cause this contradiction. How may on justify this choice?
Comment: @mrtaurho: What makes you say it's cheating? The definition of Hausdorff says that for every pair $x,x' \in X$ with $x \ne x'$, there are disjoint open neighbourhoods $U$ of $x$ and $V$ of $x'$. To prove this, you let $x,x' \in X$ be arbitrary elements with $x \ne x'$, and then in terms of $x$ and $x'$, all you have to do is find a neighbourhood of $x$ and a neighbourhood of $x'$ that are disjoint. Any two open balls that are small enough that they don't overlap will do, so we pick the radius of the open balls to be (at most) half the distance between $x$ and $x'$, so that they don't overlap.
Comment: If what you're worried about is that $\varepsilon$ is defined in terms of $x$ and $x'$, that's just what proofs of statements of the form $\forall \cdots \exists \cdots$ look like: in terms of the $\forall$-quantified variable(s), find a single thing (or, in this case, a single *pair* of things) making the statement true.
Comment: I would say I am not familiar yet with the choice of these specific values therefore it seemed unnatural to me to just choose the fixed number $\varepsilon$ to equal half the distance, but I would say this is just a personal opinion. Anyway thank you for your answer and your further explanation!
Answer: You wrote that $\varepsilon,\varepsilon'$ were chosen to be small numbers, but you did not tell us which choice was that. Therefore, you proved nothing.
Simply take $\displaystyle\varepsilon=\varepsilon'=\frac{d(x,x')}2$. That will do: $U_\varepsilon(x)\cap U_{\varepsilon'}(x')=\emptyset.$


What settings should my email server be mindful of to avoid bounce back from major email providers?

Question: So I think my postfix+dovecot+roundcube+postfixadmin+sasl+spamassassin+amavisd-new+postgrey setup is working correctly. I can send out emails to certain domain names. Receiving definitely works; however, when i send out emails to hotmail for instance I get a bounce back. Even worse yahoo doesn't even bounce it just kills the email all together.
I don't think I have been blacklisted or anything (maybe I have been? I don't even know.) so I am assuming that these companies don't like that some of my settings don't match up in my headers or something. Perhaps I have an IP or Server name instead of domain name somewhere or something. I am not sure.
Also is there a way to confirm that I have password protected SMTP? I am pretty sure it is; however, How can I be sure?
Here is the bounce back email:

This is the mail system at host XXXXXXX.
I'm sorry to have to inform you that your message could not
  be delivered to one or more recipients. It's attached below.
For further assistance, please send mail to postmaster.
If you do so, please include this problem report. You can
  delete your own text from the attached returned message.
<code>               The mail system
</code>
:
      said: 550 OU-001 Mail rejected by Windows Live Hotmail for policy reasons.
      Reasons for rejection may be related to content with spam-like
      characteristics or IP/domain reputation problems. If you are not an
      email/network admin please contact your E-mail/Internet Service Provider
      for help. Email/network admins, please visit x for
      email delivery information and support (in reply to MAIL FROM command)
Reporting-MTA: dns; XXXXXXXXXXXXXXX
  X-Postfix-Queue-ID: C9CD66C0F4
  X-Postfix-Sender: rfc822; XXXXXXXX
  Arrival-Date: Sun,  4 Oct 2009 23:30:50 +0000 (UTC)
Final-Recipient: rfc822; XXXXX
  Original-Recipient: rfc822;XXXXXX
  Action: failed
  Status: 5.0.0
  Remote-MTA: dns; hotmailserver
  Diagnostic-Code: smtp; 550 OU-001 Mail rejected by Windows Live Hotmail for
      policy reasons. Reasons for rejection may be related to content with
      spam-like characteristics or IP/domain reputation problems. If you are not
      an email/network admin please contact your E-mail/Internet Service Provider
      for help. Email/network admins, please visit x for
      email delivery information and support
Comment: Not sure if I completely understand the "question" but have you tried the tests here: http://www.mxtoolbox.com
Answer: Yep, Windows Live can be a pain. Check:

You're not on a blacklist
Your server has MX and reverse DNS records
You have SPF DNS records (many servers reject mail without a valid SPF, GMail for example, here's an explanation and a wizard)
Your mailserver's HELO response matches your hostname
Your mailserver is not an open relay
Your DNS records' TTL is not too low - 86400 (24 hours) is recommended (some spammers set their TTL very low to regularly update forged DNS records)
Comment: I think that pretty well covers it. +1
Answer: The MX record doesn't matter.  MX is purely for inbound.  Your SMTP server may not be the MX server.
The reverse DNS records have to exist, but they also have to match going both ways.
If you look up the IP, it produces a hostname.  If you look up the host name it must match the same IP, not a different IP, or it will be rejected.
Also, around the beginning of October, there was a problem with hotmail where they were rejecting all email from many cable company IPs.  I'd expect that problem is now past.
Comment: Agreed, it SHOULDN'T be an anti-spam criteria. However, you should at the very least receive postmaster@ email for any domain you send email from.


How do I set, and return, a value in Views PHP?

Question: I'm not going to use the real scenario here, just a very simple one that I think should be working.
I have a View.  This view does access some Solr stuff.
I've added a new field to the view.  It's a Global PHP field.  My end goal of this is that I'd like to make this field sortable when you click the table heading.
In the "Value code":
return "asdfasdf";

In the "Output code"
<?php
  print $value;
?>

This returns... nothing. No errors, no output. This is the simplest example I could think of. Am I missing something here?
"Output code" does display other things, even complex things if I ask it to.  It just seems like "Value code" is being completely ignored.
Answer: It works for me. I put the information you said in a PHP field and it printed out as expected. I imagine it's a caching issue or something else about your site that is causing the issue.
Comment: Okay. Thanks!  I have a feeling it's related to the view being generated using Solr data.


How to State My Results for a Mann-Whitney U test (High Schooler)

Question: I have two independent samples that are non-normally distributed and have unequal variances.
I want to do a very simple two-tailed test of equality like this:
H0: The two populations are equal versus
H1: The two populations are not equal
Is a WMW appropriate to use in this circumstance? I have read this message board and the general consensus is that it is, so long as it is the stochastic equality between the two that is being compared and not any measure of central tendency. But this is where I get confused, because I am only a high schooler, and I do not really know how to write a statement of results for stochastic equality.
Wikipedia gives a sample statement of results for a WMW test as:
"Median latencies in groups E and C were 153 and 247 ms; the distributions in the two groups differed significantly (Mann–Whitney U = 10.5, n1 = n2 = 8, P < 0.05 two-tailed)."
But is this an appropriate way for me to state my results for my teacher since I can only look at my results from a stochastic equality perspective? If it is not, can someone in very simple and plain language provide me with an example of how I should state my results? Thank you, I am only just learning statistics and any help would be appreciated.
Answer: Let me show results from the Mann-Whitney-Wilcoxon
Signed rank test for some simulated data in R.
First, the data meet your specifications because they
are sampled from gamma distributions, which are right
skewed and so not normal. The respective population means are $\mu_1 = 10,\,
\mu_2 = 20.$ Also, the population variance from which the first
sample was drawn is less than the population variance for
the second sample.
Simulated Data and 'Location'. In a real life situation we would not
have all of this information about the populations. The
point here is to see how well the samples (both of size 20)
reflect the populations from which they were drawn. In
particular we want to see if a 2-sample Mann-Whitney-Wilcoxon test
can detect that the location of the second population is located
above the first.
set.seed(2020)
x1 = rgamma(20, 3, .3)
x2 = rgamma(20, 4, .2)
summary(x1); sd(x1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  2.401   6.846  10.218  10.335  13.861  24.977
[1] 5.370183  # sample SD of x1
summary(x2); sd(x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  8.202  10.945  16.474  17.362  22.043  34.085
[1] 7.15061   # sample SD of x2

Location shift. Notice that the 1st quartile, median, mean, and 3rd quartiles
for the first sample are all below the corresponding values for
the second sample. There are many ways to express the 'location'
of a sample (or distribution). The median is among them, but
certainly not the only one. (Also, the maximum value in the first sample
lies below the maximum value in the second sample, but in these
right-skewed distributions maximum values are rather unpredictable.)
Thus, if one does not want to use the median as the specific
measure of location, there are other ways to discuss location. A general
term for expressing that two samples (or populations) do not have
the same location, is that there is a "location shift" of one from
the other. You should discuss this with your instructor, but I think
location shift might be the best terminology for you to use.
Boxplots (each based on quartiles, median, min and max)
show that the sample x1 tends to be 'located' below
the sample x2.
boxplot(x1, x2)

Mann-Whitney-Wilcoxon Test. The M-W-W test does show a significant location shift (P-value about 0.002).
Notice the terminology "location shift" in the R output for this procedure.
wilcox.test(x1, x2)

        Wilcoxon rank sum test

data:  x1 and x2
W = 87, p-value = 0.001767
alternative hypothesis:
   true location shift is not equal to 0

ECDFs and 'Stochastic Dominance'. Another technical term for saying that one sample is located above another
is "stochastic dominance/" If you google around the internet you will see
that there are several senses (sometimes called 'orders') of stochastic
dominance. A lot of this may be above your level, but on some pages you'll find some simple gambling examples and see
illustrative graphs. You might use the terminology "stochastic dominance," if you're prepared to explain it.
ECDFs. One of the simpler kinds of stochastic dominance has to do with ECDF plots.
Especially for large samples, the empirical CDF (ECDF) of a sample imitates
the CDF of the population from which the sample was chosen.
To make an ECDF of a sample begin by sorting its values from smallest to
largest. The ECDF is a stairstep function. With a sample of size $n$ it jumps up by distance $1/n$ at each sorted data value. (If $k$ observations are tiec at a value, then the jump there is $k/n.)$ So the ECDF starts at $0$ on the left and rises to $1$ at the right. One sample "dominates" another if its ECDF
is to the right of the ECDF of the other.
The left panel below shows the CDFs of the two populations from which our samples were randomly chosen: blue for the first sample and maroon for the second. At right (same colors) are the ECDF for the samples. [R code below
the graph.]

par(mfrow=c(1,2))
 curve(pgamma(x, 3, .3), 0, 40, col="blue", lwd=2, ylab="CDF",
       main="Population CDFs")
   curve(pgamma(x, 4, .2), add=T, col="maroon", lwd=2)
 plot(ecdf(x1), col="blue", main="Sample ECDFs")
   lines(ecdf(x2), col="maroon")
par(mfrow=c(1,1))

Comment: Thank you Bruce, this is a very detailed answer that has really helped me to conceptualize what a location shift is and what it means in terms that I can understand.
Answer: The wikipedia statement reports all you need here. To answer your question: Just go with that. It's fairly standard language to report your results like that.
But for I'd recommend reading BruceET's answer for a more in depth explanation of what the Mann-Whitney test actually does and how it works. It's important to understand why you're using the test that you're using, and if this is your main result, the box plot is useful to visualise the difference.


Set order / weight of user profile core fields against user profile custom fields

Question: Is it possible to set the order of core fields against custom fields added on user profile page?
I want to bring the status field to the bottom of the list.
I'm trying the code below but without succes:
function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['status']['#weight'] = 100;
}

I want something in the following order for example:

Username (core)
Password (core)
Custom field 1
Custom field 2
Status
(core)

Thanks in advance
Answer: You can just try and set the weight as follows
$form['status']['#weight'] = field_info_max_weight('user', 'user', 'form') + 10;

Have not tried it but I am pretty sure it will work. This will make sure the status will always be the last field.
Also it should be $form['account']['status']['#weight']
Comment: Awesome, never even heard of that function before but it's very heplful
Comment: Ya I came across it from the fields ui module when I was working on a project which created dynamic fields and I was looking for something like that. There is even a hook for that function.
Comment: Yeah so it does, thanks; I'd up-vote again if I could :)
Comment: Ah i see that the status field is inside the account array. Actually what I intend to do is pull out this status field and set the weight of it according to the other custom fields one level up


$\lim\limits_{n\to\infty}{[x]+[2^2x]+\dots +[n^2x]\over n^3}$

Question: Find the limit,  $$\lim_{n\to\infty}{[x]+[2^2x]+\dots +[n^2x]\over n^3}$$
Where $[.]$ denotes the integral part of $.$?
Efforts: If $x$ is integer,
 $$\lim_{n\to\infty}{[x]+[2^2x]+\dots +[n^2x]\over n^3}$$ $$\lim_{n\to\infty}{x(1+2^2+\dots +n^2)\over n^3}$$
We know $\sum\limits_{i=1}^ni^2=(n+1)(2n+1)n/6$
Therefore we get that limit is equal to $x/3$.
How to solve it for non integral values.
Thanks in advance.
Comment: You can try to use $x-1 \leq [x] \leq x$ and squeeze out the limit.
Answer: See the difference between this one and
$\frac{x+2^2x+3^2x+...+n^2 x}{n^3}$ is $\frac{\{x\}+\{2^2x\}+\{3^2x\}+...+\{n^2 x\}}{n^3}$, which is smaller than $\frac{n^2}{n^3}=\frac 1n \to 0$; here $\{y\}=y-[y]$. So your expression has the same limit $\frac 13$ as $\frac{x+2^2x+3^2x+...+n^2 x}{n^3}$.
Comment: Probably a typo: makes more sense to say it's less than $\frac{n}{n^3}$ instead of $\frac{n^2}{n^3}$ as there are $n$ terms in the numerator each of which is less than $1$.
Answer: Applying Stolz–Cesàro theorem with
$a_n=\sum\limits_{k=1}^n [x\cdot k^2]$ and
$b_n=n^3$ (which is strictly monotone and divergent)
$$\frac{a_{n+1}-a_n}{b_{n+1}-b_n}=
\frac{[x(n+1)^2]}{(n+1)^3-n^3}=
\frac{[x(n+1)^2]}{(n+1)^2+(n+1)n+n^2}$$
and we have (using inequality @Winther suggested in the comments $x-1\leq[x]<x$ and squeeze theorem)
$$\frac{x(n+1)^2-1}{3(n+1)^2}\leq
\frac{[x(n+1)^2]}{3(n+1)^2}<
\frac{a_{n+1}-a_n}{b_{n+1}-b_n}<
\frac{[x(n+1)^2]}{3n^2}<
\frac{x(n+1)^2}{3n^2}$$
as a result
$$\lim\limits_{n\rightarrow\infty}\frac{a_{n+1}-a_n}{b_{n+1}-b_n}=\frac{x}{3}$$
and finally
$$\lim\limits_{n\rightarrow\infty}\frac{a_n}{b_n}=
\lim\limits_{n\rightarrow\infty}\frac{\sum\limits_{k=1}^n [x\cdot k^2]}{n^3}=
\frac{x}{3}$$
Comment: simply beautiful :)


Escrever os dados de um inputText em outro inputText

Question: Pessoal estou usando JAVA,JPA,PrimeFaces...Em minha view (xhtml) eu tenho uma tela de login,como faço para pegar o nome que o usuario digitou e escrever em outro campo inputText?
Comment: Não é melhor usar javascript e fazer isso client-side?
Comment: Amigo, tem várias formas de fazer, mas seria interessante você postar seu código para podermos dar a resposta baseado no que você quer.
Comment: Veja se isso te ajuda:
http://pt.stackoverflow.com/questions/54037/enviar-e-receber-vari%C3%A1vel-para-outra-p%C3%A1gina
Comment: Veja se isso te ajuda:
http://pt.stackoverflow.com/questions/54037/enviar-e-receber-vari%C3%A1vel-para-outra-p%C3%A1gina
Comment: Carlos, agradeço o link mas nao ajdou muito pq é de um inputText, oq eu me mandou o valr esta descrito na URL o meu nao esta, quero simplesmente pegar o que esta num inputText e escrever em outro inputText de outra página
Answer: Se for em tempo de execução (sem recarregar a pagina) o melhor é usar JQuery:
<code> <script>
                jQuery(document).ready(function () {
                    jQuery('#idCampoOrigem').blur(function () {
                        jQuery('#idCampoDestino').val(jQuery('#idCampoOrigem').val());
                    });
                });
            </script>
</code>
Comment: Norivan desculpe, não expliquei 100%,...realmente muda de página sim...=/
Quero o texto digitado em um campo e escrever este texto em outro campo em outra tela.
Comment: Grava a informação do primeiro campo no seu controller em escopo de sessão e pega na outra tela


What are the (dis)advantages of a constant declared in an anonymous namespace vs a function-scope static constant?

Question: I want to define a function that, when given an integer, will return a string. Like this:
# Pseudocode
function get_string(i)
  return my_string_array[i]
end

The strings will be hard coded into the application. The function prototype is declared in a header file:
// header.h
const std::string &get_string(const int i);

The way I see it, I have two options for declaring the hard-coded strings.
Option #1: Declare a static variable in get_string
// source.cpp
const std::string &get_string(const int i)
{
    static const std::string values[] = {
        std::string("foo"),
        std::string("bar"),
        std::string("baz"),
    };

    // Assume bounds checking is performed on i.

    return values[i];
}

Option #2: Declare global constant in an anonymous namespace
// source.cpp
namespace
{
    const std::string values[] = {
        std::string("foo"),
        std::string("bar"),
        std::string("baz"),
    };
}

const std::string &get_string(const int i)
{
    // Assume bounds checking is performed on i.
    return values[i];
}

For this limited use-case, are these declarations functionally equivalent? Does the program treat static constants in functions differently from globally declared constants or constants declared in anonymous namespaces?
I'm aware of the obvious accessibility differences (i.e. constant declared in local namespace is available globally to all functions defined in the same translation unit), but that can be chalked up as an advantage either way depending on the scenario, so for the purposes of this question this difference can be omitted.
Comment: The only difference I could think of is that globals are initialized at the start of the program before `main` is entered; while function statics are initialized only when the function is first called. In your case, the distinction probably doesn't matter.
Comment: Define it inside the function itself, if nobody else uses it directly (which nobody should do, ideally, otherwise, there is no purpose of the function itself). Apart from that, you must check `i` for out-of-range value, before accessing the element.
Comment: @Nawaz - Fear not, bounds checking would be performed for sure :-)
Comment: Depending on your use case, if `i` is known at compile time, you could make `get_string` a template function taking `i` as a template parameter and use template specialization to return the appropriate string. You probably determine `i` at runtime so maybe this won't work, just throwing out options.
Answer: Strings defined as static array inside your get_string function will be constructed on the first get_string call, while strings in global namespace will be constructed on application start.
So the problems that might arrise are different for both aproaches. For example if you go with defining strings at global scope then you should not use it before your main is executed, otherwise you never know if they got constructed. If you go with static construction inside get_string you may encounter threading problems at least until c++11, after that magic statics should fix this for you.
Why dont you put them inside const char* global array?
[edit]
Global array is not the right way to do it, as I suggested above. Another thing for you to consider is to go with option 1, but instead of array of strings create array of const char* string literals. Array of std::string object's will duplicate your string literals. You would have to probably also return const char* - so maybe thats not what you want.
Comment: *Why dont you put them inside const char\* global array?* ..Why `const char*` exactly? Why *global* exactly?
Comment: I thought that would fix the 'static initialization order fiasco' problem, also I meant static array of 'const char*'.
Comment: I agree that going with `Option #1` should be recomended.
Comment: *"static initialization order fiasco"* has nothing to with elements being `std::string`, and thus if at all it is going to show up in this case, it cannot be fixed by replacing `std::string` with `const char*`.
Comment: uh, right - such global array would still have to be assigned during initialization.


Redirect visitor based upon geolocation

Question: On a Drupal website I want to redirect the visitor to a landing page based on the users location. I need this to be more specific than just the users country, but rather I need the province inside the country. When the user does not allow to be located, the user will go to the standard landing page...
Is there an (easy) way to achieve this? I am fairly new to the world of Drupal.
Answer: I've had pretty good results previously with SmartIP, and now there is Rules integration which can react to which country the user is in.
So you should be able to set a Rule similar to the following psuedo-rule:

EVENT:
Page is going to be viewed
CONDITION:

Page is: Front page
IP Address is in country: whatever country you want

ACTIONS:
Go to page: YOUR COUNTRY SPECIFIC LANDING PAGE

I know you said you were new to Drupal, so you can find some really useful Rules tutorials at NodeOne: Learn the Rules Framework.
EDIT
I've just twigged you said you want it to the province level rather than country (sorry, that was glaringly obvious - my fault), so you might be looking at some custom code.
Last time I used it, I used SmartIP to get the latitude and longitude of the user, and then the Location API for the nitty gritty.
You should be able to combine this with hook_init() and drupal_goto() to redirect the user to the relevant page.

Redirect visitor based upon geolocation


Access CCK Fields on Content Type EntityFieldQuery()

Question: Okay, I've spent two days banging my head against the wall, so I'm finally going out for help...
I have a custom content type "eod_report" with a CCK field called "rfqs_received" which stores an integer.
I need to access the value of "rfqs_received" (previous 5 entries per user), but all I get is a list of the nodes themselves. What I want is an array of the queried field values.
How can I get access to the field values? Any help is MUCH appreciated.
    <?php

global $user;
$uid = $user->uid;

$query = new EntityFieldQuery();
$entities = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'eod_report')
  ->propertyCondition('uid', $uid)
  ->propertyCondition('status', 1);

  //->fieldCondition('field_rfqs_received', 'value', '6', '<');

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = node_load_multiple($nids);
$output = node_view_multiple($nodes);

print render($output);
?>

The answer below solved it. To clarify, this was a portion of an attempt to create a custom action that would calculate the average of field values for the last five pieces of content created by a user. The action occurs when content is saved/updated and saves values to the current user's profile. It's a bit sloppy, I think, but it works. I'm still learning... Here's the full code of the action:
    <?php

global $user;
$uid = $user->uid;

// query the database to get the previous 5 eod_reports
$query = new EntityFieldQuery();
$entities = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'eod_report')
  ->propertyCondition('uid', 50)
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC')
  ->range(0,5);

$result = $query->execute();

// Collect the $nids of the nodes returned by the query

$nids = array_keys($result['node']);

// Declare an empty array to store the rfq results
$rfqs = array();
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // Get the field items
  $items = field_get_items('node', $node, 'field_rfqs_received');

  // loop through items, extract rfq values and store to array.
  foreach ($items as $item) {
    // Add to the output array.
   $rfqs[] = field_view_value('node', $node, 'field_rfqs_received', $item);
  }
}

// Declare an empty array to store the order results
$orders = array();
foreach ($nodes as $node) {
    // Get the field items
    $oitems = field_get_items('node', $node, 'field_orders_received');

    // Loop through items, extract order values and store to array.
    foreach ($oitems as $oitem) {
    $orders[] = field_view_value('node', $node, 'field_orders_received', $oitem);
    }
}

// Prepare the loop to sum the rfq results

$rfqSum = 0;
$i = 0;
// Loop through the results and collect a sum
while ($i < 5) {
    $rfqSum = $rfqSum + render($rfqs[$i]);
    $i = $i + 1;
}

// Prepare the loop to sum the order results

$orderSum = 0;
$x = 0;
// Loop through the order array to collect sum
while ($x < 5) {
    $orderSum = $orderSum + render($orders[$x]);
    $x = $x + 1;
}

// Print the Sums

print "
RFQ Sum: " . $rfqSum . "
";
print "
Order Sum: " . $orderSum . "
";

// Calculate the average

$rfqAvg = $rfqSum/5;
$orderAvg = $orderSum/5;

// Print the average
print "
RFQ Avg: " . $rfqAvg . "
";
print "
Order Avg: " . $orderAvg . "
";

// collect the current user information and store the calculated value in the user->field

$existing = user_load($uid);
$edit = (array) $existing;
$edit['field_rfq_average']['und'][0]['value'] = $rfqAvg;
$edit['field_order_average']['und'][0]['value'] = $orderAvg;
user_save($existing, $edit);

?>

Answer: EntityFieldQuerys are for querying entities, with the option to filter on their field values. They don't have the capacity to return any field data.
What you might be looking for is something like this, using field_get_items() and field_view_value()
...
$output = [];
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // Get the field items
  $items = field_get_items('node', $node, 'field_rfqs_received');

  // Truncate to the necessary number (your logic will probably change here)
  foreach (array_slice($items, 0, 5) as $item) {
    // Add to the output array.
    $output[] = field_view_value('node', $node, 'field_rfqs_received', $item);
  }
}

print render($output);

Comment: That's totally it! Thank you so much!!! I'll update my post to reflect the working code.


Wrong date field format on mobile iOS / Android

Question: I created a form with Drupal's FAPI. The form includes two date fields. It works fine on desktop browser.
But on mobile (iOS and Android), the datepicker doesn't show up. It is the native date selector which shows up.
The issue is that the native date selector doesn't seem to apply the date format (in my case : '#date_date_format' => 'd/m/Y')
I see 2 possible solutions :

With JS, force the date format
Force the date picker to show up (i've seen this on other website
i've made but in wasn't Drupal FAPI.

How do you handle this problem ?
Here is my code and a screen shot of the issue :
    $form['date_debut'] = array(
        '#type' => 'date',
        '#title' => $this->t('Date de début'),
        '#type' => 'date_popup',
        '#date_date_format' => 'd/m/Y',
        '#description' => t('Cliquez dans le champ et sélectionnez une date de début de congé dans le calendrier'),
        '#required' => TRUE
    );

Answer: The solution is not to use :
<input type="date">

but
<input type="text">

With Form API, replace :
$form['my_date'] = array(
    '#type' => 'date',
);

with
$form['my_date'] = array(
    '#type' => 'textfield',
);

And attach a date picker like the jQuery Datepicker available in Drupal 8 or other library like Bootstrap Datepicker
In safari, i need to test in private mode because sometines the Safari cache prevents me to see update in my JS.


Can $ I_n(z) = (\frac{z}{2})^n\sum_{k=0}^\infty\frac{(-1)^k}{k!(n+k)!}\frac{1}{k+(n+k)+1}(\frac{z}{2})^{2k}$ be expressed by the Bessel function?

Question: We know that the first kind of Bessel function can be expressed by the form of Taylor series
$$
J_n(z) = (\frac{z}{2})^n\sum_{k=0}^\infty\frac{(-1)^k}{k!(n+k)!}(\frac{z}{2})^{2k}
$$
when $n\in\mathbb{N}$. I'm interested in a variant of this form, that's
$$
I_n(z) = (\frac{z}{2})^n\sum_{k=0}^\infty\frac{(-1)^k}{k!(n+k)!}\frac{1}{k+(n+k)+1}(\frac{z}{2})^{2k}.
$$
So, does this variant $I_n(z)$ can be expressed by the Bessel function?
I have some ideas:
$$
I_n(z) = (\frac{z}{2})^n\sum_{k=0}^\infty\frac{(-1)^k}{(k+n+k+1)!}\left(\begin{matrix}n+2k\\k\end{matrix}\right)(\frac{z}{2})^{2k},
$$
and then use the formula
$$
\left(\begin{matrix}n+2k\\k\end{matrix}\right) = \left(\begin{matrix}n+2k+1\\k+1\end{matrix}\right)-\left(\begin{matrix}n+2k\\k+1\end{matrix}\right),
$$
...
Comment: Isn't $I_n(t)\frac 2z$ the integral of $J_n(z)$ over $\frac z2$ ?
Comment: @RaymondManzoni Long time no see. Are you OK ? Cheers :-)
Comment: Hi @ClaudeLeibovici and glad to share your interests shortly! Notice that the integral of $J_n(z)$ is [known](https://www.wolframalpha.com/input/?i=Integrate%5B%20BesselJ%5Bn%2Cz%5D%2Cz%5D) which should help using my comment. Excellent continuation anyway and cheers,
Comment: Note that the notation $I_n$ is used for the modified Bessel function of the first kind in the literature.
Answer: We have
\begin{align*}
zI_{2n} (z)  & = \int_0^z {J_{2n} (t)dt}  = \int_0^z {J_0 (t)dt}  - 2\sum\limits_{k = 0}^{n - 1} {J_{2k + 1} (z)}
\\ & = \frac{\pi }{2}z(J_0 (z){\bf H}_{ - 1} (z) - J_{ - 1} (z){\bf H}_0 (z)) - 2\sum\limits_{k = 0}^{n - 1} {J_{2k + 1} (z)}
\\ & = \frac{\pi }{2}z(J_1 (z){\bf H}_0 (z) - J_0 (z){\bf H}_1 (z)) + zJ_0 (z) - 2\sum\limits_{k = 0}^{n - 1} {J_{2k + 1} (z)}
\end{align*}
and
$$zI_{2n + 1} (z) = \int_0^z {J_{2n + 1} (t)dt}  = 1 - J_0 (z) - 2\sum\limits_{k = 0}^n {J_{2k} (z)} .
$$
To establish these, I used $(10.22.9)$, $(10.22.2)$, $(10.4.1)$ and $(11.4.23)$.
Comment: Thanks for telling me. Nice and elegant generalization
Answer: $$I_n(z)=\left(\frac{z}{2}\right)^{n}\,\sum_{k=0}^\infty\frac{(-1)^k}{k! \, (k+n)!\,(2 k+n+1)}\left(\frac{z}{2}\right)^{2 k}$$ is
$$I_n(z)= \left(\frac{z}{2}\right)^{n}\,\,\frac{\,
   _1F_2\left(\frac{n+1}{2};\frac{n+3}{2},n+1;-\frac{z^2}{4}
   \right)}{(n+1)!}$$ At least for some values of $n$, we see appearing some Bessel functions
$$I_0(z)=\frac{1}{2} \pi  \pmb{H}_0(z) J_1(z)+\frac{1}{2} (2-\pi  \pmb{H}_1(z)) J_0(z)$$
$$I_1(z)=\frac{1}{z}-\frac{J_0(z)}{z}$$
$$I_2(z)=\frac{(\pi  z \pmb{H}_0(z)-4) J_1(z)}{2 z}+\frac{1}{2} (2-\pi  \pmb{H}_1(z)) J_0(z)$$
$$I_3(z)=-\frac{2 J_1(z)}{z^2}+\frac{1}{z}-\frac{J_2(z)}{z}$$
$$I_4(z)=\frac{\left(\pi  z^3 \pmb{H}_0(z)-32\right) J_1(z)}{2 z^3}+\frac{\left(-\pi  z^2
   \pmb{H}_1(z)+2 z^2+16\right) J_0(z)}{2 z^2}$$
$$I_5(z)=-\frac{10 J_3(z)}{z^2}+\frac{\left(z^2-8\right) J_2(z)}{z^3}+\frac{1}{z}$$
The next ones are too long to be typed.
What it seems is that for odd values of $n$ only Bessel J functions appear while, for even values of $n$,they appear at the same times as Struve functions.
Comment: See my answer which confirms your observations.


What is the intuition behind quantile in scipy.stats.beta.ppf?

Question: I'm trying to use scipy.stats.beta.ppf(q, a, b), where q is referred to as quantile. I understand how beta works and its details, but I'm not able to make sense of q here (It is also called as lower tail probability). I mean, why lower tail probability here in this function ? What benefit does lower tail probability gives us here ? What exactly does q (the lower tail probability) in the above function mean and how to understand the same and its intuition ?
Comment: Too many questions in a single post…
Answer: Let $X$ be a (univariate) random variable, beta-distributed in your case.
A quantile $q$ is defined as the value $x$ such that $P(X\le x)=q$. That is, quantile $0.5$ is the value $x$ such that half of the density is $x$ or lower. For any symmetric beta distribution, quantile $0.5$ happens to be $0.5$. For asymmetric beta distributions, quantile $0.5$ could be much higher or lower, depending on the specifics of t he density.
If you understand percentiles, quantiles are extremely similar, just expressed on $[0,1]$ rather than $[0,100]$.
Comment: Thank you for your answer. I understand quantiles, I just want to understand the same in the context of beta distribution here. For example, The intuition behind the lower tail probability in beta.ppf. The intuition when we set q here to 0.05 (say) and how things change if we set q to 0.90. (I probably didn't frame my question right)
Comment: If you set it to $0.05$, it means $5\%$ of the density is in the part of the distribution at or below the returned quantile value. If you set it to $0.90$, it means $90\%$ of the density is in the part of the distribution at or below the returned quantile value.


How can I prevent an ActiveRecord object's fields from being changed?

Question: In my Rails 3 project, I have a table that I want to only be for reference to the application: I never want anyone to have the ability to change this data within the app. Here's what I have so far:
class Foo < ActiveRecord::Base
  attr_readonly :name, :description

  has_many :bars

  def readonly?
    return true
  end
  ...
end

While this prevents saving the record or using update_attributes, I'd like to lock it down even more: is there a way for me to prevent assignment of a loaded record, a la:
f = Foo.find(1)
f.name = 'New Name'
SomeError: You cannot change properties of this object

Comment: Why is it an active record object?
Comment: Because the original configuration of the object is in the database. Long story.
Comment: Why do you want to stop the altering of attributes? If they can't save them, why does it matter?
Comment: It probably doesn't, but I'm curious to know how hard I can lock these suckers down.
Answer: You can make a custom setter for the property:
def name=(val)
  raise RuntimeError, 'You cannot change properties of this object'
end

This will prevent anyone from modifying the value.


A question about how to express a fraction as ${1\over q_1}+{1\over q_2}+ \cdots+{1\over q_N}$

Question: Let $x$ be a positive rational number, strictly between $0$ and $1$. Prove that there is a finite strictly increasing list of positive integers $2 \leq q_1<q_2<\cdots<q_N $ such that $$x={1\over q_1}+{1\over q_2}+ \cdots+{1\over q_N}.$$
I have tried many methods, such as mathematical induction. I know it is obvious that $\frac{1}{m}$ is right for assumption, but when I begin to prove $\frac{2}{m}$, I feel it is hard to find some patterns for $\frac{2}{m}$. Thus, maybe my thoughts are wrong.
Also, I still tried to change the fraction so that the numerator will be smaller and smaller. But I still cannot find a way to lower the numerator. Can someone help me solve the question? Or, can someone give me some hints. I will appreciate you very much!
Comment: To see other ways to do this, look at Egyptian fractions.
Comment: yes x is a positive rational
Answer: Let $q=m/n$ rational, with $q\in (0,1)$, and hence
$$
\frac{1}{k}\le\frac{m}{n}<\frac{1}{k-1}
$$
for some integer $k>1$. If $\frac{1}{k}=\frac{m}{n}$, we have nothing to prove. Otherwise,
we have
$$
\frac{m}{n}-\frac{1}{k}=\frac{km-n}{kn}=\frac{m'}{n'}>0.
$$
But $\dfrac{1}{k-1}>\dfrac{m}{n}$ implies that $n>m(k-1)$, or $m>km-n=m'>0$.
Hence, after we subtracted the the nearest and smallest fraction of the form $1/k$, the remainder $m'/n'$ has smaller numerator.
Hence, in at most $m$ steps this procedure ends, and thus we obtain the sought for representation.
Comment: Oh, that's great


Windows Phone Emulator not starting

Question: When I run the emulator from the VS13 hangs self in "Windows Phone OS is Starting" but in Hyper-v manager is running properly and then keep getting two errors
Error : DEP6200 : Boostrapping 'Emulator 8.1 WVGA 4 inch 512MB' failed. Device cannot be found. App deployment failed. Please try again.
Error : DEP6100 : The following unexpected error occurred during boostrapping stage 'Connecting to the device':
SmartDeviceException - App deployment failed. Please try again.
Help!
Comment: I'd suggest that you reinstall the virtual phone packages.
Comment: I did that but the problem was not solved
Answer:
Repair the Visual Studio
Download and install this emulator (Microsoft Emulator - Windows 10.0.26624)
https://go.microsoft.com/fwlink/p/?LinkID=619310
Answer: The solution is removing a duplicated route.

List item
Run "cmd.exe" as administrator
Type "route print"
If you see two identical routes from 169.254.0.0 like here:

<code>Persistent Routes:
Network Address  Netmask      Gateway Address  Metric
169.254.0.0      255.255.0.0  192.168.1.47     1
169.254.0.0      255.255.0.0  192.168.1.44     1
</code>

(b) Then remove both routes with "route delete 169.254.0.0"
Remove Hyper-V (go to "programs and features")
Restart system
Install Hyper-V
Restart system

Now you can deploy and debug your windows phone project on the emulator.
Comment: Reinstalling Hyper V is quite extreme. In my experience I found that the route in question was being shared with of all things my Corporate VPN client.  On disconnecting the client and then re-running the solution it was successfully deployed to the emulator.  I hope this helps.
Answer: From my experience, the two errors you're getting have to do with two components of the Windows Phone VM.
For the first error, i don't know exactly what failed but it sounds like the VM image might not be working as VS is expecting, one thing you can do for this is simply open Hyper-V manager and delete the VM, when you start debugging again from VS, it will create the VM Image again according to the specifications of the device you're emulating.
But pay attention to the second error:
I have had that error lots of times, but that mostly presents even if the VM is successfully launched by VS, but there is an issue communicating with it through the virtual switch that is created for it and that can be managed in Hyper-V on the virtual switches section.
So in this case, once again, you can solve this issue by deleting the virtual switch in Hyper-V manager and VS will recreate it when you start debugging again.
I'm sorry i don't have a definitive answer for you with detailed steps but deleting the virtual switches and VMs works most of the time since VS does all the configuration for you when trying again, but if that fails, check this guide at MSDN. I hope you get it working, it is a serious pain to deal with those issues for a while when you're just trying to test your apps.
Answer: There seem to be problems/conflicts with Windows Update and reboots during the setup phase of the update 2 of VS2013 bringing WP8.1.
Many people have the same problem:

Case 1: http://connect.microsoft.com/VisualStudio/feedback/details/872213/vs-2013-update-2-fails-to-connect-to-wp8-1-emulator
==> Solved by a reboot, even if the user had already done the reboot after installing WP8.1 VM
Case 2: VisualStudio 2013 Express phone emulator - device not found
==> Solved by a reboot by Kajal Sinha

Can you reboot your machine, check any pending windows update, and try again?
Answer: In my case I have resolved this issue by removing all virtual machine in Hyper V manager as suggested by this solution:
https://stackoverflow.com/a/21084481/4562521

Open Hyper V Manager (click Start, point to Administrative Tools, and then click Hyper-V Manager)
Delete all installed Virtual Machines
Delete all Virtual Switches
Restart system
Rerun visual studio
Comment: Because removing all virtual machine created, solve on my computer this issue:  VS13 hangs self in "Windows Phone OS is Starting" but in Hyper-v manager is running properly. I'll change  this post  reply as you suggest. Thank you
Answer: I faced this problem many times, and the main cause is anti-virus firewall settings.
Windows phone emulator will creates virtual network adapters, and independent anti-virus firewall does not allow access to these adapters.
To solve the issue, uninstall or disable anti-virus software including windows defender.

Windows Phone Emulator not starting


Exercise from Marcus on class groups

Question: I stumbled upon this:
Let $p$ be a prime of $K$ (a given number field) and let $m$ be the order of $[p]$ in $Cl(K)$. Suppose $\mathcal{P}|p$ is a prime of $L$ (here, $L/K$ is an extension of $K$). Show that $m/(m, f(\mathcal{P},p))$ divides the order of the class $[\mathcal{P}]$ in $Cl(L)$.
Any help is welcomed, thanks!
Answer: Here is an argument avoiding class field theory:
Let $a$ be the order of $\mathcal P$ in the class group of $L$. Then
$\mathcal P^a = (\alpha)$ for some integer $\alpha$ of $L$.  Taking norms
down to $K$, we find that
$p^{f(\mathcal P,p) a}$ is principal.  Thus $m$ divides $a f(\mathcal P,p)$,
and hence $m/(m,f(\mathcal P,p))$ divides $a$, as claimed.
Answer: This is closely related to the class-field-theoretic type argument I mentioned in the other answer.  Here's a fast solution (if possibly not the most elementary).
Note that by class field theory, specifically properties of the Artin symbol, the order $m$ of $[p]$ equals the relative inertia degree of $p$ in the Hilbert class field $K^{(1)}$ of $K$, and similarly for the order of $[\mathcal{P}]$ and the residue degree of $\mathcal{}P$ in $L^{(1)}/L$.  Now consider the following diagram:
$$
\newcommand{\ra}[1]{\!\!\!\!\!\!\!\!\!\!\!\!\xrightarrow{\quad#1\quad}\!\!\!\!\!\!\!\!}
\newcommand{\da}[1]{\left\downarrow{\scriptstyle#1}\vphantom{\displaystyle\int_0^1}\right.}
%
\begin{array}{llllllllllll}
L & \ra{m':=\text{ order of }\mathcal{P}} & L^{(1)} \\
\da{f:=f(\mathcal{P}/p)} & & \da{}\\
K & \ra{m :=\text{ order of }p} & \,K^{(1)} \\
\end{array}
$$
Here the labels on each arrow are the inertia degrees of a prime above $p$ in each extension.  Now by multiplicativity of inertia degrees in towers, we have $m\mid m'f$, so $\frac{m}{(m,f)}\mid m',$ as desired.

(Apologies for the sloppy diagram, I've never jury-rigged an xypic on MSE or MO before.  Can anyone make those arrows "headless"?  And/or move the$f(\mathcal{P}/p)$ to the left of the arrow?)
Comment: Sure thing.  Happy number-theoring.
Comment: Makes sense. Thanks!
Comment: Excuse me, I am a little confused: As far as I know, the order of $P$ is equal to the order of its Frobenius, by the Artin symbol, and then is equal to the order of the decomposition group. So it is the product of $f$ and $e$, the ramification index. I guess it is assumed that $p$ is unramified, but I find no such indications. Thanks in any case in advance.
Answer: This is just a hint, that will hopefully help you realize where this $m/(m,f(\mathcal{P},p))$ comes from.
Let $m>1$ be a fixed integer and suppose that $a\in\mathbb{Z}$ is relatively prime to $m$. Then, for any $d\geq 1$, we have:
$$\operatorname{ord}(a^d) = \frac{\operatorname{ord}(a)}{\gcd(\operatorname{ord}(a),d)}.$$
Comment: Thanks a lot. I actually realized that 5 minutes after posting it :)).

Exercise from Marcus on class groups


Python S3 Boto generates Urls with SignatureDoesNotMatch Error

Question:         import boto
        from boto.s3.connection import S3Connection
        import requests

        conn = S3Connection('-----------------', '-------------------')
        snapsbucket = conn.get_bucket('snaps-snaps')

        for key in snapsbucket.list('a'):
            print key.name
            print key.generate_url(expires_in=90)

This will output a list of filenames and urls.
When I follow a url, I get the following xml:
        <Error>
        SignatureDoesNotMatch
        <Message>
        The request signature we calculated does not match the signature you provided. Check your key and signing method.
        </Message>
        <StringToSignBytes>
        47 45 54 0a 0a 0a 31 33 39 37 30 38 34 30 35 37 0a 2f 73 6e 61 70 73 2d 73 6e 61 70 73 2f 61 73 73 65 6c 69 6e 70 61 75 6c 5f 61 73 73 65 6c 69 6e 70 61 75 6c 7e 31 33 39 36 39 38 36 38 37 39 34 36 35 2e 6d 70 34
        </StringToSignBytes>
        <RequestId>2C2A6E1194BAAD85</RequestId>
        <HostId>
        ReNCy1k3OqBd2xyfA5tyixhD7MXnNACqBspsl61IAN7GSF1haK03cv4r6x6WHle/
        </HostId>
        <SignatureProvided>IlRoL9AZJZQYL4/L0wySexMBjnw=</SignatureProvided>
        <StringToSign>
        GET 1397084057 /snaps-snaps/asselinpaul_asselinpaul~1396986879465.mp4
        </StringToSign>
        <AWSAccessKeyId>--------------</AWSAccessKeyId>
        </Error>

Stuck here, any help much appreciated.
Answer: It turns out my filenames contained a tilde (~).
This would mess up the urls, thus the error.
Comment: This seems to be a bug in the boto library; see https://github.com/boto/boto/issues/2849 etc.


Filter an array of objects using an Observable filter

Question: I'm struggling to figure the correct way to filter an array of objects using RxJS 6.
Here's the scenario. I have users: User[], filter: FormControl, and another array of filteredUsers: User[]. What I would like to do is filter the list the users based on the value contained in the filter.  The only way I was able to figure this out was to use tap, and while this works, it just doesn't seem like the right way to do it...plus the whole list is "filtered out" until the filter control has its first valueChange.
this.filter.valueChanges.pipe(
  tap((term) => {
    this.filteredUsers = this.users.filter(u => u.name.indexOf(term) != -1)
  })).subscribe()

Any help would be greatly appreciated.
Answer: you're right that tap isn't the "right" way to do it... the right way is to do it in subscribe...
this.filter.valueChanges.pipe(startWith('')).subscribe(
  (term) => {
    this.filteredUsers = (term) ? this.users.filter(u => u.name.indexOf(term) != -1) : this.users;
});

and add in a blank check that doesn't filter, and a start with that kicks off the stream.  done and done.  Don't add complexity where you don't need it.  rxjs recommends side effects occur in your subscribe function, everything else SHOULD be transformative / functional, and setting a value on the controller is a side effect.
If you want to get really reactive, you can throw in an async pipe for good measure
this.filteredUsers$ = this.filter.valueChanges.pipe(startWith('')).tap(
  (term) => {
    return (term) ? this.users.filter(u => u.name.indexOf(term) != -1) : this.users;
});

then in HTML instead of
*ngFor="let user of filteredUsers"

do:
*ngFor="let user of filteredUsers$ | async"

the benefit here is automatic subscription cleanup and better support for onpush change detection.
Answer: Just move the tap function into the subscribe:
this.filter.valueChanges.subscribe((term) => {
    this.filteredUsers = this.users.filter(u => u.name.indexOf(term) != -1)
  });


element of a homotopy group

Question: I am having trouble understanding the idea of an element of a homotopy group. This is the definition from wikipedia:
In the n-sphere $S^{n}$ we choose a base point $a$. For a space $X$ with base point $b$, we define $\pi _{n}(X)$ to be the set of homotopy classes of maps $f:S^{n}\to X$
that map the base point a to the base point b. In particular, the equivalence classes are given by homotopies that are constant on the basepoint of the sphere.
So to my understanding $\pi_n(X)$ is created by taking all continuous map $f: S^n \rightarrow X$ such that $f(a) = b$ and then mod this under the homotopy equivalence relation. However, I do not understand the last sentence: the equivalence classes are given by homotopies that are constant on the basepoint of the sphere. What does it mean to be constant on the basepoint of the sphere? If $f$ and $g$ are homotopic, why must they be constant on the basepoint of the sphere?
Comment: $f$ is equivalent to $g$ iff there's a continuous map $F:S^n\times[0,1]\to X$  with $F(x,0)=f(x)\ \forall x$, $F(x,1)=g(x)\ \forall x$ and $F(a,t)=b \ \forall t$.
Comment: So then by this definition the equivalence classes are $[a] \in S^n$? So for example if $n = 1$, then the equivalence classes are $f : S^1 \rightarrow X \in [a]$ and $f(a)=b$?
Comment: I don't understand your question. See Luke's answer for a better exposition of the point I was making.
Answer: "Constant on the basepoint of the sphere" means constant in the "time" coordinate.  Recall a homotopy of maps $S^n\to X$ is a map $H:S^n\times [0,1]\to X$.  To say that $H$ is constant on the basepoint means that the function $t\mapsto H(a,t)$ is constant, where $a\in S^n$ is the basepoint.  The idea is that $H$ is a "continuous path" of maps $H_t:S^n\to X$ defined by $H_t(x)=H(x,t)$, and you want $H_t$ to map the basepoint of $S^n$ to the basepoint of $X$ for all $t$, not just $t=0$ and $t=1$ (so you have a "continuous path of basepoint-preserving maps").
Answer: To say the homotopy $F:S^n\times[0,1]\rightarrow X$ from $f$ to $g$ is constant on the basepoint of the sphere means that $F(a,t)=b\,\,\,\forall t\in[0,1]$, where $a$ is the chosen basepoint of the sphere and $b=f(a)=g(a)$ is the chosen basepoint of $X$.
A general homotopy needn't be constant on the basepoint of the sphere. For example, identifying $S^1$ with $\{z\in\mathbb{C}|1=|z|\}$, let $X=S^1$ and $1$ be the basepoint for $S^1$.
Let $f,g:S^1\rightarrow X=id_{S^1}$. So we have $1=a=b$ in the context of the definition you gave. Let $F:S^1\times[0,1]\rightarrow X;F(z,t)=e^{2i\pi t}z$.
Then clearly $f\simeq_Fg$, but $F(a,\frac{1}{2})=F(1,\frac{1}{2})=-1\neq1=b$.
Comment: So to clarify, different equivalence classes would be picking different base point of sphere and send it to the base point of $X$?
Comment: @CuriousAlpaca No, fix a base point of the sphere and of $X$, then the equivalence relation is on the set of maps $f:S^n\rightarrow X$, with $f\sim g$ iff $f$ is homotopic to $g$ via a homotopy that is constant on the basepoint of the sphere.

element of a homotopy group


CORS issue on a POST request using Flask + Typescript

Question: This is part of my python code
app/products/__init__.py
bp_products = Blueprint('products', __name__, url_prefix='/products')

@bp_products.route('', methods=['POST', 'OPTIONS'], endpoint='add')
@bp_products.route('/', methods=['POST', 'OPTIONS'], endpoint='add')
@json_response
def add():
    if request.json is None:
        abort(400, 'Request must be json')

    # Some logic here

    return product_schema.dump(product)

app/__init__.py
with app.app_context():
        # Some logic here
        CORS(app)

    from .products import bp_products
    app.register_blueprint(bp_products)

All dependencies were properly imported but I didn't add the code here.
For some reason, this code (note the trailing slash)
let response = await fetch(`${apiUrl}/products/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        asin: productAsin,
        process: 1,
      }),
    });

works properly but when I remove the trailing slash, it doesn't work, despite both routes were defined on my code
@bp_products.route('', methods=['POST', 'OPTIONS'], endpoint='add')
@bp_products.route('/', methods=['POST', 'OPTIONS'], endpoint='add')

I tried switching these routes positions, removing the rest of the routes on my code in case there was a conflicting one, removing all the code inside my method in case some code was failing there, specifying headers, methods and routes using CORS config options... none of my attempts were successful.
It's worth noting that this works when I use postman (so the route seems to be properly defined).
The solution may be in front of my eyes but I am not seeing it (it's worth noting I am new to Python).
Any help would be much appreciated.
Comment: From chrome console: `Access to fetch at 'http://127.0.0.1:5000/products' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.`

From flask debugger: `"OPTIONS /products HTTP/1.1" 415 -`
When the trailing slash is part of the url, this doesn't happen, and the `OPTIONS` request works just fine
`"OPTIONS /products/ HTTP/1.1" 200`
Comment: " but when I remove the trailing slash, it doesn't work," - what about it doesn't work? What is the network response code and data? Do you receive a particular error message? What makes you think it is CORS related?
Answer: This decorator @cross_origin() made the trick.
Once I added it, both routes started to work (with and without the trailing slash).
I am not sure why this is only necessary for the route without a trailing slash on it. If someone knows the reason, I am eager to know it.
Comment: I had the same problem with CORS and this post gave me the clue.  it was the trailing slash was not in the fetch and the route had one.  I didnt need OPTIONS method or the @cross_origin() decorator.  it was the routes that were wrong but it always gives the impression its CORS trowing you off.