Como usar função de comparação em um std::sort

Question: No código abaixo o programa deve ordenar o vector campanha se baseando na quantidade de votos de cada vereador:
#include <iostream>
#include <vector>

using namespace std;

struct Vereador
{
    string nome;
    int votos;
};

int main()
{
    vector<Vereador> campanha
    {
        { "Angelo Orlando", 6580 },
        { "Paulo Furini",   3985 },
        { "Augusto Jacob",  9025 },
        { "Chico Sardelli", 5900 }
    };

    sort( campanha.begin(), campanha.end(),
        []( Vereador x, Vereador y ){ return x.votos > y.votos; } );

    for( auto i: campanha )
        cout << "Candidato: " << i.nome << "\tVotos: " << i.votos << endl;

    return 0;
}

Eu estou com dúvida de como funciona essa função de comparação que é usada no sort na linha:
sort( campanha.begin(), campanha.end(),
                []( Vereador x, Vereador y ){ return x.votos > y.votos; } );

Quais argumentos estariam recebendo os parâmetros x e y? e como o sort iria usar o valor do retorno para ordenar o vector?
Comment: O _sorting algorithm_ utilizado pela função `sort` basicamente vai chamar a função que você passou. Se retornar `true`, considera-se o _primeiro_ parâmetro _menor_ que o segundo (ele virá antes no vetor). Se retornar `false`, considera-se o _primeiro_ parâmetro _maior_ que o segundo. É uma função genérica de comparação. Agora perguntar _quando_ essa função é chamada varia de algoritmo para algoritmo. Veja um _pseudo-código_ do [_quick sort_](https://en.wikipedia.org/wiki/Quicksort): onde é feita uma comparação é _provavelmente_ o local onde a sua _lambda_ seria chamada.
Comment: Devo salientar que não há garantia que a implementação de `sort` de fato utiliza o algoritmo _quick sort_. A especificação da linguagem (desde C++ 11) só postula a complexidade que `sort` deve assumir, `O(N * log(N))`.
Answer: Não sou um especialista em C++11, mas esse código tem algumas premissas que são tranquilas de entender.
O primeiro ponto aqui é em relação à sintaxe, []( Vereador x, Vereador y ){ return x.votos > y.votos; }. Isso é uma expressão lambda. Ela é uma função anônima criada unicamente para ser descartada, como se fosse uma variável sem maior importância, como a variável auto i que você criou no seu código.
Na documentação do próprio C++ sobre sort, você está usando a sobrecarga template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp );, onde você passa o iterador que marca o começo, o iterador que marca o fim e uma função de comparação. Na documentação, ele explica que comp é uma função que pega dois valores para comparar e retorna verdade se e somente se o primeiro argumento deve ficar a esquerda (ele é considerado "menor" segundo o critério de comparação).
Por exemplo:
auto comparador = [](Vereador x, Vereador y) { return x.votos > y.votos; };

Vereador angelo = { "Angelo Orlando", 6580 };
Vereador paulo = { "Paulo Furini",   3985 }

auto resultado = comparador(angelo, paulo);

O valor armazendo em resultado será true, justamente porque, ao ordenar, angelo deveria ficar a esquerda de paulo.

Com a questão do lambda fora do caminho e entendo o que é esperado do terceiro argumento, fica a questão de quais seriam os argumentos de fato passados para o comparador. Na real? Não importa muito o como, essa é a graça.
Para fazer uma ordenação absoluta, você só precisa ser capaz de comparar dois valores por vez. Tome, por exemplo, um insertionsort escrito com um comparador genérico e um iterador também genérico:

template<class RandomIt, class Comparador>
void insertionsort(RandomIt comeco, RandomIt fim, Comparador cmp) {
    for (RandomIt it = comeco + 1; it != fim ; it++) {
        for (RandomIt it2 = it; it2 != comeco; it2--) {
            RandomIt prev = it2 - 1;
            if (cmp(*it2, *prev)) {
              auto e = *it2;
              *it2 = *prev;
              *prev = e;
            }
        }
    }
}

Como seria chamado isso? Um exemplo:
int main() {
    std::vector<int> v = {3, 3, 2, 1};

    insertionsort(v.begin(), v.end(), [](int a, int b) { return a < b;});
    my_for_each(v.begin(), v.end(), [](int a) { std::cout << a << std::endl;}); // saída, cada número em sua própria linha: 1 2 3 3
    return 0;
}

Note que, ao chamar a minha função de ordenação, eu não me preocupei em como era o algoritmo de ordenação. Internamente ele poderia funcionar de qualquer jeito. Implementações comuns de ordenação normalmente incluem (mas não se limitam a):

TimSort
QuickSort
MergeSort

Eu escolhi insertionsort pela simples facilidade de implementação. Poderia usar um bubblesort:
template<class RandomIt, class Comparador>
void bubblesort(RandomIt comeco, RandomIt fim, Comparador cmp) {
    for (RandomIt it = fim - 1; it != comeco ; it--) {
        for (RandomIt it2 = comeco; it2 != it; it2++) {
            RandomIt next = it2 + 1;
            if (!cmp(*it2, *next)) {
              auto e = *it2;
              *it2 = *next;
              *next = e;
            }
        }
    }
}

Que de todo jeito a maneira de chamar seria exatamente a mesma (ajeitando, claro, para o nome da função):
int main() {
    std::vector<int> v = {3, 3, 2, 1};

    bubblesort(v.begin(), v.end(), [](int a, int b) { return a < b;});
    my_for_each(v.begin(), v.end(), [](int a) { std::cout << a << std::endl;}); // saída, cada número em sua própria linha: 1 2 3 3
    return 0;
}

Sobre coisas específicas do como o C++ faz as mágicas:

como os argumentos são passados para a função?

O C++ acessa o conteúdo do iterador. Eu posso pegar o conteúdo de um std::vector::iterator it usando o operador de derreferenciamento *it. Essa pode ser uma das estratégias usadas.
Eu tenho a suspeita que, na função lambda, declará-la como []( Vereador& x, Vereador& y ){ return x.votos > y.votos; } possa ser melhor na lida de objetos grandes, mas é mais suspeita do que por conhecimento consolidado ou prática.

como é usado o valor retornado para ordenar os valores?

Se você comparar um elemento a com o elemento b e retornar true, você sabe que a deveria vir antes de b. Se você pegou a mais próximo do começo do vetor, não precisa fazer nada; caso contrário, b é o elemento mais próximo do vetor, então precisa fazer o swap desses valores.
O retorno false é análogo, sempre tentando manter a ordem.

como ocorre a troca de posições, esse tal de swap?

Provavelmente eu creio que se use a função std::swap, mas funciona também fazendo uma troca de valores de modo mais tradicional. Isso é algo que pode ser feito de acordo com a implementação.
Answer: Questão 1

Quais argumentos estariam recebendo os parâmetros x e y?

x e y serão 2 instâncias de Vereador e a função será chamada sempre que o sort() precisar comparar dois Vereador, com os valores deles em x e y
em
 sort( campanha.begin(), campanha.end(),
        []( Vereador x, Vereador y ){ return x.votos > y.votos; } );

Veja o protótipo de sort() em CPP Reference

campanha é um vetor de Vereador então é isso que os iteradores vão retornar
    vector<Vereador> campanha
    {
        { "Angelo Orlando", 6580 },
        { "Paulo Furini",   3985 },
        { "Augusto Jacob",  9025 },
        { "Chico Sardelli", 5900 }
    };

Questão 2

como o sort iria usar o valor do retorno para ordenar o vector?

Para poder classificar um grupo de qualquer coisa é preciso poder comparar duas delas. Essa é a noção de ordem. E é isso que você está procurando. Por isso sort(), como qsort() em C, precisa da noção de <, de menor. Seja qual for a maneira que vai usar para classificar você precisa comparar os vereadores para saber qual vem antes de qual na ordem final.
Assim sort() não precisa saber o que está classificando, porque você diz como comparar dois elementos.
Se sua classe for trivialmente comparável, ou seja, se puder usar o operador < para comparar dois deles, pode omitir a função de classificação e usar apenas
 sort( campanha.begin(), campanha.end() );

Se puder usar ranges::sort() em C++20 pode escrever apenas sort(campanha) se a classe tiver o operador < e omitir os iteradores, classificando o vetor todo usando a noção de < para o que quer que tenha dentro do vetor. Imagine um vetor de int por exemplo.
Exemplos em C++
1. Implementando < para não precisar do terceiro parâmetro
struct Vereador
{
    string nome;
    int votos;

    friend bool operator< (const Vereador& um, const Vereador& outro)
    { return um.nome < outro.nome; };

};

Note que a partir disso um Vereador será menor que outro Vereador se o nome em ordem alfabética por menor. Podia ser o CPF se tivesse isso no registro, ou um ter mais votos que outro, ou menos.
Uma vez que implementou isso para a classe não precisa mais do terceiro parâmetro no sort() e pode escrever
    sort(campanha.begin(), campanha.end());

Então porque existe o tal parâmetro? Porque é mais dinâmico poder comparar na hora e se pode usar um critério diferente a cada chamada.
2. Usando functor para definir o outro parâmetro
Aqui se define o operador () para a classe Vereador. E o resultado dessa função é classificar os caras em ordem crescente de votos.
 struct Vereador
{
    string nome;
    int    votos;

    bool operator()(const Vereador& um, const Vereador& outro)
    { return um.votos < outro.votos; };

    friend bool operator<(const Vereador& um, const Vereador& outro)
    { return um.nome < outro.nome; };
};

E se pode escrever
    sort(campanha.begin(), campanha.end(), Vereador());

3. usando uma função qualquer para comparar Vereador
Em C++ pode usar free_functions, funções que não estão dentro de nenhuma classe, para fazer as comparações de que o sort() precisa.
struct Vereador
{
    string nome;
    int    votos;

    bool operator()(const Vereador& um, const Vereador& outro)
    { return um.votos < outro.votos; };

    friend bool operator<(const Vereador& um, const Vereador& outro)
    { return um.nome < outro.nome; };
};

const bool free_function( const Vereador& A, const Vereador& B)
{    return A.nome.length() < B.nome.length();};

E se pode escrever como em C
    sort(campanha.begin(), campanha.end(), free_function);

4. Usando uma função lambda como parâmetro
Na própria linha do comando, como no seu exemplo, se pode colocar o código da função. A menos de uma função simples, one-liner, usar o código misturado no meio da chamada a sort() pode ser ruim de ler, estilo javascript.
        []( Vereador x, Vereador y ){ return x.votos > y.votos; } );

E escrever então
    sort(campanha.begin(), campanha.end(),
        []( Vereador x, Vereador y ){ return x.votos > y.votos; } );

Um programa completo com todos os exemplos acima
Para ficar mais curto, implementando o operador left bit shift << para Vereador

    friend ostream& operator<<(ostream& saida, const Vereador& V)
    {
        saida << V.nome << "\tVotos: " << V.votos << "\n";
        return saida;
    }

Assim centraliza a formatação de Vereador e o texto fica mais legível:
    sort(campanha.begin(), campanha.end()); // operador < da classe
    cout << "\n\n==>\tdepois do sort, em ordem de nome\n";
    for (auto i : campanha) cout << i;

Separando a função lambda para ficar junto com os outros critérios de exemplo
Usando auto se pode levar a definição da comparação para o início do programa, onde estão as outras:
struct Vereador
{
    string nome;
    int    votos;

    bool operator()(const Vereador& um, const Vereador& outro)
    { return um.votos < outro.votos; };

    friend bool operator<(const Vereador& um, const Vereador& outro)
    { return um.nome < outro.nome; };

    friend ostream& operator<<(ostream& saida, const Vereador& V)
    {
        saida << V.nome << "\tVotos: " << V.votos << "\n";
        return saida;
    }
};

const bool free_function( const Vereador& A, const Vereador& B)
{    return A.nome.length()  y.votos; };

main() testando esses casos
Usando essas mudanças o código fica possívelmente mais fácil de ler:
int main(void)
{
    vector<Vereador> campanha
    {
        { "Angelo Orlando III", 6580 },
        { "Paulo  Furini Jr.",   3985 },
        { "Augusto Jacob",  9025 },
        { "Chico Sardelli Senior", 5900 }
    };

    cout << "==>\tOrdem original:\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end(), uma ); // lambda
    cout << "\n\n==>\tdepois do sort, em ordem decrescente de votos\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end()); // operador < da classe
    cout << "\n\n==>\tdepois do sort, em ordem de nome\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end(), Vereador()); // functor
    cout << "\n\n==>\tdepois do sort, em ordem crescente de votos\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end(), free_function); // free function
    cout << "\n\n==>\tdepois do sort, em ordem crescente de tamanho no nome\n";
    for (auto i : campanha) cout << i;

    return 0;
}

Saida do exemplo completo
==>     Ordem original:
Angelo Orlando III      Votos: 6580
Paulo  Furini Jr.       Votos: 3985
Augusto Jacob   Votos: 9025
Chico Sardelli Senior   Votos: 5900

==>     depois do sort, em ordem decrescente de votos
Augusto Jacob   Votos: 9025
Angelo Orlando III      Votos: 6580
Chico Sardelli Senior   Votos: 5900
Paulo  Furini Jr.       Votos: 3985

==>     depois do sort, em ordem de nome
Angelo Orlando III      Votos: 6580
Augusto Jacob   Votos: 9025
Chico Sardelli Senior   Votos: 5900
Paulo  Furini Jr.       Votos: 3985

==>     depois do sort, em ordem crescente de votos
Paulo  Furini Jr.       Votos: 3985
Chico Sardelli Senior   Votos: 5900
Angelo Orlando III      Votos: 6580
Augusto Jacob   Votos: 9025

==>     depois do sort, em ordem crescente de tamanho no nome
Augusto Jacob   Votos: 9025
Paulo  Furini Jr.       Votos: 3985
Angelo Orlando III      Votos: 6580
Chico Sardelli Senior   Votos: 5900

Usando seu código, apenas aumentei o tamanho de alguns nomes e testei com as funções de comparação descritas acima.
Espero que tenha entendido a mecânica disso.
O programa completo
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

struct Vereador
{
    string nome;
    int    votos;

    bool operator()(const Vereador& um, const Vereador& outro)
    { return um.votos < outro.votos; };

    friend bool operator<(const Vereador& um, const Vereador& outro)
    { return um.nome < outro.nome; };

    friend ostream& operator<<(ostream& saida, const Vereador& V)
    {
        saida << V.nome << "\tVotos: " << V.votos << "\n";
        return saida;
    }
};

const bool free_function( const Vereador& A, const Vereador& B)
{    return A.nome.length()  y.votos; };

int main(void)
{
    vector<Vereador> campanha
    {
        { "Angelo Orlando III", 6580 },
        { "Paulo  Furini Jr.",   3985 },
        { "Augusto Jacob",  9025 },
        { "Chico Sardelli Senior", 5900 }
    };

    cout << "==>\tOrdem original:\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end(), uma ); // lambda
    cout << "\n\n==>\tdepois do sort, em ordem decrescente de votos\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end()); // operador < da classe
    cout << "\n\n==>\tdepois do sort, em ordem de nome\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end(), Vereador()); // functor
    cout << "\n\n==>\tdepois do sort, em ordem crescente de votos\n";
    for (auto i : campanha) cout << i;

    sort(campanha.begin(), campanha.end(), free_function); // free function
    cout << "\n\n==>\tdepois do sort, em ordem crescente de tamanho no nome\n";
    for (auto i : campanha) cout << i;

    return 0;
}


Is there an equivalent of std::bind in Dart like there is for C++?

Question: Suppose I have something like this
void funct(int a ,int b)
{
    std::cout << a+b ;//3+2=5
}

in C++ we could bind a value to parameter to b so the callback will only have to pass in one parameter. Can we do this in dart ?
int main()
{
 auto f = std::bind(&funct,std::placeholders::_1,2); //pass b=2
 f(3);
}

Comment: It seems that it is possible. Look for [closure](https://www.dartlang.org/guides/language/language-tour#lexical-closures) or [partial application](https://japhr.blogspot.de/2012/01/partial-application-in-dart.html).
Answer: As mentioned in the comment below your question, you can accomplish this with a closure:
void funct(int a, int b) {
  print(a + b);
}

void main() {
  var f = (b) => funct(2, b);
  f(3);
}


Playing Guitar Tabs on Piano?

Question: I was wondering if anyone could possibly explain how I could somehow translate a guitar tab into notes on piano. Is there some sort of algorithm I can apply?
ex:

    e|---------------------------------|
    B|---------------------------------| Riff 1
    G|-5--5-5-5-5-5-5-5-5-5------------|
    D|-8--6-6-6-6-6-6-6-6-6------------|
    A|-7--7-7-7-7-7-7-7-7-7------------|
    E|---------------------------------|

What would this translate to on piano and how does one deduce this?
I think this means for example, G on the 5th fret, but what does that translate to?
Thanks!
Comment: An A on a guitar is an A on a piano.  There's no reason you can't just play the tab with a piano rather than a guitar.  If you don't know what notes are and are playing tabs merely by mapping the physical position, then you should learn the notes!
Answer: This image shows the note on the stave corresponding to each guitar string:

The lowest string is E, then A, D, G, B and E.
It might also be useful to refer to a map of the fretboard -- there's nothing there you couldn't work out from knowing the tuning of each string, and that each fret raises the pitch by a semitone:

Now, lets take first chord in your tab.
Seventh fret on A string, 8th on D and 5th on G. This means, that the chord consists of three notes: first 7 semitones up from A, then 8 semitones up from D, and 5 semitones up from G, which makes it E, Bb and C.

I think the easiest way for you would be just inputting guitar tab into any program (guitar pro; power tab; tux guitar etc), this will help you.
Answer: If we call middle C C4, then the open strings of the guitar are as follows:

e - E4
B - B3
G - G3
D - D3
A - A2
E - E2

From the appropriate open string note, go up the number of semitones indicated by the fret number to find the written note.
Eg.

e|---
B|---
G|-5-    is G3 plus 5 semitones = C4
D|---
A|---
E|---

One thing to look out for: alternate tunings. The above is for standard tuning. Some songs use an alternate tuning, which should always be indicated on the tab chart. Just change the open string notes to whatever's indicated and apply the same principle.
Answer: Here is the standard notation for your example.

Playing Guitar Tabs on Piano?


Getting garbage characters after transfering file contents via UDP

Question: Develop a client/server based application using UDP to execute the program at remote server. i.e. the client sends the executable file to the server, server executes the file , stores the result in a
file and sends back to the client.
I have coded 2 files
//sends an executable file name to the server; server executes it
//an echo program; this is the client's code
<code>      #include <sys/types.h>
      #include <sys/socket.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <netinet/in.h>
     #include <arpa/inet.h>
    #include<fcntl.h>
    #include<unistd.h>
     #include<stdlib.h>
     void usage(const char *progname)
      {
        fprintf(stderr, "Usage: %s <server-IP> <server-port>\n",
                progname);
       }
     int main(int argc, char *argv[])
      {

      if(argc != 3)
      {
       usage(argv[0]);
       exit(1);
      }
     int len, result, sockfd,clilen;
       int n;
      struct sockaddr_in seraddr;
      char buf[310], buf1[500]={0};
      sockfd = socket(AF_INET, SOCK_DGRAM, 0);
       if(sockfd<0)
             { // Check error condition
              perror("socket failed"); return -1;
             }

     bzero(&seraddr, sizeof(seraddr));

    seraddr.sin_family = AF_INET;
    seraddr.sin_addr.s_addr = INADDR_ANY;
    seraddr.sin_port=htons(atoi(argv[2]));
    int ap;

            clilen=sizeof(struct sockaddr_in);
    //read contents of file into buf; send to server
    int fd = open("Executable_Client.c", O_RDWR);
        int n1 = read(fd, buf, sizeof(buf));

         n = write(sockfd,buf,n1);
         ap=sendto(sockfd,buf,n1,0,(const struct sockaddr
         *)&seraddr, sizeof(struct sockaddr));

       int n2 = recvfrom(sockfd, buf1, sizeof(buf1), 0, (struct
                         sockaddr *)&seraddr, &clilen);
        n = read(sockfd,buf1, n2);

        printf("The output is: %s\n", buf1);
        return 0;
        }
</code>
and
Server.c
//this program accepts an executable file from the client, and executes it
//an echo program; this is the server's code
<code>      #include<stdio.h>
      #include<string.h>
      #include<sys/types.h>
      #include<sys/socket.h>
      #include<netinet/in.h>
      #include<fcntl.h>
      #include<unistd.h>
      #include<fcntl.h>
      #include<unistd.h>
      #include<stdlib.h>

      void usage(const char *progname)
      {
        fprintf(stderr, "Usage: %s <server-port>\n", progname);
      }

      int main(int argc, char *argv[])
      {

       if(argc != 2)
       {
         usage(argv[0]);
         exit(1);
       }

    int sockfd, newsockfd,portno, client, n, ans,clilen;
    char buf[310], buf1[256] = {0};

    struct sockaddr_in seraddr, cliaddr;
    int i, value;
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if(sockfd<0)
    {
     perror("socket failed"); return -1;
     }

     int size=sizeof(struct sockaddr);
      bzero(&seraddr,size);

    seraddr.sin_family = AF_INET;
    seraddr.sin_addr.s_addr =inet_addr("127.0.0.1");
    seraddr.sin_port = htons(atoi(argv[1]));

    int a=bind(sockfd, (struct sockaddr *)&seraddr, size);
            if (a<0)
            {
             perror("bind"); close(sockfd); return -1;
            }

             clilen=sizeof(struct sockaddr_in);

    int fd1 = open("Executable_Server.c", O_RDWR);
    //write contents into Executable_Server.c
    int n1 = recvfrom(sockfd, buf, sizeof(buf), 0, (struct
                      sockaddr *)&seraddr, &clilen);
            n = write(fd1, buf, n1);

    system("gcc Executable_Server.c -o execute.out");
    system("./execute.out>Output.txt");//>"Output.txt");

    //read contents from Output.txt
    int fd = open("Output.txt", O_RDWR);
    int n3 = read(fd, buf1, n1);

    //send contents to client

    n = write(sockfd, buf1,n3);
            n = sendto(sockfd, buf1, n3, 0, (const struct
                       sockaddr *)&seraddr, sizeof(struct
                       sockaddr));
   }
</code>
also, Executable_Client.c 's code is
//this file's executeable will be sent to the server, from the client; this file reads the contents of a file
<code>      #include<stdio.h>
      #include<stdlib.h>
       int main()
       {
        int a, b, c;
         a = 3;
         b = 4;

        c = a+b;

        printf("a+b = %d\n", c);
              return 0;
      }
</code>
Upon executing,
in Executable_Server.c,besides the actual code of Executable_Client.c., a lot of garbage value is also  present. As a result the terminal window in ubuntu 12.04 shows a lot of errors mentioning stray symbols which appear during the execution part.
Can anyone suggest the reason behind this anomaly?
Comment: You do **not** want to use UDP. It's such a wrong thing to do it is not even interesting. Go with TCP.
Comment: I dont have that option. I can't change the question,
Comment: If you don't have the option to use TCP instead you must handle packet reordering, packet loss and packet duplication in your code which you don't. TCP does this for you whereas UDP not.
Comment: I was getting the output with this code earlier. I made some dumb modification  and then I started having problems. Its a very small file, is packet reordering, really essential?
Answer: The code is wrong in various places. Just to mention the most obvious from a short look:
You mix recvfrom with read and try to read the same data (same with mixing sendto and write later).
<code>   int n2 = recvfrom(sockfd, buf1, sizeof(buf1), 0, (struct
                     sockaddr *)&seraddr, &clilen);
    n = read(sockfd,buf1, n2);
</code>
And you print out the buffer independent of amount of data you've actually received. This will of course print out any junk data which were in the buffer before the read and which where not overwritten by the read.
<code>    printf("The output is: %s\n", buf1);
</code>
And of course is a bad idea to do such things with UDP as long as you don't care about packet reordering, packet loss and packet duplication.
Comment: Thanks :). I was trying it since such a long time. I commented out the read line and i changed the printf statement to match printf("%.*s", stringLength, pointerToString);


RDP from Mac fails

Question: Situation:

4 Windows 2016 RDS servers in a collection
1 Windows 2016 server that serves as RD Gateway and connection broker.

Authentication is done via NAP/Radius using a 2FA (Microsoft Multi-Factor Authentication).
Connection using Windows works just fine, either via RD Web Access in Internet Explorer, a custom RDP File (adding loadbalanceinfo:s:tsv://MS Terminal Services Plugin.CollectionName) or via RemoteApp and Desktop Connections. All fine (and my users like the flexibility).
Now the Mac. Using the latest version of the Microsoft Remote Desktop App (https://itunes.apple.com/us/app/microsoft-remote-desktop-10/id1295203466)
Remote Resources kind of works. Users get multiple authentication prompts (for the RD Gateway and the RDS server).
I found this article (https://docs.microsoft.com/en-us/windows-server/remote/remote-desktop-services/clients/remote-desktop-uri) for creating an RDP uri.
rdp://promptcredentialonce=i:1&gatewayusagemethod=i:2&Use%20redirection%20server%20name=i:1&full%20address=s:connectionbroker.contoso.com&gatewayhostname=s:rdgw.contoso.com&loadbalanceinfo=s:tsv%3A%2F%2FMS%20Terminal%20Services%20Plugin.1.CollectionName&screen%20mode%20id=i:2
The uri works fine on iOS, single logon prompt and I get connected. This does not work on the Mac, giving either an Port reset by peer error on the old version of the RDP client (v8) or an access denied error in the new MS RDP client (v10).
Why won't this work on the Mac? It should be supported as far as I can see. And seeing the uri works fine on iOS it seems that is ok.
Comment: Have you checked your AA server's logs to see if there are actual authentication failures with the Mac?
Answer: Well apparently this issue can be fixed by adding a DefaultTsvUrl value in de registry of the RDS Broker server.  This redirects incompatible RD clients to a default collection.
See: https://blogs.technet.microsoft.com/askperf/2015/06/11/walkthrough-on-session-hint-tsvurl-on-windows-server-2012/
1. Start Registry Editor (Regedit.exe).

2. Locate and then click the following key in the registry:

HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\ClusterSettings

3. On the Edit menu, click Add Value, and then add the following registry value:

Value name: DefaultTsvUrl
Data type: REG_SZ
Value data: tsv://<TSVURL>

NOTE: This is being suggested as an alternate/workaround when you do
  not have upgrading the client as an option. It has the following
  caveats that one should be aware of:
This would only be read when the client is unable to understand the
  tsvurl sent in the RDP file (from the remote app) and thus does not
  present the tsvurl to connection broker. Whenever such a client comes
  the DefaultTsvUrl sends it to one single collection as specified in
  the registry value. DefaultTsvUrl can only point to one single
  collection only and thus you may want to plan and create a single
  collection for non compatible clients that has all their required apps
  in it. There is no provision of defining multiple collections in this
  registry so if you want to use incompatible clients over multiple
  collections then it won't be possible. In case you change that
  collection, you will have to change the defauDefaultTsvUrl lttsvurl
  registry value as well. This registry is only a workaround for tsvurls
  and will not work if the clients are not compatible with remoteapps
  itself. It is only for providing a workaround for clients that were
  able to access remoteapps earlier in Windows 2008/R2 but cannot access
  them through collections as explained in the section "Change in the
  way we connect in 2012 -Session Hint / TSVUrl".

So this also work for Windows 2016. Why the new RDP client for the Mac seemingly ignores the loadbalanceinfo=s: info is unkown, it should be supported.
Also this is not really a solution but more a workaround but good enough for now.

RDP from Mac fails


Understanding the rhythmic structure of a song

Question: I have played drums for a few months. Currently, I play for myself. I do exercises from stick control, but I also want to 'play along' to songs.
Given a song A, how do I start playing along? By ear? Make a sketch of its basic time signature?
Comment: Before anything, first listen to the bass guitar. It's the connection rod between the locomotive(you) and the luxury cabins(lead, singer etc.) and mostly(of course with exceptions) producers arrange things accordingly.
Answer: There are a few different levels here. One of the things you can practice are "Grooves", for example, those included with the Vic Firth Groove Essentials packages. That will give you some starting places based on the style of the music, and it's a lot easier to learn from written-out grooves than to decode every little thing by ear.
You'll also need to figure out the overall form of the song. If you "know" the song already, say, you know exactly how it goes and might be able to sing along, you probably already have a concept of the form. This might be something like:

4-bar intro, 32-bar A section, 8-bar bridge, 32-bar B section, end

It doesn't have to be formalized like that, but if you're having trouble figuring out the large-scale structure of a song, it can help to put it down in writing. You might have a slightly different groove for each section, or not--use your ears to figure out what changes.
If you can play some relevant grooves and you know the song form, that should be enough to get you started. Depending on how complicated the song is, transitions between sections might take a little more work.

A large part of drumset playing in certain styles of music is improvisational, so training your ear by learning drumset grooves by ear or transcribing them can be very useful.
Now, another approach to this is to find books of drumset parts that have been transcribed by a professional. These are often published for the express purpose of having people buy them to play along with the songs, and often include a recording or remix with the drums subtracted.
Comment: @user29163 If you are good with notation, or want to learn it, then absolutely. If you only learn aurally then it's likely to be frustrating, but if you want to work on written music literacy and have trouble defining the rhythms that you hear, it's incredibly helpful.
Comment: Wow, great information, thanks! Found some of this stuff on youtube too.

Is there much learning value in transcribing rhythms?
Answer: One very neat trick a teacher of mine taught me is to start transcribing a new song using personal symbols for each part. For example: a dot for every bar of the Intro, then a square for the Verse, and a triangle for the Chorus. It's a very quick way for start grasping the overall structure, however with more complex songs you can start putting little modifiers on each symbol. E.g.: a triangle with one stripe for the  first verse, and then a triangle with two stripes for the second Verse because it's the same groove but a little different.
This modifier idea is nice because you can recognize that even when the groove has some differences, the overall idea is pretty much the same - and afterwards you may want to add your own little nuances to that.
Then, you begin learning how to write sheet music for drums (which is very helpful, and I recommend a lot!), you can complement that early notation with a little "dictionary" thing where you explain on a footnote the meaning of each symbol.
Of course it's a very simple technique for writing music, which is quicker than writing a whole sheet music, but has less "expression power" than that. You'll find that there's always a trade-off, and sometimes one will be more appropriate than the other.


C++ How to parse the output of a structured git log into an object

Question: Problem: parse the output of git log, which has a structured commit message, into an object.
This is what the log looks like for this particular directory:
commit 7df03ac69f27f80887cc588ab7bec7e38a42d3db
Author: John Doe <email@example.com>
Date:   Thu Apr 6 19:43:18 2017 +0200

    VAL_A "Something"
    VAL_B "Goodbye"
    OPTIONALVAL_1 "Hello World \n"

commit 9d9c69f2798778yyuyuu6786767tc7e38a42d3db
Author: John Doe <email@example.com>
Date:   Thu Apr 6 19:43:18 2017 +0200

    VAL_A "Hello World"
    VAL_B "Goodbye World"
    OPTIONALVAL_2 "Hello again World \n"

commit 666669f2798778yyuyuu6786767tc7e38a42d3db
Author: John Doe <email@example.com>
Date:   Thu Apr 6 19:43:18 2017 +0200

    VAL_A "Hello World"
    VAL_B "Goodbye World"

Where each commit is to be parsed into an object which has member variables git_commit_hash, VAL_A, VAL_B, OPTIONALVAL_1, and OPTIONALVAL_2. The optional values can be empty but the VAL_A and VAL_B cannot.
My approach:

Dump the git log output into a temporary file.
Read the file line by line, if it starts with the word "commit" then save the characters after the space into git_commit_hash of a new object.
Skip the next three lines.
Save the two mandatory VAL_A and VAL_B values.
Since the values may overflow to the next line, just keep going down, check if either OPTIONALVAL_1 is set and/or OPTIONALVAL_2 at the beginning of the line, and if so, save it.
Stop parsing the current object once the word "commit" is reached. Create a new object then repeat 1-5.

This is a brute force approach which works somewhat, but has no flexibility. I was wondering if anyone could point me towards a more elegant solution or a c++ or boost library. Thanks.
Comment: How about creating a struct or class that holds all the information, no skipping anything.  Then it is as simple as picking out of the struct the information you need.  One pass reading the file into the array, vector, list, whatever of the structs, and then everything is memory based, not disk based.
Answer: you could use your own formatting of the git log using pretty formats like this:
git log --pretty=format:"<your formatting>"

If you put each element in an easy to parse way (e.g. define an xml with the data you need and then use boost::property_tree to extract the data) you could easily read the file and exactly know which information is where without parsing the whole log.
More info in this thread: Git log output to XML, JSON, or YAML?


what are the alternative open source tools for PredictionIO?

Question: PredictionIO is good to be enough for content discovery and recommendation but it seems  it does not support classification. Then I should use a different tool then Prediction IO for my prediction server. Do you know good alternatives?
I know Google Prediction Server, Azure ML, BigML and looking for more alternatives to compare them.
Best :)
Answer: Depending on urgency I would recommend you to wait for the next release of PredictionIO ;)
It will have much better support for building custom engines (e.g., classification) and algorithms. You can subscribe to our newsletter at http://eepurl.com/u4OEH to catch the release announcement.
If you can't wait you can implement classification methods provided by some of the open source ML libraries such as Mahout, scikit-learn, Weka or the ML-as-a-service providers you mentioned.
Thomas
Comment: I would comment on this answer, @tstonez, but I can't.
On the next release of PredictionIO, how soon do you suppose will it come out?
Comment: This is possible as of recently released version 0.8.x, [see announcement](https://groups.google.com/d/msg/predictionio-user/ay_AxmekvLA/YdZk_ZaHlGYJ) on our user group. Though depending on use case you might want to wait for "engine template" for your use case (e.g., classification should be ready very soon you can [track issue/ticket on our public JIRA](https://predictionio.atlassian.net/browse/PDIO-352)).


Google Geocoding XML response removes apartment/suite numbers

Question: When using the Geocode API it seems that any embedded apartment or suite number in the original address is removed in the XML response. This makes it impossible to use the returned address as a "corrected" or "standardized" format to save.

Is there a way to preserve the address information?
Secondly, as in this case, the "apt B" represents a distinct building from "A,C,D,E, etc." and hence a different rooftop geocode.

Any help appreciated
Sending the following address: 1135 Thomas Ln. Apt B, Hixson, TN 37343
to the following URL (key removed) "https://maps.googleapis.com/maps/api/geocode/xml?address=[ADDRESS]&key=[KEY]"
results in the following response:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>street_address</type>
  <formatted_address>1135 Thomas Lane, Hixson, TN 37343, USA</formatted_address>
  <address_component>
   <long_name>1135</long_name>
   <short_name>1135</short_name>
   <type>street_number</type>
  </address_component>
  <address_component>
   <long_name>Thomas Lane</long_name>
   <short_name>Thomas Ln</short_name>
   <type>route</type>
  </address_component>
  <address_component>
   <long_name>Hixson</long_name>
   <short_name>Hixson</short_name>
   <type>neighborhood</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Chattanooga</long_name>
   <short_name>Chattanooga</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Hamilton County</long_name>
   <short_name>Hamilton County</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Tennessee</long_name>
   <short_name>TN</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>United States</long_name>
   <short_name>US</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>37343</long_name>
   <short_name>37343</short_name>
   <type>postal_code</type>
  </address_component>
  <address_component>
   <long_name>3744</long_name>
   <short_name>3744</short_name>
   <type>postal_code_suffix</type>
  </address_component>
  <geometry>
   <location>
    <lat>35.1448870</lat>
    <lng>-85.2471100</lng>
   </location>
   <location_type>ROOFTOP</location_type>
   <viewport>
    <southwest>
     <lat>35.1435380</lat>
     <lng>-85.2484590</lng>
    </southwest>
    <northeast>
     <lat>35.1462360</lat>
     <lng>-85.2457610</lng>
    </northeast>
   </viewport>
  </geometry>
  <partial_match>true</partial_match>
 </result>
</GeocodeResponse>

Comment: It seems you need the Geocoding API get to Apartment level, you may read here:https://geonet.esri.com/thread/26594
Answer: The trouble you are experiencing goes back to the core philosophy and use case goals for the Google Geocoding API: identify the latitude/longitude coordinate of a structure or facility and plot it on a map. Secondary information (suite, apartment, etc.) is generally not necessary to fulfill that goal and is thus discarded or overlooked. Delivery points that have a structure per secondary number, e.g. an entire building for Suite 100 and another for Suite 200 are not particularly common and seem to fall outside of the intended users of the Google Geocoding API.
Furthermore, the API is an "address approximation" tool that guesses where an address might be. For example, if 121 Main Street has a building and 125 Main Street does too, but 123 Main Street isn't real, it will plot the address right between 121 and 125 as if it were there, even when the address doesn't exist.
If you're looking to verify the address (with or without secondary information) to make sure it's real and then plot it on a map, there are a number of services (both free and paid) that can offer this behavior.  A simple Google search for something like "address verification" will give you a number of results for organizations that offer verification along with geocoding.
If the geocoding resolution from these services isn't good enough for your business needs, you will still want to have a cleaned address because it will then allow you to pipe those cleaned and verified addresses to another service--perhaps NavTeq--to get rooftop level data for locations that have entire buildings dedicated to secondary number (suite, apartment, etc.). Note that providers such as NavTeq are often incredibly expensive, so only you can make the judgement call if your business requirements truly demand the expense of ultra-precise resolution.
In the interest of full disclosure, I am the founder of SmartyStreets and we provide address verification and geocoding services. We're happy to help if you have additional questions.
Answer: If you can request a json response instead of an xml response, it preserves the 'Apt B' data in
"types" : [ "subpremise" ]

subpremise indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a
common name.

[1135 Thomas Ln. Apt B, Hixson, TN 37343] as a json response..
"https://maps.googleapis.com/maps/api/geocode/json?address=[ADDRESS]&key=[KEY]"

returns:
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "b",
               "short_name" : "b",
               "types" : [ "subpremise" ]
            },
            {
               "long_name" : "1135",
               "short_name" : "1135",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Thomas Lane",
               "short_name" : "Thomas Ln",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Hixson",
               "short_name" : "Hixson",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Chattanooga",
               "short_name" : "Chattanooga",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Hamilton County",
               "short_name" : "Hamilton County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tennessee",
               "short_name" : "TN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "37343",
               "short_name" : "37343",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "3744",
               "short_name" : "3744",
               "types" : [ "postal_code_suffix" ]
            }
         ],
         "formatted_address" : "1135 Thomas Ln, Hixson, TN 37343, USA",
         "geometry" : {
            "location" : {
               "lat" : 35.144887,
               "lng" : -85.24711000000001
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 35.1462359802915,
                  "lng" : -85.24576101970851
               },
               "southwest" : {
                  "lat" : 35.1435380197085,
                  "lng" : -85.24845898029152
               }
            }
         },
         "place_id" : "EiUxMTM1IFRob21hcyBMbiwgSGl4c29uLCBUTiAzNzM0MywgVVNB",
         "types" : [ "subpremise" ]
      }
   ],
   "status" : "OK"
}

Comment: Noteworthy: it is syntax-related, because it will return subpremise for `21 Avenue de New York, apartment 1, Paris, France` but NOT for `21 Avenue de New York 1, Paris, France`. Does not work with `block_number/apartment_number` syntax.
Answer: Yes, but neither XML nor JSON know the difference between UNIT B and APT BBBB. They just echo the unit-I-D, and that regardless of the unit type. What would be helpful is a geocoding API that would return the unit type, if given a unit-I-D. For example, put in "100+Biscayne+Ave+B+33606 and get back the formatted address "100 Biscayne Ave Apt B, Tampa, Florida 33606"


Scale and Save Images (AttributeError: 'NoneType' object has no attribute 'shape')

Question: I'm trying to scale and save a thousand images to a directory.
I succeeded to resize images. However, errors occur while saving.
Code is below. Help me pls.
import cv2
import numpy as np
import os

def scaling_shirink(addr):
    img = cv2.imread(addr)
    height, width = img.shape[:2]
    shrink = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
    cv2.imshow('Shrink', shrink)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

count = 0
IMAGE_DIR_BASE = 'C:/ClassShared\Data/CM_ML_IMG_181011/CASE_01/FPS_10_PNG'
image_file_list = os.listdir(IMAGE_DIR_BASE)
for file_name in image_file_list:
    image = scaling_shirink(IMAGE_DIR_BASE + '/' + file_name)
    cv2.imwrite('C:/ClassShared\Data/CM_ML_IMG_181011/CASE_01/34_sdetect_db1/' + '_' + "%04d" % (count) + '.png', image)
    count = count + 1

Error messages are as follows.
Traceback (most recent call last):
  File "C:/PycharmProjects/TS_S/Scailing.py", line 19, in <module>
    image = scaling_shirink(IMAGE_DIR_BASE + '/' + file_name)
  File "C:/PycharmProjects/TS_S/Scailing.py", line 8, in scaling_shirink
    height, width = img.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'

I don't understand why it says
    AttributeError: 'NoneType' object has no attribute 'shape'
Comment: `cv2.imread(addr)` returned `None`.  Are you sure `addr` is correct?  Are there any non-image files in that directory?
Comment: sure its correct and if I run without for statement, then it run well.
Comment: The above code is a little wrong, and the return of the scaling_shirink function is shirink.
Comment: If it's wrong, then fix it.  We can't help if you don't show us the real code.
Comment: I solved this porblem haha it was simple thing! thx for answering John :)
Answer: EDIT:
Check if the image path is correct and if it its in fact a image with the formats accepted by Opencv. Because if your path is wrong the img = cv2.imread(addr) will return None and height, width = img.shape[:2] will throw an error
Also, your function scaling_shirink() is returning None.
To fix it, just change it to the function below:
def scaling_shirink(addr):
    img = cv2.imread(addr)
    height, width = img.shape[:2]
    shrink = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
    cv2.imshow('Shrink', shrink)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    #this return was missing
    return shrink

That should work!
Comment: This is not the problem that is causing the error (although it is another problem for OP); `img.shape` is throwing the error before the `return` statement would even happen because the `imread()` function is returning `None`.
Comment: @AlexanderReynolds you are right! Altough the lack o return in the function is also a problem. Thanks for the tip


Web Load Test with MVC route parameters creates many instance URL's

Question: I have a web test for the following request:
<code>{{WebServer1}}/Listing/Details/{{Active Listing IDs.AWE2_RandomActiveAuctionIds#csv.ListingID}}
</code>
And I receive the error message:

The maximum number of unique Web test request URLs to report on has been exceeded; performance data for other requests will not be available

because there are thousands of unique URL's (because I'm testing for different values in the URL).  Does anyone know how to fix this?
Comment: Google provides lots of answers. Read about "reporting names".
Comment: I am using reporting names, and the individual URL's aren't showing up anymore, but it's still warning me that there are too many instance URL's...  Thank you though.
Comment: Visual Studio has lots of poorly documented customisation options available via registry and configuration files. Careful web searching *might* find a way of increasing the limit. Perhaps asking via Microsoft's own forums might get an answer.
Answer: There are a few features within Visual Studio (2010 and above) that will help with this problem.  I am speaking for 2010 specifically, and assuming that the same or similar options are available in later versions as well.
1.  Maximum Request URLs Reported:
This is a General Option available in the Run Setting Properties of the load test.  The default value set here is 1,000.  This default value is usually sufficient... but not always high enough.  Depending on the load test size, it may be necessary to increase this.  Based on personal experience, if you are thinking about adjusting this value, go through your tests first and get an idea of how many requests you are expecting to see reported.  For me, a rough guideline that is helpful:
*number_of_request_in_webtest * number_of_users_in_load_test = total_estimated_requests*
If your load test has multiple web tests in it, adjust the above accordingly by figuring out the number of requests in each indvidual test, sum that value up, and multiply by the number of users.
This option is more appropriate for large load tests that are referencing several web tests and/or have a very high user count.  One reference for a problem|resolution use-case of this option is here:
https://social.msdn.microsoft.com/Forums/en-US/ffc16064-c6fc-4ef7-93b0-4decbd72167e/maximum-number-of-unique-web-test-requests-exceeded?forum=vstswebtest
In the specific case mentioned in the originally posted question, this would not resolve the problem entirely.  In fact, it could create a new one, where you end up running out of virtual memory. Visual Studio will continue to create new request metrics and counters for every single request that has a unique AWE2_RandomActiveAuctionIds.
2.  Reporting Name:
Another option, which @AdrianHHH already touched on, is the "Reporting Names" Option.  This option is found in the request properties, inside the web test.  It defaults to nothing, which in turn, results in Visual Studio trying to create the name that it will use from the request itself.  This behavior creates the issue you are experiencing.
This option is the one that will directly resolve the issue of a new request being reported for every unique request report.
If you have a good idea of the expected number of requests to be seen in the load test (and I think it is a good idea to know this information, for debugging purposes, when running into this exception) a debugging step would be to set the "Maximum Request URLs Reported" DOWN to that value. This would force the exception you are seeing to pop up more quickly.  If you see it after adjusting this value, then there is likely a request that is having a new reported value generated each time a virtual user executes the test.
Speaking from experience, this debugging step can save you some time and hair when dealing with requests that contain sessionId, GUID, and other similar types of information in them.  Unless you are explicitly defining a Reporting Name for every single request... it can be easy to miss a request that has dynamic data in it.
3.  Record Results:
Depending on the request, and its importance to your test, you can opt to remove it from your test results by setting this value to false.  It is accessed under the request properties, within the web test itself.  I personally do not use this option, but it may also be used to directly resolve the issue you are experiencing, given that it would just remove the request from the report all together.
A holy-grail-of-sorts document can be found on Codeplex that covers the Reporting Name option in a small amount of detail. At the time of writing this answer, the following link can be used to get to it:
http://vsptqrg.codeplex.com/releases/view/42484
I hope this information helps.


Dynamically creating an SQL query with many ANDs and ORs

Question: I have a .NET Forms application that is a tracking system for manufacturing. I have a DataGridView and several ListViews with checkable items to filter the data table. Filters include part number, charge number, current location, etc. There are 9 ListViews and 2 TextBoxes (inputs are heavily checked). Right now I am using a For loop on the checked items to add them to the Where clause of an SQL query. I am worried that my queries might become very inefficient.
The query includes 13 joins and the main table I am querying has about 2,000 rows, but I can see it getting to 100,000 over the next few years.
string query = @"SELECT top 1000 [column names] FROM [table names and joins] ";

List<string> filters = new List<string>();

//
// Part Number
//
if (ListViewPartNumber.CheckedItems.Count != 0)
{
    string PartNumberFilterString = " ( ";
    for (int i = 0; i < ListViewPartNumber.CheckedItems.Count; i++)
    {
        int PN_ID = ListViewPartNumber.GetCheckedValue( i );
        PartNumberFilterString += "SubAssembliesTable.PN_ID  = " + PN_ID;
        if ( i < ListViewPartNumber.CheckedItems.Count - 1 )
            PartNumberFilterString += " OR ";
    }
    PartNumberFilterString += " ) ";
    filters.Add(PartNumberFilterString);
}

It adds to the filter list for each listview that has items checked. Then it combines them into one string for the database query.
//
// Create filter string
//
for ( int i = 0 ; i < filters.Count ; i++ )
{
    if ( i == 0 ) query += "\r\n where ";
    query += filters[ i ];
    if ( i < filters.Count - 1 ) query += " AND ";
}

query += " \r\nORDER BY [ColumnName]  desc ";

It works fine, I haven't noticed any performance issues, but I am worried that I am doing this the completely wrong way. The query could end up with dozens of ANDs and ORs.
Comment: Why not create a test table with 250k records and run the queries against that? Then you'll know whether it's a problem or not.
Comment: This sounds more like a Database Design then a C# question. I added the respective tags. But really, we need some information on how the table looks to give any actually advice. If your server supports it, you can turn some of the more common combinations into a View. That would keep the query readable, and would allow the Server do to sensible caching without running into out-of-date data. But if you got **thirteen** joins, somethjing sounds very wrong.
Comment: @Christopher I think you are right about using a view to eliminate all of the joins. But, that wouldn't solve the problem of all of the ANDs and ORs in the where clause.
Comment: @MikePennie basically you could build your own query and translate them to SQL string query, it might spend time but it's interested. Check Azure Storage Table query builder `TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "RawMaterial");` [Read more](https://vkinfotek.com/azureqa/how-do-i-query-azure-table-storage-using-tablequery-class.html). Otherwise, finding 3rd party [SQL query builder](https://github.com/sqlkata/querybuilder) for time-saving
Answer: Looks like the list boxes contain the lines of multiple reference tables

check that corresponding foreign keys columns are indexed (excluding non-selective columns like "sex" or "enabled" which have 2-3 unique values)
use the code snippets like SubAssembliesTable.PN_ID IN (id1, id2, .. idN) instead of SubAssembliesTable.PN_ID=id1 OR SubAssembliesTable.PN_ID=id2 ...
use rather query parameters to avoid SQL injection attack
add some performance tests to ensure required response time in concurrent mode

You can also have a look on "Programming with databases" book which contains more detailed explanations on the topics above.


How to join general string to every first column of every sub row

Question: I want to join every first general string in the case below "ADMIN" and "DB" to the data which they represent and the place which will they take to be every time on the first column.
Example:
ADMIN
                         ADMIN_DB         Running          1          0          1          0          0          0         80
                         ADMIN_CATALOG    Running          0          0          1          0          0          0        452
                         ADMIN_CAT        Running          0          0          1          0          0          0         58
DB
               SLAVE_DB    Running          2          0          3          0          0          0         94
               DB_BAK      Running          1          0          1          0          0          0         54
             HISTORY_DB    Running          0          0          1          0          0          0         40
         HISTORY_DB_BAK    Running          0          0          1          0          0          0         59

Expectation:
ADMIN ADMIN_DB         Running          1          0          1          0          0          0         80
ADMIN ADMIN_CATALOG    Running          0          0          1          0          0          0        452
ADMIN ADMIN_CAT        Running          0          0          1          0          0          0         58
DB SLAVE_DB            Running          2          0          3          0          0          0         94
DB DB_BAK              Running          1          0          1          0          0          0         54
DB HISTORY_DB          Running          0          0          1          0          0          0         40
DB HISTORY_DB_BAK      Running          0          0          1          0          0          0         59

In the past I have one example this is the start point which can do the thing but I'm not aware so much in that kind of scripting: perl -ne 'chomp; if($. % 2){print "$_,";next;}
Answer: How about
awk 'NF==1{ val=$0; next} {print val" "$0}' input

You can format the output using the column utilty as
$ awk 'NF==1{ val=$0; next} { print val" "$0}' input | column -t
ADMIN  ADMIN_DB        Running  1  0  1  0  0  0  80
ADMIN  ADMIN_CATALOG   Running  0  0  1  0  0  0  452
ADMIN  ADMIN_CAT       Running  0  0  1  0  0  0  58
DB     SLAVE_DB        Running  2  0  3  0  0  0  94
DB     DB_BAK          Running  1  0  1  0  0  0  54
DB     HISTORY_DB      Running  0  0  1  0  0  0  40
DB     HISTORY_DB_BAK  Running  0  0  1  0  0  0  59


Use image scale and crop in custom function

Question: In Drupal 7, I'm trying to use image_scale_and_crop() to take an image from an external URL and resize it.  Then I want to print it out to my page.  Here is my code:
$filename = $bjt_img;
$img_url = "http://www.mydomain.com/uploads/".$filename;
$myimg = image_load($img_url);
$myimg_scaled = image_scale_and_crop($myimg, 100, 80);

print ''

I'm getting the message:

Recoverable fatal error: Argument 1 passed to image_scale_and_crop()
  must be an instance of stdClass, boolean given, called in...

How exactly is the image returned with image_scale_and_crop()?
Answer: You problem is image_load($img_url) is returning FALSE, which is not an object.
$filename = $bjt_img;
$img_url = "http://www.mydomain.com/uploads/".$filename;
if (isset($myimg = image_load($img_url)) {
  $myimg_scaled = image_scale_and_crop($myimg, 100, 80);
  print ''
}
else {
  print 'error'
}

Plus I think it must be a file,  not a url to a file
Answer: The problem is the value returned from image_load(), which is the boolean FALSE because the function is not able to load the image file.

Return value
An image object or FALSE if there was a problem loading the file. The image object has the following properties:

'source' - The original file path.
'info' - The array of information returned by image_get_info()
'toolkit' - The name of the image toolkit requested when the image was loaded.

As for the parameters accepted from the function, the first one is the path to the image file, which normally doesn't mean the URL of the image. Check also that in your PHP installation, the file functions are allowed to open remote files; in the case it is not enabled, passing a URL when a function is expecting a file name would cause the error you noticed.
The documentation for imagecreatefromjpeg(), which is the function that is called if the image toolkit Drupal is using is GD2, and the image is a JPEG one, reports:

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Similar warning is given for imagecreatefrompng(), and the other imagecreatefrom[image-type]() functions.


Why does my Jekyll site show HUGE icons on Github Pages

Question:
I generated a new jekyll site with jekyll new simple-site
The site looks ok in the localhost. It's the default, dummy site that's generated anyways.
I pushed it to gh-pages branch of a repo.

Now the site shows up under github.io/ but with HUGE icons.
The svg icons for github and twitter in the default jekyll generated site span the whole width of the page. They should be 16px or so.
Similarly 3 huge blocks appear in the top. They, again, are svg, which are supposed to be thin lines.
Here's my site: http://ananthp.github.io/carnatic_scores/
(repo: https://github.com/ananthp/carnatic_scores/tree/gh-pages )
Answer: As your site is not at the root of the domain ananthp.github.io/ but in a "directory" carnatic_scores/, you have to set baseurl variable in your _config.yml file.
baseurl: '/carnatic_scores'

Edit: some explanations
In _includes/head.html you can see this :
<link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">

which is equivalent to
<link rel="stylesheet" href="{{ site.baseurl }}/css/main.css">

With baseurl set to "" (default) your relative url is /css/main.css, which is resolved as http://ananthp.github.io/css/main.css by your browser = 404 not found.
With baseurl set to "/carnatic_scores" your relative url is /carnatic_scores/css/main.css, which is resolved as http://ananthp.github.io/carnatic_scores/css/main.css by your browser = your cool css !
That's true for all assets (css, js and image) :

or in markdown

![Image alt]({{ site.baseurl }}/path_to_images/image.jpg)

Comment: That fixes it. So, was the lack of baseurl prevented the stylesheet from loading?
Comment: @DavidJacquel  Any idea about [this](http://stackoverflow.com/q/34532476/2404470)
Answer: David Jacquel's answer is correct but I wanted to point out that Jekyll has a page about how to properly setup your Jekyll site for github pages. On that site they specifically talk about the fix (changing baseurl) but they mention other important things that you have to know too such as previewing your site with
$ jekyll serve --baseurl ''

Good luck and happy blogging!


How do the tonewood of a guitar body, neck and fretboard combine to contribute to the final tone?

Question: How does the tone of a guitar body, neck and fretboard combine to contribute to the final tone?
Many guitar manufactures go on about how each part has a certain tone. Like a maple neck having a bright tone, but a mahogany neck has a warm tone. However they never mention how these different tones contribute to the final tone of the guitar.
I realize this is ignoring many factors that also contribute (generally far more considerably) to tone. But for the purposes of this question if it is important please assume it refers are using quality wood in a electronic stratocaster guitar with a bolt on neck and all other equipment being equal.
More specifically how does the tone of say a body contribute. What if you have a bright toned body and a warm neck, a all warm tonewoods for all of these, all bright, or does it not really matter that much in the end?
Comment: This may be more important for acoustic than electric guitars. The pups on electrics tend to pick up (!) the vibrations from the strings, which are probably less influenced by particular woods, although it has been said that sustain is a factor due to certain woods. However, sustain is not tone.
Comment: What does the "(!)" mean?
Comment: Pickups pick up the sound.
Answer: I assume you are talking about electric guitars. If not, ignore my answer.
For electric guitars, the answer is, "they don't, in any noticeable way". "Tonewood" for electric guitars is, to the best available scientific knowledge, marketing hype. Tests indicate that listeners cannot reliably tell the difference between the sound of two guitars with body or necks made of different woods, if the other parameters of the guitar are kept constant (If you happen to read German, you can have a look here; it's quite funny - many listeners even think that the same guitar played twice, by the same player, sounds different). So if you cannot even tell the difference each component makes, asking how they combine their influences is pure speculation.
Comment: @user45266 -- what study? A link to a German site was provided. How are we to assess such a study and verify the claims that were made? We could take the poster at his word; we could also take Todd Wilcox at his word, and the many musicians who concur. There is never agreement on this issue, and every time somebody points to a study it seem to be lacking in some way. This is not engineering, and it is difficult to see how you can even form a scientific question that squares with claims about tone. If you can't hear something, fine. But don't tell others what they can or can't hear.
Comment: @ToddWilcox That said, he has a study to back up his claim, whereas you have an anecdote. Perhaps you can find some research to back up your claim so as to lend credibility to your argument.
Comment: @DavidBowling True, but the German site does have a study, does it not? I looked at it and saw that it had conducted what appeared to me to be, if not a study, then at least an experiment of sorts. Go ahead and assess the site, it lists the exact instructions they gave participants. What exactly is unable to be assessed? That said, I didn't mean to imply that Todd Wilcox could not hear or could hear the difference, I just mean that it's hard to really say that his anecdote has much authority compared with Richard Metzler's post.
Comment: @user45266 -- yes, a study that I can't read. That is why I can't assess. It looks like there are some test audio files, but this is a silly way to establish anything about the tone of a guitar. I am not interested in what a guitar sounds like on my laptop; I am interested what it sounds like when I am plugged into an amp. More to the point, I am interested in the way the guitar responds when I play it. Different woods seem to have to do with the responsiveness of an instrument (electric or otherwise). My thoughts about this are always shifting as I continue to play and listen....
Comment: @user45266 -- and this is the bottom line for me: I have to listen and form opinions based on that. People who have been playing for a long time, in a sustained and serious way, have opinions that are worth something. It is not bad to listen to what such people have to say; platitudes about anecdotes and data are too facile here, in my opinion. What I don't need is a study to tell me about tone. I would much rather talk with actual musicians, as messy at that is, to arrive at something more meaningful for a musician.
Comment: Look, I agree with you on your claim. I'm just trying to get information into more credible forms. I get that you feel that talking to musicians is as valid as it gets, but I'm doing research for an argument, and I can't very well just cite "some random guy on Stack Exchange" as a source, even though this site is very reputable.
Comment: @user45266 -- This doesn't appear to be your question, and I didn't realize that you were using the comments as resources for research. There is no definitive answer to the question of how tone woods affect the tone of electric instruments. There is a perfectly valid _mechanism_ for why they would. But who is listening, in what capacity, and according to what definition of tone all conspire to make this question much softer than "I have a study" can address.
Comment: @DavidBowling Okay, thanks. That clears up the issue for me considerably (I was using the answer as research, and tried to find opposing arguments in the comments).
Comment: @ToddWilcox - Do you have peer reviewed research (specifically a controlled A/B test of experiments in which every other parameter is held constant and tone wood is replaced) to back your claim?
Comment: "I don't see any peer reviewed research cited in any of your answers or comments so far" - https://en.wikipedia.org/wiki/Burden_of_proof_(law). The @ToddWilcox burden of proof is on you since you made a claim about X. I never made a claim about the fact it does not, I am only looking for concrete hard evidence that it does. Otherwise my claims of Santa Claus being real is just as valid as your claims about Tonewoods mattering.
Comment: @ToddWilcox "It's not too hard to take a Strat or Tele-style guitar and make changes and see what affects the tone. So we don't really need peer-reviewed research when we can easily conduct experiments ourselves" - Anecdotal hearsay. How do I ascertain the validity of your statements with the number of adhoc blind tests by professionals who could not discern the difference between a cheap squier made of agathis and a custom shop fender.
Comment: @ToddWilcox "Even if you don't own a guitar, you can simply go to a store with a good selection and play two different guitars that are identical except for their woods (ash vs. alder bodies and maple vs rosewood necks are easy to find". No they are not. How to do you prove they are identical otherwise? For instance how do I know one pickup is slightly more degaussed than the other. Or that even between the same tonewoods, one came from a tree that had less moisture content? How do I know the difference when one is reliced and the other is not.
Comment: @ToddWilcox - So far you sound like a priest/minister trying to proselytize a religion. Thats not how the scientific method works. It starts with skepticism, a hypothesis and then construct repeatable experiments that demonstrably show the measurable tangible difference between the two components. Everything other than that is hearsay. Also yes I do own guitars, and I do not fall for the tone wood hype. I have cheap beaters with modded electronics that (and yes this is subjective) blow the LP types out of the water.
Comment: @ToddWilcox: you are correct, the tone doesn't only come from the pickups. Manfred Zollner (one of the people behind the study I linked to, and an engineering professor with a long-standing passion for guitars) did the research and wrote a book on this - "Die Physik der Elektrogitarre". He measured and explained influences on the guitar tone from the pickups, the strings, the pick,  the construction and quality of the bridge, the construction and quality of the neck joint, the construction and quality of the nut and headstock, the fretboard, the setup and pickup height... but not the wood :-/
Answer: Depending on how the strings are attached to the guitar (how much string to body contact there is), different densities of body wood can give you slight tonal differences. How the neck is attached also factors in: neck through body will transfer more sound than a bolt on.
For example, a guitar with an in-body tailpiece, floating bridge, and neck through body can have some tone difference comparing a soft wood or plywood body to something like a hard maple neck and body.  The softer woods have some frequency absorption/dampening.
While this tonal difference shows up on a spectrogram, as stated in Richard's answer it is unlikely in a performing situation that a listener would notice a difference.


Testing approach Chi Square vs Mann Whitney

Question: I am looking to understand the best approach to determine if students in one school performed better on a quiz than another. In this scenario the quiz has five questions and only whole points are awarded, giving 0, 1, 2, 3, 4, & 5 as the only possible results.
The results:
| score | school_a | school_b |
|-------|----------|----------|
| 0     | 150      | 175      |
| 1     | 50       | 40       |
| 2     | 30       | 30       |
| 3     | 20       | 15       |
| 4     | 5        | 10       |
| 5     | 80       | 90       |

Given the non-normality of the distribution it seems like the Mann-Whitney test would be appropriate, but because scores are integers I am concerned that the ties may cause issues. Should I instead treat the scores as categorical variables and perform a chi-square test instead?
Is there another approach I should be considering instead?
Comment: A plain chi-square will ignore the ordering of the categories, making it hard to establish the question of interest. Can you explain more about the sense in which you intend "better"?
Comment: If you want to be theoretically safe, you could use ordinal regression with Score as the dependent variable and School as the independent variable.  Unfortunately I don't have this published anywhere, but at least for the two-sample case, Mann-Whitney follows the results of ordinal regression closely for this kind of data.  Just be sure to use a procedure for MW that accounts for ties.
Answer: Mann-Whitney (also two-sample Wilcoxon test): Data are
a = rep(0:5, c(150, 50, 30, 20, 5, 80))
b = rep(0:5, c(175, 40, 30, 15, 10, 90))
summary(a)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.000   0.000   1.000   1.761   4.000   5.000
 summary(b)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.000   0.000   1.000   1.764   4.250   5.000

The means and medians look very nearly the same for the two schools.
The formal test has P-value $0.6723 > 0.05$ so the difference is not
significant at the 5% level. For samples as large as these, the implementation of the Wilcoxon rank sum test in R, reports no difficulty
handling ties.
 wilcox.test(a,b)

        Wilcoxon rank sum test with continuity correction

data:  a and b
W = 61350, p-value = 0.6723
alternative hypothesis:
   true location shift is not equal to 0

Chisquared test of homogeneity of probabilities: Counts are
f.a = c(150, 50, 30, 20, 5, 80)
f.b = c(175, 40, 30, 15, 10, 90)
MAT = rbind(f.a, f.b);  MAT
    [,1] [,2] [,3] [,4] [,5] [,6]
f.a  150   50   30   20    5   80
f.b  175   40   30   15   10   90

I agree with @Glen_b that the Wilcoxon test is best here, because the issue seems to be which school had the higher scores overall.
However, the chi-squared test will test whether the probabilities of getting
individual scores 0 through 5 are substantially the same at the two
schools. No difference between the two distributions is found.
chisq.test(MAT)

        Pearson's Chi-squared test

data:  MAT
X-squared = 5.1107, df = 5, p-value = 0.4025

Kolmogorov-Smirnov test of of differences in CDFs:
This is a test to see if there is a substantial difference
between the empirical CDFs (ECDFs) of the two samples.
To make an ECDF, sort the data and plot a stairstep function
that increases by $1/n,$ where $n$ is the sample size, at each
data value. If there are $k$ tied observations at a point, then
jump up by $k/n.$ Here are the ECDFs of for the two schools,
blue for a and orange for b.
plot(ecdf(a), col="blue", lwd=2)
lines(ecdf(b), col="orange", lty="dotted", pch="o")

The test statistic $D$ of the K-S test is the maximum vertical
distance between the two ECDFs. Again here, no significant
difference is found. For your data, this test may be considered an alternative
to the chi-squared test.
ks.test(a,b)

        Two-sample Kolmogorov-Smirnov test

data:  a and b
D = 0.03835, p-value = 0.9605
alternative hypothesis: two-sided

Warning message:
In ks.test(a, b) :
   p-value will be approximate in the presence of ties

Comment: +1.  The only thing I might add is that looking at bar plots of the frequencies might be helpful: `Y= factor(c(a,b)); Group = c(rep("A", length(a)), rep("B", length(b))); library(lattice); histogram(~ Y | Group, nlayout=c(1,2), col="darkgray")`


ActiveRecord::Relation trouble

Question: I am using Ruby on Rails 3.0.10 and I would like to "subtract" two ActiveRecord::Relation "entities" and have back again an ActiveRecord::Relation. That is, I have two ActiveRecord::Relation objects (@articles and @articles_checked) and the following code:
@unchecked_articles = @articles - @articles_checked

# $  @unchecked_articles.class
# => Array

@unchecked_articles.method_call
# raise a NoMethodError error (read above for more information).

The above code, anyway, returns a Ruby Array so I can not "play" (use where, order, ... statements) anymore with that as I do normally with an ActiveRecord::Relation. In the console it generates the following error:
NoMethodError (undefined method 'method_call' for #<Array:0x000001063dd658>)

How can I retrieve an ActiveRecord::Relation object after I made the above changes? Or better, there is a way to accomplish what I aim to retrieve with the @unchecked_articles?
Answer: Use scope.
scope :unchecked, where("checked is FALSE")

I've made an assumption there that you flag checked articles like this. After defining a scope you can call Article.unchecked to get you AR of unchecked articles.
Answer: I don't know how your model looks, but i'd suggest defining a scope for articles.
Article < ActiveRecord::Base
  scope :unchecked, where(:checked => false)

  #or this, apologies for somewhat unefficient, but you already seem to have several queries
  scope :unchecked2, lambda { |checked| where(["id not in (?)", checked.map(&:id)]) }

end

Article.unchecked
Article.unchecked2(@unchecked_articles)

ActiveRecord::Relation trouble


About boundedness of continuous functions on a bounded closed interval

Question: Suppose that $f(x)$ is continuous on a bounded closed interval $I$.
Then, $f(x)$ is bounded on $I$.
I want to prove this fact like the following:
Assume that $f(x)$ is not bounded on $I$.
Then, there is an $a \in I$ such that $\displaystyle \lim_{x \to a} f(x) = +\infty$ or $\displaystyle \lim_{x \to a} f(x) = -\infty$.
On the other hand, $\displaystyle \lim_{x \to a} f(x) = f(a)$ because $f(x)$ is continuous at $a \in I$. This is a contradiction.
How can I derive the existence of an $a \in I$ such that $\displaystyle \lim_{x \to a} f(x) = +\infty$ or $\displaystyle \lim_{x \to a} f(x) = -\infty$ ?
Answer: If $f$ is unbounded on $I$ it does not necessarily mean that there is a value $a \in I$ for which $f(x) \to \pm\infty$ as $x \to a$. For example consider $f(x) = (1/x)\sin(1/x)$ on $(0, 1)$. It is essential to use some form of completeness here and also note that the the requirement of closed interval is essential. Result fails to hold for functions continuous on open intervals (see example $f$ given earlier).
While there are many way to prove this result (based on many different forms of completeness property) I find the one via Heine Borel Theorem to be very direct. Let $f$ be continuous on $[a, b]$ and defined $f(x) = f(a)$ for $x < a$ and $f(x) = f(b)$ for $x > b$ so that $f$ is continuous everywhere. By continuity for each $x \in [a, b]$ there is an open interval $I_{x}$ containing $x$ such that $|f(t) - f(x)| < 1$ for all $t \in I_{x}$. Thus $f$ is bounded on $I_{x}$ and let $M_{x}$ be such that $|f(t)| < M_{x}$ for all $t \in I_{x}$. The collection of all such intervals $I_{x}$ forms an open cover of $[a, b]$ and by Heine Borel Theorem there are a finite number of these intervals, say, $I_{x_{1}}, I_{x_{2}}, \ldots I_{x_{n}}$ which cover $[a, b]$. Let $M = \max(M_{x_{1}}, M_{x_{2}}, \ldots, M_{x_{n}}$. Clearly every point $t$ of $[a, b]$ lies in some $I_{x_{j}}$ and hence $|f(t)| < M_{x_{j}}$ and thus $|f(t)| < M$ for all $t \in [a, b]$.
Comment: Thank you very much, but I want to know if I can derive the existence of an a $\in I$ such that $\displaystyle \lim_{x \to a}  f(x) = + \infty$ or $- \infty$.
Comment: @Bolt: In my first paragraph I have mentioned that this is not necessary. A function may be unbounded without $f(x) \to \infty$ or $f(x) \to -\infty$. I have given an example of a function $f$ also which is unbounded but does not tend to $\pm\infty$. In short it is not possible to derive the existence of an $a \in I$ such that $\lim_{x \to a}f(x) = \infty$ or $-\infty$.


Como fazer o codigo ler input negativo - C

Question: Olá!
Estou fazendo um exercício e me deparei com esse problema:
Quando vou testar e coloco um número negativo ele não reconhece que o número é negativo.
Algúem consegue me ajudar?

<code>#include <stdio.h>
#include <math.h>

int main(void)
{
    int i;
    float vetor[6];

    for( i = 0; i < 6; i++){
        printf("Digite o %dº número: ", i+1);
        scanf("%f", &vetor[i]);

        if(vetor > 0){
            printf("\nNumero invalido. Digite somente numeros negativos.");
            return 0;
        }else{
            printf("\nOk, continue");
        }

    }
    printf("O resultado é:");
    for(i = 0; i < 6; i++){
        printf(" - %f ", vetor[i]);

    }

}</code>
Answer: Ele não está reconhecendo devido a forma com que você usou o vetor na primeira comparação, você não especificou qual espaço do vetor está sendo comparado.
Deveria estar especificando o espaço, como:
<code>    if(vetor[i] > 0){
          printf("\nNumero invalido. Digite somente numeros negativos.");
    }
</code>
Logo, fica da seguinte forma:
Comment: Muito obrigada! era isso mesmo!


Seamless move of an arrow in a loop with css animation

Question: I am trying to implement a seamless loop of one arrow inside a div.
I am using two SVG arrows and what I am trying to archieve is when the top of the first arrow is partly hidden the same part of the second one should be shown so it seems like only one arrow is used and it is moving in the loop (when the first arrow reaches the top of the div and the 50% of it is hidden then the 50% of the second one should be shown at the bottom).

.arrows-wrapper {
  width: 124px;
  height: 83px;
  overflow: hidden;
  position: relative;
  background-color: gray;
}

.arrows-wrapper svg {
  position: absolute;
}

.arrows {
  animation: slide 4s linear infinite;
}

.arrow2 {
  animation-delay: 2s;
}

@keyframes slide {
  from {
    transform: translate(0, -25px);
  }
  to {
    transform: translate(0, -125px);
  }
}

  <svg width="124" height="197" viewBox="0 0 124 197">
    <g class="arrows arrow1">
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,110 61,104 72,110"></polyline>
      <polyline stroke="yellow" stroke-width="4" fill="none" points="50,116 61,110 72,116"></polyline>
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,122 61,116 72,122"></polyline>
    </g>
  </svg>
  <svg width="124" height="197" viewBox="0 0 124 197">
    <g class="arrows arrow2">
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,110 61,104 72,110"></polyline>
      <polyline stroke="yellow" stroke-width="4" fill="none" points="50,116 61,110 72,116"></polyline>
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,122 61,116 72,122"></polyline>
    </g>
  </svg>

See the demo of what I have got so far (two arrows are visible at once but only one arrow or part of it should be visible at the same time).
The result I need:

The question is if it's possible to archieve.
Comment: And the question is...? Try use SVG as background
Comment: The question is added. Example of "Try use SVG as background"?
Answer: This should do it: Just needed to tweek the translate in your css animation.

.arrows-wrapper {
  width: 124px;
  height: 83px;
  overflow: hidden;
  position: relative;
  background-color: gray;
}

.arrows-wrapper svg {
  position: absolute;
}

.arrows {
  animation: slide 4s linear infinite;
}

.arrow2 {
  animation-delay: 2s;
}

@keyframes slide {
  from {
    transform: translate(0, -25px);
  }
  to {
    transform: translate(0, -200px);
  }
}

  <svg width="124" height="197" viewBox="0 0 124 197">
    <g class="arrows arrow1">
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,110 61,104 72,110"></polyline>
      <polyline stroke="yellow" stroke-width="4" fill="none" points="50,116 61,110 72,116"></polyline>
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,122 61,116 72,122"></polyline>
    </g>
  </svg>
  <svg width="124" height="197" viewBox="0 0 124 197">
    <g class="arrows arrow2">
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,110 61,104 72,110"></polyline>
      <polyline stroke="yellow" stroke-width="4" fill="none" points="50,116 61,110 72,116"></polyline>
      <polyline stroke="yellow" stroke-width="2" fill="none" points="50,122 61,116 72,122"></polyline>
    </g>
  </svg>


Genesis Child Theme's header.php not overwriting

Question: I have Genesis and a Genesis Theme installed. Now I would like to make some customization's so I have created a child-theme and activated it. I have made CSS changes and everything works. Now I would like to overwrite the header.php file from the the Genesis theme so I have copied the header.php file to my child-theme in hopes I would be able to overwrite the parent themes header.php. But any change I make to my child-theme's header.php file does not work. Any idea's how I can overwrite the parent's header.php file?
Comment: You copied the `header.php` file in the root of your Genesis folder to the root of your child theme folder?  That should overwrite it.   I ran a test and it did.
Comment: @Hubvill you said you have genesis and genesis theme, then you created own child theme also.. what you mean by Genesis theme? as please know , genesis is framework, then every other theme you install is Child theme.. and there are no support for grandchild themes.. i.e. you have just genesis+your activated child theme... so make sure you have got it right.
Comment: I think I miss understood how Genesis works. I have Genesis installed and a genesis theme installed. What I did was make an additional child-theme for the genesis theme so I have 3 themes, but it looks like this is wrong? I should just have 2 theme files correct?
Comment: Yes I didn't understand correctly how Genesis works and made a grand-child theme on accident. Thanks for clearing that up.
Answer: Grab the code from header.php inside genesis > lib > structure > header.php near line 623 and modify it in your child themes functions.php file like this:
remove_action('genesis_header','genesis_do_header');

add_action('genesis_header','genesis_custom_header');
function genesis_custom_header() {

global $wp_registered_sidebars;

    genesis_markup( array(
        'open'    => '
',
        'context' => 'title-area',
    ) );

        do_action( 'genesis_site_title' );
        do_action( 'genesis_site_description' );

    genesis_markup( array(
        'close'    => '
',
        'context' => 'title-area',
    ) );

    if ( ( isset( $wp_registered_sidebars['header-right'] ) && is_active_sidebar( 'header-right' ) ) || has_action( 'genesis_header_right' ) ) {

        genesis_markup( array(
            'open'    => '
' . genesis_sidebar_title( 'header-right' ),
            'context' => 'header-widget-area',
        ) );

            do_action( 'genesis_header_right' );
            add_filter( 'wp_nav_menu_args', 'genesis_header_menu_args' );
            add_filter( 'wp_nav_menu', 'genesis_header_menu_wrap' );
            dynamic_sidebar( 'header-right' );
            remove_filter( 'wp_nav_menu_args', 'genesis_header_menu_args' );
            remove_filter( 'wp_nav_menu', 'genesis_header_menu_wrap' );

        genesis_markup( array(
            'close'   => '
',
            'context' => 'header-widget-area',
        ) );

    }

}

Answer: normally header of genesis theme have this  code
/**
 * Fires immediately after the site container opening markup, before `genesis_header` action hook.
 *
 * @since 1.0.0
 */
do_action( 'genesis_before_header' );

/**
 * Fires to display the main header content.
 *
 * @since 1.0.2
 */
do_action( 'genesis_header' );

/**
 * Fires immediately after the `genesis_header` action hook, before the site inner opening markup.
 *
 * @since 1.0.0
 */
do_action( 'genesis_after_header' );

You have to change it like this.
/**
 * Fires immediately after the site container opening markup, before `genesis_header` action hook.
 *
 * @since 1.0.0
 */
do_action( 'genesis_before_header' );

/**
 * Fires to display the main header content.
 *
 * @since 1.0.2
 */
do_action( 'my_custom_header' );

/**
 * Fires immediately after the `genesis_header` action hook, before the site inner opening markup.
 *
 * @since 1.0.0
 */
do_action( 'genesis_after_header' );

Now in function.php or in header.php add your custom header like this.
add_action( 'my_custom_header', 'my_custom_header');
function my_custom_header() { ?>  Your header code <?php } ?>


How do I set Internet Proxy on Apache Commons Mail Api?

Question: I would like to send email using a custom proxy on apache commons email api because I'm connected to the internet through a proxy server.
I've tried using the common ways of setting proxies in java but it doesn't seem to work. e.g
System.getProperties().put("http.proxySet", "true" );
System.getProperties().put("http.proxyHost", "127.0.0.1");
System.getProperties().put("http.proxyPort", "6056");

And
System.getProperties().put("http.proxySet", "true" );
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "6056");`

Thanks.
Answer: Something like this should work:
  Email mail = ....

mail.getSession().getProperties().setProperty("mail.smtp.socks.host", "my.socks.host");
  ...

  mail.send();


Display view on all page routes

Question: I would like to display a multi value media field and its file type and size in a content type and display it in a table layout. I thought using a view would be the best way to pull the media file type and file size and any references it has using views relations.
The view uses Relations to get the media type and size and uses a Contextual filter - Content ID from URL. Now I am printing the display in a node template like this using Twig tweak.
{{ drupal_view('materials', 'block_1') }}
The table and media values display fine when published on route entity.node.canonical.
But the media values do not display on other routes and tabs like /latest routename entity.node.latest_version and /full routename entity.node.preview. The table markup displays but not the media values inside. I have tried printing the view using the drupal_block method and had the same results.
Answer: The content id is missing from your function call you have to add it like this
{{ drupal_view('who_s_new', 'block_1', arg_1, arg_2, arg_3) }}
or you can render your view in custom block and add it in every page via 'block layout'
https://www.webwash.net/programmatically-create-block-drupal-8/
<code>$view = views_get_view('view_name');
$view->set_display('view_block_name');
$view->set_arguments(array($tid));
// change the amount of items to show
$view->set_items_per_page(4);
$view->pre_execute();
$view->execute();
$view->render();
</code>

Display view on all page routes


Why do we also call the roots of the polynomial that cannot be solved by radicals "algebraic"?

Question: Quote from Wiki: "An algebraic number is a number that is a root of a non-zero polynomial in one variable with integer (or, equivalently, rational) coefficients."
But, the root of unsolvable polynomials (by radicals) cannot be obtained by "algebraic" operations:
"addition,subtraction,multiplication, division  and root extraction"

So, if they're not expressible in radicals, in what sense are they 'algebraic'?
Comment: What if we allow polynomials that have algebraic number coefficients? Do we get some super-algebraic numbers, and if we iterate on that, is there a fixed point?
Comment: The algebraic numbers from an algrebraic closed field , hence the roots are again algebraic.
Answer: A number being the root of a polynomial means you have access to it by the methods of algebra: linear algebra, modules, traces and norms, ideals, and so on. I am not saying that is why the term "algebraic number" was used initially, but the term is very nice today for the reason I just indicated. Non-algebraic numbers are called transcendental since they "transcend" (go beyond) techniques of pure algebra, both historically and today.
You appear to be under the impression that numbers that can be described by explicit root formulas are important, perhaps because a more impressive word "solvable" is used for them. Let me advise you to reconsider this idea. While historically the property of being expressible by radicals was a big deal, and trying to understand this property led to important developments in abstract algebra, after Galois cleared this issue up his ideas (Galois theory) did not atrophy but continued to find many new applications up to the present day. Solvability of a number is not important in modern math while the property of being algebraic is very important: see any account of algebraic number theory.
Comment: What is "Solvability of a number"?
Comment: You used the term yourself (indirectly) when you wrote about unsolvable polynomials.  An algebraic number is called solvable or unsolvable when it is the root of a polynomial (with rational coefficients) that is solvable or unsolvable.  So $\sqrt{2}$ is solvable (maybe the right term is "solvable by radicals", whatever) while roots of $x^5 - x - 1$ are not solvable.
Comment: @user1094359, in this context, it means "expressibility in terms of root-taking"... the Galois-theoretic condition is about "solvability" of relevant Galois groups.
Comment: Thanks for clarifications!
Answer: Yes, I, too, "in my youth", was greatly confused about what kind of numbers "algebraic" numbers could be, if they were not expressible in terms of radicals! :)
No, one's high school teachers would most likely not be able to explain the difference...
So, yes, the obvious question "but, wait, if they're not expressible in radicals, in what sense are they 'algebraic'?" deserves an answer... which is that "it turns out" that there are roots of polynomial equations not expressible in terms of radicals. Who knew? But they're still characterized by purely algebraic means (just not quite expressions in terms of radicals).
In the 19th century, and into the 20th, there was considerable interest in determining what "new" operations, beyond root-taking, would be necessary to express solutions to polynomial equations. The "Tschirnhausen transformations" showed that there was some meaningful reduction. In the late 19th, Klein (and others) showed that modular forms could express solutions of quintics. In the 20th, people realized that, similarly, Siegel automorphic forms (connected to the Jacobian variety of an algebraic curve attached to a polynomial) could express the solution of an arbitrary polynomial. (See Mumford's three volumes "On Theta"... or similar title.)
(And, in the 20th, we did also see that elliptic functions, and so on, can express Hilbert class fields of certain number fields. Work of Shimura, et al. And then there are Stark's conjectures about generation of fields...)
Comment: Indeed! :) To repeat: they are _characterized/defined_ by algebraic conditions (satisfying polynomial equations), but not necessarily expressible in terms of the specific operation(s) of root-taking. :)
Comment: Ah, indeed, it's fun, crazy stuff. There is the classic book, Klein's "The Icosahedron" (from about 120 years ago) which explains how to solve quintics (with some fancy stuff). Those other phrases are possibly adequate key-word/phrases to google... At least Wikipedia surely has some good pointers. About 1973, I myself heard about Kronecker's work, and Shimura's (my eventual PhD advisor), and was enchanted... :)
Comment: +! Yes. That is a my exact question. If they're not expressible in radicals, in what sense are they 'algebraic'?"
Comment: Thank you for expressing my question better.  I made this my own question.
Comment: I am a high school student...But, I know that Galois theory says we can not construct general algebraic formula for quintics or higher degree polynomials...Also, I understood your last comment exactly! Yes! although I've never heard of "elliptic function", "Hilbert class fields, Work of Shimura, Stark's conjectures  ..."


Proving Properties limsup and liminf

Question: I got stuck by proving following statement: If $c \leq0 $, prove that $ \liminf_{n \to \infty  }(ca_n) = c \, \limsup_{n \to \infty  }(a_n) $.
Proof:
Consider $A_n = \{a_m |  m  \geq n\} $. The set $A_n$ has a supremum. Let $x_n = sup(A_n)$. This applies that $\forall a \in A_n: x_n \geq a  $. Next, we multiply by $c \leq 0  $ and we get $ca \geq c  x_n$. So $c \,x_n$ is a lower bound for the set $cA_n$. So we get:  $ \liminf_{n \to \infty  }(ca_n) \leq c \, \limsup_{n \to \infty  }(a_n) $.
I got stuck by proving the other inequality. I tried it next way: Take $\epsilon \geq 0 $ arbitrarily. Then $cx_n + \epsilon > cx_n$. So I just need to show that $cx_n + \epsilon$ is not a lowerbound for $cA_n$. But I cannot get there. Somebody who wants to help me?
Thanks in advance!
Answer: Note that if $c \ge 0$ then $\sup_k c x_k = c \sup_k x_k$, and similarly for $\inf$.
Hence $\limsup_n c a_n = \lim_n \sup_{k \ge n} c a_k = \lim_n ( c \sup_{k \ge n} a_k )=
c\lim_n \sup_{k \ge n} a_k = c \limsup_n a_n$,
and similarly for $\inf$.
If $c \le 0$ instead, then we have $\sup_k c x_k = c \inf_k x_k$ and similarly with the $\sup, \inf$ interchanged. Repeating the above chain mutatis mutandis gives the desired result.
Comment: I suspect that $c\geq0$ in the first line of the question is a typo. The OP continues with: "....Next we multiply by $c\leq0$..." and I think that there $c\leq0$ is not a typo.
Comment: Yeah, my mistake! Edited it!
Comment: @drhab: Thanks for catching that. I suspect you are correct.
Comment: I have added an answer for $c \le 0$.
Answer: Let $\limsup (a_n)=a$
for $c<0$,consider $-\epsilon/c$ which is positive,then we can get an $N$ in $\mathbb N$ such that $\forall n>N$ we have $a_n\leq a-\epsilon/c$ i.e. $ca_n\geq ca-\epsilon$ for all $n>N$.So it follows that $\liminf (ca_n)=c \limsup(a_n)$.

Proving Properties limsup and liminf