Can't run EXE file in Python

Question: In a folder, I have two files— a Python Script and an Executable application. What I want is to run the Executable app using the Python script. I used below pieces of code:
os.chdir("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") # NotADirectoryError: [WinError 267] The directory name is invalid: 'D:\\ToneFinder GIthub\\ToneFinder\\Record.exe'
os.system("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") # 'D:\ToneFinder' is not recognized as an #internal or external command,
operable program or batch file.

os.startfile("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") # Nothing happens

subprocess.call("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") #Error loading Python DLL 'D:\ToneFinder GIthub\ToneFinder\python310.dll'

Note: Always, the path is 100% correct
Any ideas on that? Thank you.
Comment: The chdir wouldn't work... you change to the directory `"D:\\MyTestApp\\MyTestApp"` , not the executable file in that directory. The path is 100% correct, but the error message has a different path name in it... that is puzzling. Is D:\\MyTestApp a symlink?
Comment: I'm really sorry for the mistake, the path in the error is correct. Just edited it!
Comment: As mentioned below, you need to escape the spaces in the path name. Usually that can be done by adding quotes for the windows shell. Note the single quotes for python, then the doubles for windows. `os.startfile('"D:\\ToneFinder GIthub\\ToneFinder\\Record.exe"')`
Answer: chdir
os.chdir is for changing the working directory, not running a program. ...\Record.exe is not a directory.
system, startfile
The path contains a space, so Windows tries to run D:\ToneFinder (which implicitly becomes D:\ToneFinder.exe) with the argument GIthub\ToneFinder\Record.exe. Since there is no such file, an error occurs. Surrounding it with double quotes (os.system(r'"D:\ToneFinder GIthub\ToneFinder\Record.exe"')) will cause it to be interpreted as one long path.
call
subprocess.call takes a list of space-separated arguments, so it should be called like so: subprocess.call(r'"D:\ToneFinder GIthub\ToneFinder\Record.exe"'.split())
Which one should I use?
See Difference between subprocess.Popen and os.system.
Comment: Hey there, @Makonede. Thanks for the explantation but still, I can't figure out what to use. As in the answer you mentioned, I tired subprocess.Popen, but it returned: `Error loading Python DLL 'D:\ToneFinder GIthub\ToneFinder\python310.dll'.
LoadLibrary: The specified module could not be found.
Comment: @JKR Try `os.system` then.
Comment: It returns another Error: `'D:\ToneFinder' is not recognized as an internal or external command, operable program or batch file.
Comment: @JKR Did you even read my answer?
Comment: I'm sorry, I tried it right now. But, then another error: `Error loading Python DLL 'D:\ToneFinderGIthub\ToneFinder\python310.dll'.
LoadLibrary: The specified module could not be found.`
Comment: @JKR I told you, use `system` if `Popen` doesn't work.

Can't run EXE file in Python


C++ pointer to template function which class member

Question: I have the following functions in class "C"
class C
{
  template<typename T> void Func1(int x);
  template<typename T> void Func2(int x);
};

template<typename T> void C::Func1(int x)
{
  T a(x);
}

template<typename T> void C::Func2(int x)
{
  T a(x);
}

The functions uses templates only in the implementation. The signature does not contain template parameters.
Is it possible to define pointers to such template functions?
I tried the following definition but it results compilation error.
typedef template<typename T> void (СSomeClass::*TFuncPtr)(int);
Comment: Does it work without the typedef?
Comment: Stop calling them template functions. They are function templates. It does make a difference (no, I am not willing to explain to somebody who does not accept answers).
Answer: Once instantiated, a member function template is just a normal member function, so you can use a normal member function pointer (best typedef'd like below):
typedef void (C::*mem_fun_ptr)(int);
mem_fun_ptr p = &C::Func1<Bar>;
//          IMPORTANT -- ^^^^^

The underlined part is the important part. You can't make a pointer to a function template, but you can make a pointer to an instantiated function template.
Answer: do you want only a pointer to a function?
that's simple:
class C
{
public:
  template<typename T> void Func1(int x);
};

typedef void (C::*TFuncPtr)(int);

int main()
{
 TFuncPtr ptr = &C::Func1<int>;
}

if you want something else could you show an example of using the pointer you want?
Comment: You answer completely matches my question. Thanks.
Comment: http://stackoverflow.com/faq#howtoask read the part about accepting answers: "When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer."
Comment: What if I have a return value as a Template as well how would I deal with it ?


finding $g(x)$ when $f(x)$ and $f(g(x))$ are given.

Question: I'm currently stuck solving this question.
$f(x) = x^3 - 5x^2 + x - 7 $
$f(g(x)) = 27x^3 + 90x^2 + 78x - 2  $
I know that I can find $g(x)$ by finding the inverse function of $f(x)$ and $f^{-1}(f(g(x))$ but in this case it looks like it is impossible to find inverse function of $f(x)$. So is there an easier method of doing this?
Thanks in advance.
Comment: And *how* would you find $f^{-1}$? It doesn't exist, since $f$ is *not* bijective.
Answer: Yes, there is an easier method. Just write $g(x)=ax+b$ and compute $f(g(x))$. Comparison of the coefficients of $x^3$ gives $a=3$, and comparison of the coefficients of $x^2$ gives $b=5$. Hence
$$
g(x)=3x+5.
$$
Note that the degree of $g$ cannot be bigger than $1$, because otherwise the degree of $f(g(x))$ would be bigger than $3$.
Comment: It is not given that $g$ is a polynomial.
Comment: @KaboMurphy Like it is not given that $f\in K[X]$ for some field $K$ of characteristic zero. Probably the OP means this, but has not specified.
Comment: @KaboMurphy That doesn't really matter. When looking for a solution, one is allowed to hope that the solution is nice, assume the solution is nice, and if one finds a solution with such an assumption, then great! If not, then you're almost back at square 1, true. But nothing has been lost other than a minute of calculation. If one is asked to find _all_ such $g$, then that's a different matter.
Answer: In general, no there isn't a better way (although finding the inverse of this $f$ might prove to be a problem since it doesn't exist).  However, in this problem, it might be best to stare at the problem to see if an idea appears.

We see that both $f(x)$ and $f(g(x))$ are polynomials, so it makes sense to guess that $g(x)$ might also be a polynomial.
The leading term of $f(x)$ is $x^3$, while the leading term of $f(g(x))$ is $27x^3=(3x)^3$.  Therefore, we might guess that the leading term of $g(x)$ is $3x$, which is then getting cubed to get $27x^3$.
At this point, we're guessing that $g(x)=3x+a$ for some $a$.  We could just substitute our guess for $g(x)$ into $f(x)$ to get an expression of
\begin{align*}
f(g(x))&=(3x+a)^3-5(3x+a)^2+(3x+a)-7\\
&=(27x^3+3(3x)^2a+3(3x)a^2+a^3)-5(9x^2+2(3x)a+a^2)+(3x+a)-7\\
&=27x^3+(27a-45)x^2+(9a^2-30a+3)x+(a^3-5a^2+a-7).
\end{align*}
Now, we look at the $x^2$ term of $f(g(x))$, which is $90x^2$.  On the other hand, the $x^2$ term of our guess is $(27a-45)x^2$, and these should be equal.  In other words, $90=27a-45$.  Solving for $a$, we get $a=5$.
Now that we have a guess of $a=5$, we can take our $g(x)=3a+5$ and hope that $f(g(x))$ is correct by plugging in.  Plugging into our formula above gives exactly the form given, so we are done.


Como montar uma matriz no R sendo os valores a subtração de valores de um vetor

Question: Como fazer para criar uma matriz no R, cujos valores sejam o resultado de uma subtração de valores de um vetor?
ex.:
Vetor
x <- c(a, b, c)

Matriz
1 a-a  a-b  a-c
2 b-a  b-b  b-c
3 c-a  b-b  c-c

Answer: A função outer foi feita para responder ao problema da pergunta. Por defeito assume a função "*" para calcular o produto externo (Wikipedia em Português, em Inglês), mas pode-se passar qualquer outra função.
a <- 1
b <- 3
c <- 6
x <- c(a, b, c)

outer(x, x, '-')
#     [,1] [,2] [,3]
#[1,]    0   -2   -5
#[2,]    2    0   -3
#[3,]    5    3    0

Answer: Só pensar na matriz como um conjunto de vetores, aí vocÊ forma as linhas e colunas e junta numa matriz.
Aqui já feito de uma vez, crio um vetor com as linhas concatenadas e depois transformo em uma matriz com 3 linhas.
x <- c(1,2,3)

m <- matrix(c(x[1]-x, x[2]-x, x[3] - x), nrow =  3, byrow = T)


Starting out with PDEs

Question: In order to introduce myself to PDEs, I decided to set up my own, and see if I can solve it. So, I started with this:
$$z = x^2 + y^2$$
And differentiated with respect to x:
$$\frac{\partial z}{\partial x} = 2x$$
And the same for y:
$$\frac{\partial z}{\partial y} = 2y$$
So now, I can equate both equations:
$$\frac{\partial z}{\partial y} \frac{1}{y} = \frac{\partial z}{\partial x} \frac{1}{x}$$
Now, I have to reverse this process and solve them. I presume you set both sides to equal a constant, $C_1$ like so:
$$\frac{\partial z}{\partial y} \frac{1}{y} = \frac{\partial z}{\partial x} \frac{1}{x} = C_1$$
So I can split these apart again and integrate:
$$\frac{\partial z}{\partial y} = C_1y$$
$$z = \frac{C_1}{2} y^2 + f(x) + C_2$$
And similarly:
$$\frac{\partial z}{\partial x} = C_1x$$
$$z = \frac{C_1}{2} x^2 + g(y) + C_3$$
Comparing the two equations, I see that $f(x) = \frac{C_1}{2} x^2$, $g(y) = \frac{C_1}{2} y^2$ and $C_3 = C_2$, so we can write the equation as:
$$z = \frac{C_1}{2}\left(x^2 + y^2\right) + C_2$$
Where the values of the constants can be found later.
So, is this the right way of solving PDEs or is my technique wrong?
Comment: As you can easily check, for every differentiable function $f$, $z=f(x^2+y^2)$ is a solution of your PDE. So what do you think, is your method correct?
Comment: Why should both sides of that equation be equal to a constant? If you're truly interested in learning PDEs, you should be working from a book on the subject.
Comment: @ProfessorVector Well after trying the same method on some other equations, no, it only works here
Answer: When you equated the two ODE's (w.r.t. $x$ and w.r.t. $y$), you ignored the value $2$ completely.
Now the equation
$$\frac{\partial z}{\partial y}\frac1y=\frac{\partial z}{\partial x}\frac1x$$
tells us that the two expressions, $\displaystyle{\frac{\partial z}{\partial y}\frac1y}$ and $\displaystyle{\frac{\partial z}{\partial x}\frac1x}$ are equal to each other, but it doesn't say that both these expressions are equal to $2$. Also by making both these expressions equal to $C_1$, you changed the value $2$ by $C_1$, which hence also replaces $2$ in the end result. So the above PDE when solved doesn't make the answer same as the initial values $\displaystyle{(C_1=2,\ C_2=0)}$, but you can get the start expression for $z$ by introducing initial value conditions that make the values for $C_1$ and $C_2$ equal to $2$ and $0$, respectively. I don't know how to derive IVC's for given expression (that's because I didn't ever bother to find the ODE of a function and then solve it to get what I already have). Yet, by inspection, I can easily say that the initial value conditions for the given problem are
$$z(0,0)=0,\ z(1,0)=z(0,1)= 1$$
By putting these IVC's in the expression,
$$z=\frac{C_1}{2}(x^2+y^2)+C_2$$
I get $C_1=2$ and $C_2=0$ and putting these values in the result, we obtain
$$z=x^2+y^2$$
which is the required answer.
Answer: What you have done in fact is applying the method of separation of variables which is one method among various others.
The PDE to be solved is :
$$\frac{\partial z}{\partial y} \frac{1}{y} = \frac{\partial z}{\partial x} \frac{1}{x} \tag 1$$
A form of separation of variables is :
$$z(x,y)=F(x)+G(y)$$
$\frac{\partial z}{\partial x}=F'(x)$
$\frac{\partial z}{\partial y}=G'(y)$
$$G'(y) \frac{1}{y} = F'(x) \frac{1}{x}$$
This can be equal for any values of $x$ ans any values of $y$ only if both fonctions are constant. That is why $ \quad G'(y) \frac{1}{y} = F'(x) \frac{1}{x}=C_1$
$$\begin{cases}F'(x)=C_1x \quad\to\quad F(x)=\frac{C_1}{2}x^2+\text{constant} \\G'(y)=C_1y\quad\to\quad G(y)=\frac{C_1}{2}y^2+\text{constant}\end{cases}
\quad\to\quad z(x,y)=\frac{C_1}{2}\left(x^2+y^2\right)+C_2$$
That is what you found, in fact in "reinventing" a form of the method of separation of variables.
The method of separation of variables, on several variants, cannot solve all the kind of PDEs.
They are other forms of separation of variables and other methods that you have to learn to be able to solve more completely this PDE and to solve more complicated PDEs.
In the case of the PDE (1) above, $\quad z(x,y)=\frac{C_1}{2}\left(x^2+y^2\right)+C_2\quad$ is a family of solutions, but not all the solutions. A more general solving leads to
$$z(x,y)=\Phi(x^2+y^2)$$
where $\Phi(X)$ is any differentiable function. Among them, the fonction $\Phi(X)=X$ corresponds to the fonction used at your starting point : $z(x,y)=x^2+y^2$.
The arbitrary function $\Phi$ is determined according to some boundary conditions when they are specified in the wording of the problem.
For example, if in addition to the PDE (1), a boundary condition $z(x,0)=x^2$ is specified, then the unique solution is $z(x,y)=x^2+y^2$. But if another boundary condition is specified, for example $z(0,y)=\sin(y^2)$ the unique solution is $z(x,y)=\sin(x^2+y^2)$.

Starting out with PDEs


Take messages generated by module and print them inside the node teaser?

Question: I have a Pay2Publish module, which gets no support these days, so I have to turn to the community for the help.  I guess this is a simple PHP question:
I want to take the messages generated by Pay2Publish module and display them bellow each node teaser.
Here's the code from the module:
/**
 * Implements hook_node_view()
 *
 * Displays the Message for the author of a node
 */
function ms_paypublish_node_view($node, $view_mode, $langcode) {
  $plans = variable_get('ms_paypublish_plan_' . $node->type, array());
  $pp_node = ms_paypublish_load_node_nid($node->nid);

  if ($pp_node AND !empty($plans)) {
    if ($view_mode == 'full' AND user_access('renew own pay to publish nodes')) {
      global $user;
      if ($node->uid == $user->uid) {
        switch ($pp_node->status) {
          case 0: // Not Published
            drupal_set_message(
              str_replace(
                '!link',
                l(t('Publish'), 'ms_paypublish/publish/' . $node->nid),
                variable_get('ms_paypublish_not_published_text', 'This content is not published. To publish, please click here: !link')
              )
            );
            break;

          case 1: // Published
            if ($pp_node->expiration_date) {
              drupal_set_message(
                str_replace(
                  array('!days','!link'),
                  array(
                    ms_paypublish_get_expiration_string(ms_paypublish_get_expiration($node->nid)),
                    l(t('Promote / Extend'), 'ms_paypublish/publish/' . $node->nid)
                  ),
                  variable_get('ms_paypublish_published_text', 'This content will expire in !days days. To Promote / Extend, please click here: !link')
                )
              );
            }
            break;

          case 2: // Awaiting Admin Approval
          case 5:
            drupal_set_message(variable_get('ms_paypublish_approval_text', 'This content is Awaiting Admin Approval. It will be published shortly.'));
            break;

          case 3: // Not yet published
            drupal_set_message(str_replace('!link', l(t('Publish'), 'ms_paypublish/publish/' . $node->nid), variable_get('ms_paypublish_publish_text', 'This content has not been published yet. To publish, please click here: !link')));
            break;
        }
      }
    }
  }
}

What do I need to put inside my custom node--content-type.tpl.php so that these messages are displayed below each teaser?
Answer: My suggestion is:

Change this line in hook_node_view()
if ($view_mode == 'full' AND user_access('renew own pay to publish nodes')) {
and add $view_mode == 'teaser' to it. Then you can create a patch and submit to community, if you think that this feature may be needed by other users.
You can create a template file for this content type, store the messages in a theme variable and display them in template file, just use <?php print $VARIBALE_NAME ?> You also have to write a template preprocess function where you will write code to get message body.

I think second option is the best. The requirement is not generic and changing the module is not right in this case. However, you can search the module's issue queue for this.
References

function template_preprocess_node
Drupal 7 Template (Theme Hook) Suggestions
Comment: I pasted that code inside my_theme_preprocess_node of the template.php, but what do I need to replace "drupal_set_message"??? What is the correct syntax?
And what do I need to put inside the node--content-type.tpl.php
Comment: I have changed the answer see if that helps


Soma de elementos em listas

Question: [[3, 2, 7], [8, -2, 5], [-1, 4, 3], [2, 2, -9]]

De seguida guarda em três variáveis distintas, ignorando os valores negativos, a soma dos elementos separadamente. Ou seja, a soma do primeiro elemento de cada sublista, a soma do segundo elemento de cada sublista e a
soma do terceiro elemento de cada sublista. Depois cria um dicionário com a correspondência de chave/valor dos números de 1 a 15, por exemplo:
{1:"Um", 2:"Dois" … 15:"Quinze"}.

Para finalizar, fazendo corresponder o valor do resultado à chave do dicionário, apresenta o resultado individualmente em forma de texto.
Comecei com este código. A minha primeira questão é faço um ciclo for if else? Como consigo que some apenas os positivos? Como chamo os blocos? da mesma forma que nas listas 0,1,2,3?
lista=[[3,2,7], [8,-2,5], [-1,4,3], [2,2,-9]]

var1=""
var2=""
var3=""

for int in range(len(lista))
    if (int in lista)
    var1=

Comment: [Nessa página](http://www.devmedia.com.br/como-trabalhar-com-listas-em-python/37460) tem um tutorial breve sobre listas, pode te ajudar.
Answer: Considere a lista de entrada:
values = [[3, 2, 7], [8, -2, 5], [-1, 4, 3], [2, 2, -9]]

Desejando somar os valores de cada lista em um determinado índice, devemos, então redefinir a lista conforme nossa necessidade. Para tal, utilizamos a função nativa zip:
values = list(zip(*values))

Nota: Utilizar o * faz com que cada posição da lista seja passada como parâmetro à função. Fazer zip(*values) é o equivalente à zip(values[0], values[1], values[2]), mas com menos código e muito mais fácil de ler.

Desta forma, nossa lista será da seguinte forma:
[(3, 8, -1, 2), (2, -2, 4, 2), (7, 5, 3, -9)]

Ou seja, criou-se uma tupla com os valores no índice 0 de cada lista, outra com os valores do índice 1 e outra com os valores no índice 2. Basta agora somarmos os valores quando os mesmos não forem negativos, armazenando o resultado em variáveis, utilizando a função nativa sum.
sum_1 = sum(i for i in values[0] if i >= 0) # Resulta: 13
sum_2 = sum(i for i in values[1] if i >= 0) # Resulta: 8
sum_3 = sum(i for i in values[2] if i >= 0) # Resulta: 15

É pedido, também, para que seja definido um dicionário com os números por extenso. Assim:
texts = {
  1: "um",
  2: "dois",
  3: "três",
  4: "quatro",
  5: "cinco",
  6: "seis",
  7: "sete",
  8: "oito",
  9: "nove",
  10: "dez",
  11: "onze",
  12: "doze",
  13: "treze",
  14: "catorze",
  15: "quinze",
}

Finalmente, é apresentado o resultado:
print("A soma 1 resultou em: {}".format(texts[sum_1]))
print("A soma 2 resultou em: {}".format(texts[sum_2]))
print("A soma 3 resultou em: {}".format(texts[sum_3]))

Que será:
A soma 1 resultou em: treze
A soma 2 resultou em: oito
A soma 3 resultou em: quinze

Veja o código funcionando no Repl.it ou no Ideone.
Comment: O problema de se usar um dicionario assim e que se a soma resultar em um numero que não esteja em um dicionario o programa informaria um erro, dessa forma teria que utilizar tratamento de erro e mesmo assim não se obteria um resultado esperado. Outro ponto e que salvar os resultados em variáveis pode resultar em novos erros  caso a matriz seja maior.
Comment: @Arcashaid, de fato, mas o enunciado pede explicitamente desta maneira e, considerando uma solução de exercício, TODOS os requisitos levantados pelo enunciado devem ser satisfeitos.
Comment: O problema e que o enunciado não especifica o tamanho de colunas
Comment: Serão sempre três valores em cada sub-lista, está claro isso em: *a soma do primeiro elemento de cada sublista, a soma do segundo elemento de cada sublista e a soma do terceiro elemento de cada sublista*.
Answer: Você precisa encarar o problema como uma matriz
(que é acessada: matriz[posicao_i][posicao_j]))
1. Deixe fixada a coluna e percorra todas as linhas, fazendo então as sua condições e operações;
2. incremente a posição da coluna;
3. repita.
# para somar ignorando os valores negativos:

lista = [[3,2,7], [8,-2,5], [-1,4,3], [2,2,-9]]

valores = []

for coluna in range(len(lista[0])):
    soma = 0

    for linha in range(len(lista)):
        if(lista[linha][coluna] >= 0):
            soma += lista[linha][coluna]

    valores.append(soma)

print(valores)

Comment: Obrigado agora so tenho de armazenar o resultado em variáveis diferentes.
Comment: Por mais que possa resolver o problema, está solução não é considerada boa em Python. Faça melhor uso das ferramentas da linguagem e terá resultados muito mais interessantes. Busque sempre analisar qual é a solução mais [*pythonica*](http://pt.stackoverflow.com/questions/192343/o-que-%C3%A9-um-c%C3%B3digo-pyth%C3%B4nico).

Soma de elementos em listas


What do you call adding zeros to a table of frequency counts of consecutive integers where the given integer does not occur

Question: I am wondering what the proper term is, for when a table like this (where values that did not occur are omitted entirely):
<code> ________ _______
| Length | Count |
|--------|-------|
|      1 |     5 |
|      3 |     2 |
|      6 |    12 |
|________|_______|
</code>
Is rewritten like this (where values that did not occur are noted with a frequency of zero):
<code> ________ _______
| Length | Count |
|      1 |     5 |
|      2 |     0 |
|      3 |     2 |
|      4 |     0 |
|      5 |     0 |
|      6 |    12 |
|________|_______|
</code>
Comment: If it's truly missing data, I would call it a (bad) form of single imputation. If the missing rows truly mean that the count was zero (i.e. there is no uncertainty involved), I do not know of a name. But then I wonder if it needs one, because it's only a step 'behind the scenes' (data cleansing)
Comment: @Tie-figher I tried to come up with a clearer title given that the data isn't "missing" in the statistical sense. feel free to modify.
Comment: I second @Nick Sabbe; if the missing rows are in fact observed zeros then all you're doing is recoding your data (and it shouldn't be necessary in order to calculate a histogram). You also observed 0 for the integers in 6-infinity but it would be inconvenient to include 0's those in your dataset ;)
Comment: I'd see this just as a way of making explicit in a report what is implicit in the data, namely that certain values that might have occurred did not occur in the dataset to hand. It's nothing to do with imputation.. It is common with one-way tables in many fields to fill gaps with zero counts, and very common with two-way or higher tables to show zeros when combinations of categories do not occur (you could hardly do otherwise).
Comment: I am trying to extract data via SQL for a Histogram, so if there is no row it means 0.
Isn't this something like normalizing?
Comment: IF you're trying to create a histogram, you shouldn't need the zeroes. What software are you using?
Comment: well it is not missing, there just no observations for 2, 4, 5, so you could just right 0 for not observed (it is truly different from missing) data. However to make nice histograms, I think, you have to group the intervals to include at least 5 counts in it. So for example 1-3 4-6 would be one of possible devisions.
Comment: Is it fair to say that the unobserved integers exist in the population but not in the finite data sample?
Comment: It's a matter of taste and circumstance when to do it. For example, if I had family sizes 1 to 7 and 17 I would probably not have rows showing zero counts for sizes 8 to 16, but it would not be crazy to do that, just not usually a good use of reporting space. As to the question, I don't know a special name for this and I don't think a name is needed.
Answer: Mapping a set of observed value onto the observable values expected for a given variable?
That is, a variable is characterized by all hypothetical values that can be observed when using it, but observed values may not reflect the full range of possible values. For example, when collecting n=100 discrete scores on a 0-20 point scale, you might end up with some scores that were observed more often than other, while some never occurred.
And if the number of observable (distinct) value is so small, I would suggest some kind of bar graph (or a dot chart) rather than an histogram, which for a random sample might look like this:
Comment: @Tie-fighter A barplot is for discrete outcomes, an histogram is for continuous ones (that will be grouped into contiguous bins).
Comment: @Nick Others make a different distinction: a bar chart represents quantities by means of the *lengths* of the bars whereas a histogram represents quantities by means of the *areas* of the bars. This distinction acquires some force when you contemplate (a) interpreting variable-width histograms or (b) what happens as the amount of data increases and the bar widths decrease (the data histogram approaches a probability density function, if one exists). The area interpretation does not preclude using histograms to represent discrete data, but (b) explains chl's reference to continuous variables.
Comment: That is what I'm trying to do in Excel :/
What's the difference between a bargraph and a histogram?
Comment: Late comment, but I am happy to regard **bar chart** as a general **graphical** term for any chart with bars, including histograms as a special case; and **histogram** as a specifically **statistical** term for a representation of a frequency distribution using bars; the bars should touch when the variable is continuous and binned; but the bars may be separate when the variable is discrete. So my senses are broader than those given above.
Comment: @whuber Naturally I agree. I didn't and wouldn't define a histogram as requiring bars of equal width. I've seen bar charts with unequal widths that weren't histograms. Most importantly,  emphasis on area as a key principle would be essential  in a fuller, self-contained explanation.


Android - Create Button Programmatically

Question: I have an Activity called GameLoop (class which extends Activity).
But instead of using an xml file for the layout, i'm using a class for it, since I want to be able to draw to a canvas. (I've seen on some tutorials this is what you're supposed to do)
The layout class is called GameLoopLayout.
I have a game loop running in the layout class, I can render bitmaps to the screen and control the FPS, everything is fine.
But now I want to add a button to it, but since i'm not using an xml layout file, I don't know how to do it. Can anyone help me out please?
What I'm doing atm:
GameLoopLayout:
Button button;
Canvas canvas;
SurfaceHolder surfaceHolder;

public GameLoopActivityLayout(Context context) {
    //all necessary initializations here...
    button = new Button(context);
    button.setEnabled(true);
    button.setLeft(10);
    button.setTop(20);
}

//render function called during game loop
private void render() {
    if (!surfaceHolder.getSurface().isValid())
        return;
    canvas = surfaceHolder.lockCanvas();
    //draw all game objects to canvas...
    button.draw(canvas);
    surfaceHolder.unlockCanvasAndPost(canvas);
}

Answer: try to below code :
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout2);

// add button
Button b = new Button(this);
b.setText("Button added dynamically!");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
b.setOnClickListener(this);
ll.addView(b);

Comment: Care to explain how this works? What is the linearLayout2, and where do i get it? same question for id My_BUTTON
Comment: @Tirafesi private static final int MY_BUTTON = 100; add this in your code.
Answer: Creating custom Views does not prevent you from having XML layouts. For example:
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.yourpackage.GameLoopLayout
        android:id="@+id/game_loop_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ... />

</FrameLayout>

You can use margins and android:layout_gravity to place the button wherever you like.
In code, get access to your GameLoopLayout like you would any other view:
// inside of onCreate()
mGameLoopLayout = (GameLoopLayout) findViewById(R.id.game_loop_layout);
// do setup with GameLoopLayout

Comment: Ok, somehow I've made it work, even though I'm quite lost tbh. Could you explain to me what's being done here, please? Here's the onCreate method:

setContentView(R.layout.game_loop);

layout = (GameLoopLayout) findViewById(R.id.game_loop_layout);
Comment: @Tirafesi What are you confused about? This is the standard way to do UI on android. You pass an XML layout to`setContentView()`, then you look up the view by the ID that you set in the XML. That's all that's happening.
Comment: I've finally understood it! I thought that my custom view was the same thing as a layout, and that's why i had to setContentView(myCustomLayout). But now i've realized that i am simply creating my own view object, which then i put inside the xml file, like if it was a button, or textView etc. thanks for all the help!


EntityFramework 6 + LazyLoadingEnabled + using()

Question: Preciso de um help. Meu problema é o seguinte: Não consigo retornar os itens do meu objeto.
Segue meu código para analise.
Classe Cliente
public partial class Cliente
{
    public Cliente()
    {
        this.ClienteEndereco = new HashSet<ClienteEndereco>();
    }

    public int IdCliente { get; set; }
    public string Nome { get; set; }

    public virtual ICollection<ClienteEndereco> ClienteEndereco { get; set;}
}

Classe ClienteEndereco
public partial class ClienteEndereco
{
    public int IdClienteEndereco { get; set; }
    public int IdCliente { get; set; }
    public int IdCidade { get; set; }
    public string Endereco { get; set; }

    public virtual Cidade Cidade { get; set; }
    public virtual Cliente Cliente { get; set; }
}

Método de consulta
    public IList<T> ListarTudo()
    {
        using (MeuContext context = new MeuContext())
        {
            context.Configuration.LazyLoadingEnabled = false;

            return context.Set<T>().ToList();
        }
    }

Quando chamo minha consulta os itens do ClienteEndero me retornam Count = 0:
var clientes = repositorioCliente.ListarTudo();

Sei que se eu colocar o no método de consulta Include("ClienteEndereco") ele irá retornar todos meus itens, porem esse método é genérico, então alterei o método passando os includes necessários.
    public List<T> ListaTudo(string[] includes)
    {
        using (MeuContext context = new MeuContext())
        {
            IQueryable<T> query = context.Set<T>();
            if (includes != null)
                foreach (var includeProperty in includes)
                {
                    query = query.Include(includeProperty);
                }
            return query.ToList();
        }
    }

Mas agora, toda chamada que eu fizer lá no meu Controller (MVC) para todos os métodos eu terei que passar a lista de includes necessários.
private readonly RepositorioGenerico<Cliente> repositorioCliente = new RepositorioGenerico<Cliente>();

private string[] includes = {"ClienteEndereco","ClienteEndereco.Cidade"};

var Clientes = repositorioCliente.ListaTudo(includes);

Além de achar que meu código está ficando muito poluído estou tendo muito trabalho para mapear em todos os Controllers os Includes necessários, só para lá na minha View não estourar o erro de:

"The ObjectContext instance has been disposed and can no longer ...."

Tem alguma outra forma de trazer os itens sem que eu necessite utilizar Includes?
Answer: Se você está tendo muito trabalho, significa que está usando a ferramenta errado, e isto é evidente pela sua explicação.
Pelo jeito não vou poder cansar de dizer que o Entity Framework jé é um repositório, então você não precisa implementar outro repositório. Veja as respostas que já dei a respeito:

Entity Framework DDD Infra repositório Genérico
Unidade de trabalho (Unit of Work) com repositório
Lugar em que devem ficar métodos de interação do CRUD com o banco em ASP.NET MVC
Como manter sempre 1 registro no BD após inserir com entityframework?
EF6 erro de EntityValidationErrors em propriedade preenchida
Boas práticas com .NET MVC
problema com update Entity Framework 6
Camada de Aplicação
Como funciona o Tracking / Chache de objetos do EntityFramework?

Sobre Model Cliente
Isto não precisa ser feito. O Entity Framework controla as propriedades de navegação automaticamente, então nada precisa ser inicializado. A parte abaixo pode ser retirada do código:
public Cliente()
{
    this.ClienteEndereco = new HashSet<ClienteEndereco>();
}

Sobre o Método de Consulta
Não há motivo pra você desativar o Lazy Load neste momento. Ele só se justifica caso você tenha uma massa muito grande de registros para usar, o que dificilmente é o caso.
Além disso, esta construção aqui:
return context.Set<T>().ToList();

Faz o Entity Framework realizar um FULL TABLE SCAN no seu banco de dados. O correto é montar a sentença no DbSet e só usar .ToList() com a devida parametrização. Ou seja, está construção é péssima para o desempenho.
Sobre o problema do Include
Os problemas que você está tendo ocorrem pela insistência de você usar um repositório genérico onde não precisa.
Este tipo de construção é completamente desnecessária e deve ser abandonada:
public List<T> ListaTudo(string[] includes)
{
    using (MeuContext context = new MeuContext())
    {
        IQueryable<T> query = context.Set<T>();
        if (includes != null)
            foreach (var includeProperty in includes)
            {
                query = query.Include(includeProperty);
            }
        return query.ToList();
    }
}

Se preciso listar tudo, como por exemplo clientes, posso fazer apenas:
var clientes = context.Clientes.ToList();

Se preciso carregar dados do cliente e quero carregar por JOIN endereços, posso fazer da seguinte forma:
var clientes = context.Clientes.Include(c => c.ClienteEndereco).ToList();

Ou seja, não há qualquer motivo pra continuar uma implementação com repositório genérico. Simplesmente use o Entity Framework como mostram os tutoriais que a otimização dos dados ocorre naturalmente em quase todos os casos.
Para outros casos, pergunte aqui no site.


Equivalence relation, product and quotient spaces

Question: I have a problem with the following:
"Define a relation $\sim$ on $R^2$ by $(u,v) \sim (x,y)$ if and only if both $u-x$ and $v-y$ are integers. Show that for each point $(x,y) \in R^2$ there exists at least one point $(u,v) \in [0,1] \times [0,1]$ such that $(u,v) \sim (x,y)$ and deduce that $R^2/\sim$ is compact. ($\sim$ is an equivalence relation.)"
My guess is that it has something to do with homeomorphism and torus but could not move on. I would appreciate any help.
Comment: Have you done the first part of the hint and shown that each point of the plane is equivalent to some point in the unit square?
Comment: No, I haven't. Not sure how to approach it.
Comment: Think about the factional part of a number.
Comment: That's *fractional*, of course!
Answer: HINT: To show the first part of the hint, think about fractional parts of $x$ and $y$. Once you've done that, you know that $R^2/\!\sim$ is homeomorphic to $[0,1]^2/\!\sim$. Which points of $[0,1]^2$ are related? Can you see why $[0,1]^2/\!\sim$ is a torus?
Comment: Hm, I don't find it intuitive at all that each point of $R^2$ is equivalent to some point of the unit square. Related points are $0$ and $1$ I guess. Is it torus because when I take points $(0,0)$, $(1,0)$ and try to glue them with $(0,1)$ and $(1,1)$ I will have to bend it to get the cylinder and then bend again it's open ends which would give me torus?
Comment: @Jim: For the first part, given $\langle x,y\rangle\in\Bbb R^2$, consider the point $$\big\langle x-\lfloor x\rfloor,y-\lfloor y\rfloor\big\rangle\;.$$ There are more pairs of related points in the unit square. For instance, $\langle 0,y\rangle\sim\langle 1,y\rangle$ for each $y\in[0,1]$. Thus, the identifications force you to roll the square into a cylinder and then join the ends of the cylinder.
Comment: Ah, of course. For the compactness part, is it enough to say that $R^2/\!\sim$ is compact, since it is homeomorphic to $[0,1]^2 /\!\sim$ which is compact because it is closed and bounded? And do I really need to construct homeomorphism from the square to the torus or all of of the above is enough?
Comment: @Jim: Once you've shown that it's homeomorphic to $[0,1]^2/\!\sim$, you can definitely conclude that it's compact, since it's the continuous image of the compact set $[0,1]^2$. As for the rest, it depends on how fussy the person marking the answer is. It's not actually terribly hard to write down an actual homeomorphism with, say, the set obtained by revolving the circle $(x-2)^2+y^2=1$ about the $y$-axis, but it is finicky and tedious.
Comment: Ok, I will think about that, probably not necessary then. But I need to construct the homeomorphism between $$R^2/\!\sim$$ and square or I just say as above?
Comment: @Jim: Let $f:\Bbb R^2\to\Bbb R^2/\!\sim$ be the quotient map. By definition $U\subseteq\Bbb R^2/\!\sim$ is open if and only if $h^{-1}[U]$ is open in $\Bbb R^2$. Now show that this is true if and only if $h^{-1}[U]\cap[0,1]^2$ is open in $[0,1]^2$; it follows that the restriction of $h$ to $[0,1]^2$ is the quotient map from $[0,1]^2$ to $[0,1]^2/\!~\sim$.
Comment: Great, thanks a million!
Comment: @Jim: You're welcome!


How do I participate in ITTF events as a player?

Question: I looked through all the ITTF events but I couldn't find a way to register for any of these events. I am a new table tennis player and my objective is to play in official matches.
On the ITTF events webpage, it is just dates and locations, but no register button or link. Could someone explain how these events work?
Additional question: Some said that it is free to participate in ITTF events, and some said that it costs $10,000. Which is true?
Comment: Are you beating players at your club? From experience of being a member of sports clubs (but not table tennis) You need to play in club competitions, if you do well then you may be asked to represent the club in their local league and you begin to make your way up the levels of competitions.
Answer: To answer the question as asked: you (personally) can't enter those highest level tournaments; entry is by invitation only.
So, how do you get invited? My showing that you are good enough in the second tier of tournaments, something like national championships. However, they are probably invitation only as well.
So, how do you get invited to national championships? Probably by competing in the highest level leagues in your country and consistently winning matches. How do you get to play in those leagues? By persuading a club that you are good enough. How do you persuade a club you are good enough? By winning matches in lower level leagues. And so on, and so on until you're at beginner level leagues.
It all begins with joining a club.


Android opening Instagram intent with image causes crash

Question: I am developing an app for Android which should have the functionality to take a picture, and share it to the Instagram app.
The app opens up the camera, takes a picture and then the Instagram app is opened with the "Crop photo" window active. It seems to be loading the picture, but after a couple of seconds the app crashes, i can't see that the image ever gets loaded.
I am developing the app on top of Appcelerators Titanium platform, however i do not think that my problem is related to Titanium, but rather how i pass the image.
Since the emulator doesn't have the Instagram app, i am developing on my Galaxy S4. I have tried running logcat through adb to get some sort of error message to help me, but only thing i see is that it notices that Instagram exited.
Here is my code, what could be wrong? I have checked that the image is saved into the filesystem.
<code>Ti.Media.showCamera({
success: function(event) {
    var file = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,"ggs-instagram.jpg");
    file.write(event.media);
    var instaIntent = Ti.Android.createIntent({
        action: Ti.Android.ACTION_SEND,
        packageName: "com.instagram.android",
        type: 'image/jpeg'
    });
    /*instaIntent.putExtra(Ti.Android.EXTRA_TEXT, "EXTRA_TEXT");
    instaIntent.putExtra(Ti.Android.EXTRA_SUBJECT, "EXTRA_SUBJECT");*/
    instaIntent.putExtra(Ti.Android.EXTRA_STREAM, file.getNativePath());
    Ti.Android.currentActivity.startActivity(instaIntent);
},
cancel: function() {},
error: function (error) {
    if (error.code == Ti.Media.NO_CAMERA)  {
        alert("Din telefon/platta har ingen kamera!");
    } else {
        alert("Kamerafel!");
    }
},
mediaTypes:         [Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO],
showControls:       false,
autohide:           false,
saveToPhotoGallery: true
});
</code>
Comment: I had seen a similar issue online almost six months back(dont have the link) where the solution was to add FLAG_ACTIVITY_CLEAR_TOP to the intent and that had worked for a similar problem. Try that.
Comment: @Slartibartfast unfortunately it made no difference :/
Comment: Well see if there is a known internal issue with Instagram itself from their website like here: http://help.instagram.com/379302862144995/
Comment: Also it would help if you posted some logcat - even if its garbled junk- maybe someone here would understand it :)
Comment: please add log for above crash
Answer: pls take a look at
Instagram from Android open on certain user and add caption to uploaded image

Instagram Option in Sharing Intent Android
Android: post image and text to Instagram
Comment: None of those links answered my question. I have been looking at those questions before, and use it as reference when i implemented my solution, but still doesn't work


Qual lógica utilizar para escrever este programa em C?

Question: Estou resolvendo uma lista de exercícios sobre pilhas e filas e travei em uma questão onde pede para escrever o programa de acordo com pseudo código da questão.
Tenho pouca experiência com C, então, não estou conseguindo resolver essa questão.
Queria a ajuda de vocês do SO para criar esse programa.
Programa:
Programa inverte var P : Pilha;

n : inteiro;

s : literal;

Início

Imprima('Entre com uma frase: ');

Leia(s)

Inicia(P); //{Torna a pilha vazia}

Para n de 1 até COMP(s) faça

PUSH(P, s[n]);

Enquanto não Vazia(P) faça //{pilha vazia, para}

Imprima (POP(P));

Fim-enquanto;

Fim

Comment: E qual sua dúvida? Até onde chegou? Nos motre seu código atual para que possamos ajudá-lo a resolver seu problema, e não fazer seu exercício.
Answer: Boa tarde Leonardo,
Primeiramente vamos quebrar o problema em pequenas partes:

O que seu programa deve fazer?

Pelo título posto, "inverte", é fácil deduzir que ele quer inverter uma string usando uma estrutura de pilhas, onde o usuário vai digitar uma palavra/frase e a mesma deve ser impressa invertida ao final da execução.

Mas a final, como posso fazer isso utilizando pilhas?

Pilhas são estruturas de dados do tipo LIFO [Last in, First out], ou seja, o último elemento a entrar deve ser o primeiro a sair.
Ilustração:

A partir disso podemos deduzir que, para inverter sua string usando uma pilha, basta empilhar e desempilhar em seguida.

Dicas para a implementação:

Já que você não tem muita experiência com C, eu fortemente sugiro que você estude a aplicação do malloc, do...while() e, principalmente, ponteiros.
Tradução de comandos do seu pseudo código:
Imprima = printf();
Leia = scanf();
Enquanto = while();
Para = for(;;); [Laço de repetição, assim como o while]
Espero ter ajudado, abraços e bons estudos!


How to connect to ssh with .ssh directory?

Question: My co-worker sent me a '.ssh' directory with files in it. He said that I can put that directory in my user directory then connect to ssh without password (ssh root@ip).
I put that directory in my home directory then tried ssh root@ip, but it didn't work.
Am I missing something?
Comment: I have no words to express how horrible this is. Enumerating: 1. sending a .ssh directory around (which contains **private** keys); 2. that, to connect without a password, which means that you have **unprotected keys**, password-less keys, instead of using an ssh-agent; 3. that, for the **root** account. Please, learn how to properly use SSH.
Comment: Please post the output of `ls -l ~/.ssh`.
Answer: Two things here.
1) You coworker sent you a .ssh directory (horrible idea btw, but thats another issue..) Inside here there is a file called authorized_keys which holds one or many "SSH Public keys". The "connection without passphrase" that he is talking about happens when you connect and offer up a private key and the system recognizes a matching public key in .ssh/authorized_keys. If you do not have said ssh private key then this folder is essentially useless. This key needs to be on the client side not server side. Look inside the .ssh folder, is there a id_rsa file? if so copy that to your client and load it up inside Pagent or inside Putty.
2) You said you put this inside your home directory, lets say /home/Moon. Now you try to login as root@ip.
SSH will look inside /root/.ssh/ for the files NOT /home/moon/.ssh/ because you tried to login as root NOT as Moon. Depending on your distro you can log into your own account and sudo or su to root. Putting a passphrase-less key for root is all kinds of horrible.
Finally a word of warning.. you coworker gave you his .ssh directory that contains an authorized_keys file to some unknown private key. Unless you really really really trust your coworker this is a horrible idea. If your home folder has a .ssh directory with someone elses public key in the authorized_keys file then they can log into your user WITHOUT providing your system password. Essentially your coworker could log in as you and do whatever he wanted under your name and no one could prove otherwise.
If you want to do this yourself and do it properly do the following.

Logged in as your normal user type in the command
ssh-keygen -t rsa
Follow the prompts, select default for everything (I recommend you enter a password for your key however).
Copy your public key into your authorized keys file, deleting old content.
cat ~/.ssh/id_rsa.pub > ~/.ssh/authorized_keys
Copy the ~/.ssh/id_rsa file to your client computer, using either Pagent, Putty, ssh -i, or some other key manager load/open id_rsa. Now SSH to yourusername@ip and you will not need a prompt.
Answer: The .ssh directory should (If your co-worker has done it correctly) contain a public key which you need to add to your authorized keys file. Open a terminal and type
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
(That may not be the correct command, the directory you were sent should have one .pub file in, cat that instead, whatever it's called)
You should probably also suggest to them that sending the entire SSH directory is a very bad idea, for one thing you now have his private key. Also any previously authorized keys or known hosts have been overwritten, they should have just sent you the id_rsa.pub file.
Alternatively your sshd may not be configured to allow key based auth, consult the docs for specific instructions on how to do this.
Answer: Another possibility: depending on how you extracted the .ssh directory, you may not own the files you created (which is a prerequisite for most versions of ssh to connect).  Try chown -R $USER. ~/.ssh and chmod -R g-rwx,o-rwx ~/.ssh.


How to extend a set to fit a basis

Question: If I have the set $\{(3, −2, 1, 3),(−1, 3, −3, 4),(3, 8, 7, 0)\}$, how can I extend this into a basis of $\mathbb{R}^4$?
I have seen questions in the past asking to reduce a set in order to fit it into a basis, but I am unsure how to do the opposite.
Any help with this issue would be greatly appreciated.
Comment: Would this post answer your question? https://math.stackexchange.com/questions/1740134/extending-basis-for-span-of-3-vectors-into-basis-for-r4
Comment: That certainly helps. However, once I have it in reduced row echelon form, how do I find the new vector itself?
Comment: As the answer says, you look at the pivot columns (which in that example are the first four columns) meaning that the first four columns of the augmented matrix $A$ is your basis for $\mathbb{R}^4$, so in that example, the fourth vector in the basis would be $(1,0,0,0)^T$ .
Comment: I see. That answer seemed too simple. To clarify, if I wanted to extend into, say, the 5th or 6th dimension, I would use the respective 5th and 6th columns?
Comment: I think you would need to view the lower dimensional space ($\mathbb{R}^4$) as being embedded in the higher dimensional space ($\mathbb{R}^5$ or $\mathbb{R}^6$). Kaj Hansen's answer illustrates this quite nicely: https://math.stackexchange.com/questions/2808038/how-to-extend-a-basis-for-mathbbrn-to-a-basis-for-mathbbrn1?rq=1
Answer: Make a $4\times4$ matrix whose first three rows are your vectors, and whose last row is $(a\ b\ c\ d)$. Compute the determinant of this matrix (by expansion along the bottom row. would be a good way). Then choose any $a,b,c,d$ that make this determinant nonzero.

How to extend a set to fit a basis


Moving elements to other page regions

Question: I want to move the page breadcrumb to the content region in Bartik (D7.)
I assume it is theming but I can't find anywhere (style.css, layout.css) where the breadcrumb is assigned in the first place.
Does anyone know how to do this?
Thanks. :)
Answer: I will again answer my own question here:
The change is made in the page.tpl.php template found the the template directory of your theme.
In this case, all I had to do is move the following:
<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>

from it's present location under the main-wrapper to its new location under the content heading. Then I cleared the theme registry cache.
Make sure that if you move an "if" statement, that you always move its corresponding "endif" statement too.
:)

Moving elements to other page regions


Norm function in OpenCV

Question: How can I take easily norm of an array?
I tried this and I have an error:

too many initializers error C2440: 'initializing' : cannot convert
  from 'cv::OutputArray (__cdecl *)(void)' to 'double'

double DaisyFeature [200];
double DaisyFeature1 [200];

double norm( DaisyFeature , DaisyFeature1 , NORM_L2,noArray);

I think the problem is something about initializing but I don't know what should I use instead of double DaisyFeature [200];
Answer: The documentation is pretty clear on how Input/OutputArrays work. The documentation can be found here.
It basicly states that you can assume that any algorithm implemented by openCV accepts the following types as input (and output);

cv::Mat, std::vector<>, cv::Matx<>, cv::Vec<> or cv::Scalar
Answer: Use an std::vector instead of arrays:
std::vector<double> DaisyFeature(200);
std::vector<double> DaisyFeature1(200);

norm( DaisyFeature , DaisyFeature1 , NORM_L2,noArray);

Norm function in OpenCV


Cloning content types and corresponding Display Suite settings

Question: I need to clone a content type, so I choose to do that with module: Bundle copy.
I need to clone Display Suite settings of my bundle as well. How would I clone that? (Found a patch that enables that with Bundle copy: https://drupal.org/node/2055157). Wondering is there any better solution?
Comment: Hello. Pooling questions are not so good here. And having 3 of them asked as one is not really the best approach either.
Comment: Hi guys! How about this? Just edited the question. :)
Answer: Nevermind, found a solution:

Bundle copy version 7.x-2.x-dev allows cloning directly (without exporting/importing and changing bundle's machine name).
There is a patch that gives support for display suite cloning, exporting and importing. (I had to fix the patch first to be able to apply it with patch manager.)

All worked like a charm!


counter_cpu_share_used com alerta vermelho - PowerPanel

Question: Resource counter_cpu_share_used red alert on environment 170 dominio.com current value: 89 soft limit: 85 hard limit: 95

Por vezes no log de recursos da este aviso vermelho, o que me preocupa, a dúvida é.. Como posso debugar isso no PowerPanel? Tentei ver algo nos processos que estão sendo executado, mas não consigo entender como isso pode me ajudar.
Servidor é VPS.
Vou deixar printado o System Proccess, afim de facilitar o entendimento do meu cenário atual.
Answer: Boa noite,
Não tenho experiência com power panel, mas tenho com outros softwares similares de gestão e no post tem poucas informações. Mas estudei um pouco materiais da net e vou tentar te ajudar.
Para começar, aqui há um PDF (em inglês), com informações de administração deste sistema.
Na página 62 (Monitoring Operations and Viewing Logs) fala um pouco sobre a exibição e configuração desses logs.
Isso está acontecendo porque o processamento atingiu um limite pré estabelecido no parâmetro counter_cpu_share_used. Para debugar, você tem que analisar a lista de processos em Container Services dashboard, indo no link System Processes e ver quais processos estão consumindo mais recursos, através da coluna TIME, você vê quais processos estão usando mais tempo da CPU. Daí precisa estudar se deverá mudar a aplicação/serviço ativo, restringindo o uso, caso possível, ou se deverá aumentar a CPU da sua VPS.
Pelo o que eu vi das imagens que postou, é um indicador quantitativo, ou seja, só conta o número de processos ativos. Isso só será um problema se a % da CPU estiver alta.
É comum o apache disponibilizar processos para cada conexão. Aqui há uma explicação detalhada disso e como limitar os processos (em inglês).
Segue um trecho:

For example, Apache needs 1000 processes to handle 1000 concurrently connected clients, or connections.

tradução:

Por exemplo, O Apache precisa de 1000 processos para lidar com 1000 clientes conectados simultaneamente, ou conexões.

Se o tempo da cpu (em %) não estiver auto, basta você ajustar o parâmetro counter_cpu_share_used, para um valor mais auto, caso contrário, você terá que estudar uma ação para esse serviço, seja melhorar processamento ou restringir usuários/conexões simultâneas.
Qualquer dúvida, estou à disposição.
Comment: Alterei a resposta com uma nova referência. Qual é a % do tempo da cpu? Se não estiver alta, você pode alterar o parâmetro, caso contrario, vai ter que analisar mais a fundo o que está gerando o consumo auto.
Comment: Disponha. Quanto à dúvida, porque o **_counter_cpu_share_used_** está contando o número de processos em uso enquanto os 49% do uso da CPU é o tempo que a CPU consome computando, em porcentagem. Isso significa que 51% do tempo ela está ociosa, por isso perguntei "Qual é a % do tempo da cpu". Acho que a solução seria somente mudar o parâmetro do log e colocar algo em torno de 130 processos como crítico, o que pelos dados que você me disse, representaria em media 70% do uso da CPU e não dária mais alertas desnecessários no log.
Comment: Alexandre, achei [aqui](http://kb.odin.com/en/117211) uma descrição detalhada do problema e como resolve-lo. (Em Inglês).

[Aqui](https://mediatemple.net/community/products/dv/204645150/troubleshooting-dv-memory-issues#2) também tem uma boa fonte de informação, para fazer um estudo nos processos e ver se é hack, defeito na aplicação ou se é normal.
Me parece que o buraco é mais embaixo do que estávamos pensando. Esse alerta, pelo o que diz nesse artigo, é realmente do uso da cpu e não um simples contador do número de processo. O que quer dizer que seu contêiner está realmente sobrecarregado.
Comment: Boa! Vou processar essas informações e volto após aqui para ver o que consegui entender, obrigado!
Comment: Printei ali(coloquei na postagem) a ultima parte dos processos na sessão System Proccess, o que me preocupa é o Command que parece repetido, com time alto(maior que os outros processos,.. Esse Command repete varias e varias vezes:  `/usr/local/apache/bin/httpd -k start -DSSL`
Comment: Não entendo quando diz: "Qual é a % do tempo da cpu",.. O que me estranha que a CPU usada diz 49%, quando o parametro `cpu_share_used` está quase estourando(perto dos 95 quando o limite é 95). Obrigado pela atenção, e pelo tempo tempo é claro.. valeu!
Comment: Eric, eu andei procurando como mudar o parâmetro `counter_cpu_share_used`, mas sem sucesso. Eu acredito que mudando esse parâmetro meu servidor vai deixar de cair(percebi que ele cai quando o valor corrente ultrapassa o limit(95)).  Como posso mudar esse valor? Mesmo assim se voltar a cair pelo menos deixaria de exibir estes alertas, o que já ajuda. Grato.
Comment: Apenas para constar, eu resolvi mudar para um plano dedicado, e vou começar a trabalhar com memcached para deixar o servidor mais performático, thanks Eric, agradeço a persistência em meu caso, até mais.


Visually comparing two models based on the per-observation AIC

Question: In order to visually compare two models (logistic regression, in case that it matters) I thought of plotting the contribution of the individual observations to the AIC of the respective model. The plot looks like this:

One can see that, although for some observations the full model makes larger errors than the simple one (i.e. a larger contribution to the AIC), for the majority of the observations the per-observation AIC is lower for the full model. The linear regression (the orange line) reflects that by being below the diagonal dotted line. This, I hope, gives some visual support for using the full model---assuming that the model selection is based on the AIC in the first place.
Are plots like these actually used in practice and do they have an established name?
If not, why? Is this plot in any way misleading or unclear?
Comment: Linear regression is not symmetrical.  If you regressed X on Y, would the orange line be above the diagonal?  Moreover, what is the justification for treating X as fixed & Y as (partly) random?
Comment: If the idea is to argue for the full model, what is the advantage of this method over just reporting that the full model's AIC is lower?  Is someone arguing that the lower AIC is due to just some of the data or something?
Comment: @gung-ReinstateMonica (1): Yes, since the regression line must pass through the $(\bar{x}, \bar{y})$. Regarding randomness, if it were for predictive modelling, I'd worry more about the non-normality and heteroskedacticity of the errors. But I'm just interested in an intuitive visualisation.
Comment: @gung-ReinstateMonica (2): This is just a general example. In my case at hand I have the opposite situation: The full model has a slightly lower AIC than a simpler one (467 vs. 469, less than 0.5% difference). I want to argue that the simpler model is sufficient; that the difference in AIC is likely random. The graph shows the observations neatly aligned along the diagonal.
Comment: Good point regarding $(\bar x, \bar y)$, but I bet it would cross the diagonal.  Is the simpler model nested within the full model (e.g., the full model has X1-5, & the simpler model only has X1)?
Comment: @gung-ReinstateMonica Re: regression: Thanks, you convinced me that it's the $\bar{x}, \bar{y}$ that is actually relevant, not the line. Re: models: Yes, they are nested.
Comment: Igor, AIC is optimal in a well defined sense under a certain set of assumptions. You seem to be looking for a reason not to use AIC. If so, might it be that the goal of your analysis does not justify AIC as a model selection criterion to begin with? Or might it be that it does, in which case you might be straying away from the optimal choice without a theoretically sound argument? See [AIC versus Likelihood Ratio Test](https://stats.stackexchange.com/questions/198799/aic-versus-likelihood-ratio-test-in-model-variable-selection/198863#198863) which tells you AIC and LRT serve different goals.
Answer: I've never heard of that plot.  It may already exist and have a name, however, I suspect it would not be persuasive to a reasonable skeptic, if it's sufficiently esoteric.  Simply based on human psychology, people will find things they're familiar with persuasive and be skeptical of someone trying to persuade them of something based on something they've never heard of.  For what it's worth, I do think it's interesting—I like plots and thoroughly exploring data to ensure I understand them fully.
In your actual case, I gather you want to argue for the simpler model even though the AIC for the full model is ever so slightly lower.  I have heard various times that an AIC that isn't more than 1% lower shouldn't be trusted, but I certainly don't have a citation for that.
Instead, I think there may be a simpler solution.  You state that the models are nested.  You can perform a nested model test / simultaneous test of all added variables in the full model.  For logistic regression, that would be a likelihood ratio test.  In R, the code would be something like:
<code>anova(simple.model, full.model, test="LRT")
</code>
@Glen_b has shown that a lower AIC corresponds to a p-value of approximately .16, so such a test is unlikely to be significant by conventional standards.
Comment: Different tools are meant for different goals: [AIC versus Likelihood Ratio Test](https://stats.stackexchange.com/questions/198799/aic-versus-likelihood-ratio-test-in-model-variable-selection/198863#198863). I do not find it quite reasonable to contemplate the choice between a LR test and AIC once the goal of the analysis has been determined.


Compute $\sum \binom{n}{k} \binom{n+k-1}{k} (-1)^k$

Question: How can we study a series like this :
$\sum_{k=0}^{n} \binom{n}{k}\binom{n+k-1}{k} (-1)^k$.
I thought about consider $S(x) = \sum_{k=0}^{n} \binom{n}{k}\binom{n+k-1}{k} x^k$. But the only one I've found is hypergeometric function. It's hard to analyze.
Hope there are more combinatorical ideas for finding such series.
Any hints? Maybe generating functions?
Answer: $[x^k]:f(x)$ means the coefficient of $x^k$ in the function $f(x)$. So for instance
\begin{eqnarray*}
\binom{n}{k}=[x^k]: (1+x)^n.
\end{eqnarray*}
So for your sum we have
\begin{eqnarray*}
\sum_{k=0}^n (-1)^k \binom{n}{k} \binom{n+k-1}{k} &=& [x^0]: \sum_{k=0}^n (-1)^k \binom{n}{k} \frac{(1+x)^{n+k-1}}{x^k} \\
&=& [x^0]: (1+x)^{n-1} \left(1- \frac{(1+x)}{x} \right)^n \\
&=& [x^n]: (1+x)^{n-1} (-1)^n =\color{red}{0}.
\end{eqnarray*}
Answer: Here we  have  the  Chu-Vandermonde Identity  in disguise.

We     obtain         for        $n>0$:
  \begin{align*}
\color{blue}{\sum_{k=0}^n}&\color{blue}{ \binom{n}{k}\binom{n+k-1}{k} (-1)^k}\\
&=\sum_{k=0}^{n}\binom{n}{n-k}\binom{-n}{k}\tag{1}\\
&=\binom{0}{n}\tag{2}\\
&\,\,\color{blue}{=0}
\end{align*}
and the claim follows.
Comment:

In (1) we use the   binomial identities  $\binom{p}{q}=\binom{p}{p-q}$ and  $\binom{-p}{q}=\binom{p+q-1}{q}(-1)^q$.
In (2) we apply the Chu-Vandermonde identity.
Answer: You may also use shifted Legendre polynomials. Rodrigues' formula ensures
$$P_n(2x-1)=(-1)^n\sum_{k=0}^{n}\binom{n}{k}\binom{n+k}{k}(-1)^k x^k $$
hence
$$\sum_{k=0}^{n}\binom{n}{k}\binom{n+k-1}{k}(-1)^k=\sum_{k=0}^{n}\binom{n}{k}\binom{n+k}{k}(-1)^k\frac{n}{k+n}=n(-1)^n\int_{0}^{1}P_n(2x-1)x^{n-1}\,dx $$
and the RHS is zero, since $P_n(2x-1)$ is orthogonal to any polynomial with degree less than $n$.
Answer: Using Vandermonde's Identity and Negative Binomial Coefficients
$$
\begin{align}
\sum_k\binom{n}{k}\binom{n+k-1}{k}(-1)^k
&=\sum_k\binom{n}{n-k}\binom{-n}{k}\\
&=\binom{0}{n}\\[9pt]
&=[n=0]
\end{align}
$$
Note that $\binom{-1}{0}=1$.

Using Finite Differences
For $n\ge1$,
$$
\sum_k\binom{n}{k}\binom{n+k-1}{k}(-1)^k
=\sum_k(-1)^k\binom{n}{k}\binom{n+k-1}{n-1}
$$
which is an order $n$ repeated difference of a degree $n-1$ polynomial, and therefore, vanishes.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[15px,#ffd]{\sum_{k = 0}^{n}{n \choose k}
{n + k - 1 \choose k}\pars{-1}^{k}}
\\[5mm] = &\
\sum_{k = 0}^{n}{n \choose k}
\bracks{{-\bracks{n + k - 1} + k - 1 \choose k}\pars{-1}^{k}}\pars{-1}^{k}
\\[5mm] = &\
\sum_{k = 0}^{n}{n \choose k}{-n \choose k}\ =\
\bbox[15px,#ffc,border:1px solid navy]{\delta_{n0}}
\end{align}


Intersection $f(G\cap \mathbf{R}) \subset \mathbf{R} \Leftrightarrow f(\bar{z}) = \overline{f(z)}$

Question: $G\subset \mathbf{C} , G= \{z\in \mathbf{C}| \overline{z}\in G\} = \overline{G}$, then for $f\in \mathcal{O}(G)$ it holds that:$$f(G\cap \mathbf{R}) \subset \mathbf{R} \Leftrightarrow \forall z\in G : f(\overline{z}) = \overline{f(z)}$$
This is an example in the script of our professor, however there is no proof for it and it hasn't been shown during the lectures either.
Proof   :
$"\Rightarrow " :$ Let $f(G\cap \mathbf{R}) \subset \mathbf{R}$, so all points on the real axis are mapped to the real axis. That means $f$ does not have any imaginary part, because then this would not be true anymore. Since f does not have any imaginary part. it follows also that : $f(\overline{z}) = \overline{f(z)}$
$"\Leftarrow" :$ Let $f(\overline{z}) = \overline{f(z)}$, so f can not have any imaginary part, otherwise this would not be true anymore. But if f doesn't have any imaginary part, then the map of the real axis is always on the real axis. So $f(G\cap \mathbf{R}) \subset \mathbf{R}$
What I mean with not having any imaginary part is that it is of the form $f(z) = z ; f(z)=2z; f(z) = 2z+z^{3}$ etc.
I am not sure if this is the right thought, and how to express this better.
Help is greatly appreciated.
Comment: Thanks for your attention. I tried to show it in my edited post.
Comment: Yes, G is a domain. :)
Comment: Ah, okay. I think it's good to mention that sort of thing, just for reassurance.
Comment: I don't follow your $"\Rightarrow"$. If I write $f = u(x, y) + iv(x, y)$, then we find that $v(x, 0) = 0$ for all $x \in G \cap \mathbf{R}$. I don't see how to finish off from there -- maybe there are facts about harmonic functions that we could use?
Answer: ($\Rightarrow$) I think it should be straightforward to check that the function $\overline{f(\bar z)}$ is holomorphic on $G$. Then $f(z) - \overline{f(\bar{z})}$ is a holomorphic function on $G$ which vanishes along an interval on the real axis.
($\Leftarrow$) I think you have the right idea, but we should write down some equations. Try to use the fact that $z = \bar z$ if and only if $z \in \mathbf R$; if you take $z \in \mathbf R \cap G$ and conjugate $f(z)$, what happens?
The problem is very related to the Schwarz reflection principle.
Answer: :) :) :)  Dylan Moreland :) :) :)
$$"\Rightarrow: "$$ If $f(G\cap\mathbf{R})\subset \mathbf{R}$, then for every $z_{0} \in \mathbf{R}$ we can write $f(z)= \sum_{k=0}^{\infty} a_{k}(z-z_{0})^{k}$, $a_{k}\in \mathbf{R}$. From this it follows immediately that $\overline{f(\overline{z})}=f(z)$ in a neighborhood of the real axis. Because of the identity theorem these two holomorphic functions must be the same everywhere.$$"\Leftarrow":$$ If $z\in \mathbf{R}$, $\overline{z}=z$. Then  $f(\overline{z})=\overline{f(z)}= f(z)$ $\forall z\in \mathbf{R}$, so $f(z) \in \mathbf{R}$ , which means that $f(G\cap \mathbf{R})\subset \mathbf{R}$
Is this ok? Thank you for your help.
Comment: No problem! I agree with your "$\Leftarrow$". For the other direction, it isn't clear to me how you get $a_k \in \mathbf R$. I think the holomorphicity should be obtainable without thinking about power series--let me try to work that out. The identity theorem is definitely what you want to use.


When and why do we use sparse coding?

Question: Sparse coding is described as "given an input $X$, finding a latent representation $h$ such that h is sparse and the input can be reconstructed as well as possible." (source: https://www.youtube.com/watch?v=7a0_iEruGoM)
My question is why do we want to find a latent representation ? I mean, what's the benefit of sparse coding? Why do we want to reconstruct the input if we have it in the first place? To which type of problem would we say: "Ok! I am going to use sparse coding for that!"
Comment: it's also more interpretable than dense factorization. for a given data element, a sparse coding lets you "summarize" what's "going on" in the data.
Answer: Parsimony. Sparse representations of a signal are easier to describe because they're short and highlight the essential features. This can be helpful if one wants to understand the signal, the process that generated it, or other systems that interact with it.
Denoising. In this context, the measured signal is a mixture of some underlying/true signal and noise. The goal is to remove the noise. If the underlying signal is sparse in some basis (which is often the case for interesting signals) and the noise is not (e.g. white noise), then denoising can be done by constructing a sparse approximation of the measured signal.
Data compression The goal here is to store the signal, transmit it over a communication channel, or perform further processing on it. These operations require memory, communication, and computational resources that scale with the size of the signal. Sparse coding can be used to compress a set of signals, reducing the resources needed.
Compressed sensing The goal here is to measure signals efficiently by exploiting knowledge about their structure. This allows more efficient storage and transmission, and may also allow measurements to be made more quickly. Typically, specialized hardware is involved. If a signal is known to be sparse in some basis, it's possible to acquire it using fewer measurements than would otherwise be necessary. The original signal can then be reconstructed from the reduced set of measurements. Sometimes a class of signals is known a priori to be sparse in a particular basis. For example, natural images are sparse in the wavelet basis. In this case, the known basis can be used to design the measurement and reconstruction procedure. But, if the basis isn't known, it can be learned from a set of example signals using sparse coding (aka dictionary learning).
Comment: +1 for the excellent answer. Thought I would add avoiding the [curse of dimensionality](https://stats.stackexchange.com/questions/169156/explain-curse-of-dimensionality-to-a-child) as another motivation to use a latent space.
Answer: "In numerical analysis and computer science, a sparse matrix or sparse array is a matrix in which most of the elements are zero." Wikipedia
There are some datasets where instances have a large number of attributes. This dataset can be thought of as a sparse matrix if most of the recorded attribute are zero. In this scenario we could potentially have a very large file containing the dataset without an equivalent amount of "information."
One way to reduce the size of the dataset files without losing any information is to use a sparse file format. For example, an ARFF file can be stored in either dense or sparse format.
From Weka's documentation, the header information is the same between the two formats. The difference is in how the instances are represented. The instances in the dense representation look like this:
<code>0, X, 0, Y, "class A"
0, 0, W, 0, "class B"
</code>
While a sparse representation of the same instances looks like this:
<code>{1 X, 3 Y, 4 "class A"}
{2 W, 4 "class B"}
</code>
It can be seen that the first instance, where most of the attributes are nonzero, becomes longer in the sparse representation. The second instance, however, has mostly zeros as attributes and is represented more efficiently. If most of your dataset is like the second instance - if the dataset is a sparse matrix - then a sparse file format might make sense to reduce the size of storing the dataset with no loss in information.

When and why do we use sparse coding?


Replicação unilateral no PostgreSQL

Question: Tenho dois servidores. Um é única e exclusivamente para testes. O outro é para a produção propriamente dita. Eu preciso que o banco de dados de testes, contenha os mesmos dados do banco de dados da produção. Eu não posso fazer um espelhamento, visto que se eu fizer isso, as mudanças no servidor de testes obviamente afetarão os dados da produção, e isso seria catastrófico!
Eu preciso então de uma forma de somente fazer uma sincronização Servidor -> Cliente, sem jamais fazer o inverso (Cliente -> Servidor). Preciso que essa sincronização aconteça todas as noites.
O que pode ser feito neste caso?
Answer: Se é apenas um servidor de testes eu recomendo fortemente fazer a cópia dos dados por demanda e não fazer on-line. Você terá que montar scripts que façam isto para você. Em geral é coisa simples, é fazer o dump do banco de dados como se fosse fazer um backup, colocar no local adequado e restaurar no outro servidor. Provavelmente você não precisa mais que isto. Existem várias formas de obter o mesmo resultado.
Mas se tiver um real motivo para replicar tem algumas formas.
Na verdade a maioria das soluções podem, mesmo que opcionalmente, replicar em apenas uma direção. Eu diria que a maioria só pode fazer em uma direção.
Me parece que você precisa no máximo de uma replicação por log. Acho que é o mais simples. A documentação do PostgreSQL fala sobre isto. Tem a opção de streaming mas no seu caso é exagero.
O log shipping tem baixo overhead no servidor principal e funciona bem sem muita complicação. Ela não oferece capacidades de alta disponibilidade ou redundância imediata, nem pode ser usando em balanço de caraga mas não parece ser o que você precisa.
Também tem o Slony. Eu acho que é um canhão para matar passarinho mas é uma opção.
Outra opção semelhante é o Bucardo.
Existem outra soluções que não lhe atende (apesar de eu achar que estas também não são boas ideias) ou eu não conheço. Um deles seria o PGPool-II que libera o servidor principal apenas para atender as requisições de produção mas exige um hardware adicional para coordenar o envio de queries para os servidores, não é vantagem no seu caso.
O PostgreSQL evoluiu muito e já possui soluções nativas para replicação, dê uma olhada no estado atual antes de considerar as opções apresentadas aqui.
Acho que outras soluções podem ser usadas independente do banco de dados. É possível usar utilitários rodando pelo sistema operacional que repliquem o conteúdo. Mas também duvido que sejam melhores.
Coloquei no GitHub para referência futura.
Comment: mas o que seria cópia sob demanda?
Comment: Quando você precisa dos dados no servidor de teste, você manda fazer uma transferência dos dados. Precisa fazer um *script* para cuidar disto. Se é teste você não precisa estar coim os dados exatos do servidor de produção em cada segundo.

Replicação unilateral no PostgreSQL


Problems reading sheet music with visual disability

Question: I'm not really sure if "visual disability" is correctly said since english is not my native language and had to use Google Translator.
My worries are about reading sheet music.
I'm trying to learn playing trumpet, and only a few days into it, not even a month, but have played guitar for years and I think I have some musical sensitivity developed and I understand what musical scores' symbols and notation mean.
Though I learn by ear with more ease than if I haven't played any instrument before, I want to be able to read sheet music, mainly for learning more and using some exercise book, either digital or physical books, so I can try to do it like professional musicians do when learning songs, and even try to learn to fluently read while playing (if possible).
My problem is that I've been losing sight over the years due to a visual disease and I have very little sight. I can't read properly, and scores are written normally with a small font size. I have to use high contrast and bigger font size in order to be able to not have that many problems.
I tried software like "Guitar Pro", "Musescore" etc but would not find anything that puts scores at least in high contrast, since most of these software lets you make some kind of zooming.
Do you know of any app, software or anything that lets me read sheet music more confortably at least for learning purposes with my instrument?
I edit:
I managed to change page's background color in Musescore 3, I know how to change fonts and different symbols and notations size, text color and style and font type, but I don't know how to change lines and notes and symbols' color to white since they are black and can't be seen on a black background.
Comment: unfortunately you don't tell us what device you have: phone? tablet? pc?
If you are looking for sheet music and search for images you can choose those with the highest resolution.
Comment: Have you tried your computer's accessibility features? There might be an option to make everything high-contrast or negative, white on black instead of black on white.
Comment: @piiperi I use high contrast on windows but since most software nowadays use third party libraries to create their interfaces, since those libraries are not native, they are not affected by Windows Accessibility, at least high contrast.
Comment: I am also looking for a software solution - my cataracts are getting worse (and they're in no hurry to surgically correct them!), but I need to be able to read lyrics as well. Learning choral music by ear is rather time-consuming and I often have to pick up and sing church music within a day or two. It is fairly easy to enlarge a pdf of sheet music from 8.5 x 11 to 11 x 17, which helps, but I also have a serious problem with glare; white paper is painful to read. I can use the Accessibility preference setting for pdfs of digital scores, but not for scanned (image) scores. A tablet is also too
Comment: @SusanHouston Just an FYI, I've added a new answer that discusses two commercial and two non-commercial, software-based, music-reading solutions for the blind and visually impaired, plus links to additional resources.
Answer: you can save a screen print or an image copy img,pgn etc, a pdf and zoom it or enlarge it 200% or 400% with any foto programm or picture app as paint etc.
I just did download a sheet with very small resolution:

I tried to enlarge it: The result was very bad!

Than I clicked into the same picture on the webside, made a full screen image and copied it with a snipping tool:

I opened it with a foto app and enlarged it again and copied it with a snipping tool:

latest edit:
I have found now a much simpler solution: Save the sheet music as image file and open it with the foto viewer of windows 10. There is a magnifier and you can follow the lines by the arrows (left-right and up-down. So you hold in one hand your trumpet and with the other you can guide through the sheet.
If you can't read this solution I you must train your ear that you'll be able to play any music just by listening.

Comment: you still didn't tell what device you are using. I have found now a much simpler solutione: save as image and open with the foto viewer of windows. There is a magnifier and you can follow the lines by the arrows (left-right and up-down. So you hold in one hand your trumpet and with the other you can guide through the sheet. look the latest edit of my answer.
Comment: This can be a decent solution. I wish there was a solution like a web app, or tablet or pc program that displayed scores in a reversed colors and maybe auto scroll lines of a entire song or exercise.
Comment: so can't you just download the pdf and zoom it and let it scroll down? or use a pdf invert reader: *Open a PDF file (any file) in Adobe Reader. Go to Edit>Preferences. In the Preferences window, click the 'Accessibility' tab and enable the 'Replace Document Colors' option. Next, select 'Use High-Contrast Colors' and select a color scheme from the presets available.*
 https://www.addictivetips.com/windows-tips/invert-colors-in-a-pdf-file-for-better-night-time-reading/
Comment: Yes, I know that, but sometimes it doesn't work. Text keeps being invisible or nothing appears sometimes. PDF that is made with images normally doesn't work well.
Comment: PC.
Training the ear is a solution I like and see the most confortable for me, since I already have some ease to learn by ear. However, If I am learning trumpet, my worries are to learn to do some things wrong, play fast notes without knowing if I have to slur or legatto instead of articulating them, and I guess in sheet music all those details are specified so I know when to articulate and how and that's a big question I have right know. I'm trying to learn articulating and learning by ear maybe I can't tell when a sequence of notes are articulated, when to use single tonguing...
Answer: I recommend you take two steps. One is to find a "Sheet music viewer" application, of which there are many. Grab one which supports a page-turn pedal.
Next, either
1)  use a PDF editor that can convert to the "negative" of the source file, or
2) use the native operating system of your tablet to specify "white on black" display.
Answer: It will obviously be very limiting to require music that is specifically formatted to your requirements.  You need a way to take ANY piece of printed music and make it readable.  Which suggests a camera, some computer processing and a screen.
The tablet I'm typing this on has a rear camera and a zoom function. Various processes, including contrast control, are available.  Could this be a way forward for you?
Comment: may be a bit complicated. I was thinking more on a software solution.
Answer:
Three software solutions plus additional resources

1. Lime Lighter
LimeLighter software by Dancing Dots allows for the scanning of print music or importing MusicXML scores, which it then can magnify up to 10x with configurable color contrast options. It also allows for user score marking. Dancing Dots offers a free, time-limited evaluation download, and they also offer pre-configured packages which include a computer pre-loaded with the software.
Both the Dancing Dots website and several articles mentioning the software give the number 610-783-6692 to get more information.
2. Power Music
The Royal National Institute of Blind People, in collaboration with Cambron Software Limited, has created Power Music Accessible Format, which, as described on the RNIB Modified Stave Notation page (see also #3 below), is similar, and possibly superior, to LimeLighter. Power Music's various offerings can be viewed at their online store.
3. Notation systems
The Royal National Institute of Blind People describes music notation standard called Modified Stave Notation which can be implemented via MuseScore. It involves modifying existing scores by, for example, thickening stems and widening staff line vertical spacing without increasing the spacing from note to note.
There is an entirely different alternative music notation developed by Dodeka. Their notation uses vertical positioning, color, and bars of varying length to depict pitch and duration.1 They have a page discussing applications of their system for the blind and visually impaired, and, since their notation requires existing music to the re-notated, they are also developing a music library.
4. Additional resources

The article "Music Technology For The Visually Impaired", by Chris Chaswell, includes a list of resources for blind and visually impaired music students and their teachers.

The National Resource Center for Blind Musicians discussed LimeLighter as well as links to other resources. They also have a page dedicated to an extensive list of resources for the blind and visually impaired.

1 In a sense, not a new notation at all, but rather a reinvention of the ancient system of neumes that eventually developed into our current notation system.


Why use more than one type of shell for a single task?

Question: I am fairly new to high performance computing, and I've inherited some exiting code for the task I'm working on.  As it stands now, I have a Linux-based HPC using MPI and PBS to queue and run jobs.  What I inherited is python script that dynamically builds and submits a PBS script to the queue, but through the course of a single job, .sh, .csh, and .ksh scripts are called at various points, and most of the shell scripts are very simple, typically less than 10 lines.  Is there any advantage to using multiple different shell flavors in a single job?  Is there any obvious reason that I shouldn't just convert them all to a single flavor?
Comment: Unless you can show us the code this probably belongs on [Software Engineering](https://softwareengineering.stackexchange.com/). The main (only?) reason to use multiple languages for any task is that they each excel at solving different *parts* of that task. This seems unlikely in the case of shell scripts, and the situation is probably a historical accident.
Comment: In my experience there is no good technical reason for using different shells, but there are often non-technical reasons.  One is the "black-box" syndrome, in that if a program does what you want, why rewrite it?  Different people had a fetish about different shells.  I was brought-up on csh purely because it was the default on Sun (the guy who wrote csh founded Sun), fortunately I was cured a long time ago.  ksh was far superior but was not open source until (I think) 2000, so bash was used on Linux.  So the reason for the different languages is probably historical.
Comment: It's hard to answer this. Generally, if the scripts are trivial I think it's worth converting them all to one language. It's hard to definitely say that without seeing the scripts, which is why I voted to close this question as "primarily opinion based".
Comment: @l0b0 Fair point.  The code is an both huge and a huge mess.  Sharing something intelligible here isn't really doable, but I suspect you're right.  My sense of things is that this has been cobbled together over the course of several iterations and developers.  I'll pose the question over there and see if there are any ideas.
Comment: If you decide to convert them I suggest you first document what they do generally in a language-independent way.  Then write new code using the documentation, line-by-line conversion is rarely a good idea.  Also consider a system with fewer scripts using a more powerful language like python.  However always remember the adage *if it ain't broke don't fix it*.
Comment: My guess would also be a bunch of developers each writing their own way. Before you decide to rewrite everything in a more decent way, consider the life cycle. Do you expect a lot of changes in the code the next 5 years, or are you only trying to keep it running until someone shuts off the electricity?
Answer:
Is there any advantage to using multiple different shell flavors in a single job?

Highly unlikely.
The primary differences between these shells, especially at this scale, will simply be their syntax. In particular, csh uses a more "C-like" syntax for certain control structures like if and for; ksh will be more similar to the Bash syntax you're probably familiar with. Their feature sets are essentially identical.
The most likely reason that these interpreters were used is simple: the scripts were written by different authors long ago, before consensus had emerged around the use of the Bash shell. (If they're old enough, it's even possible that Bash didn't exist at the time -- csh and ksh were released in 1978 and 1983, whereas Bash didn't come around until 1989.)
Comment: Performance can be a significant difference -- genuine David Korn ksh93 is (unlike its various clones) **far** faster than bash to execute (and within a single base-10 order of magnitude of awk). But then, if you're going to mix languages to avoid implementing a tight inner loop in a slow shell, why wouldn't you take that 10x performance difference and use awk, or use an even faster/more modern language like Go or Julia? :)
Comment: (...that said, I wouldn't ever advice csh for use by anyone, ever; it has the same kind of inattention to good design that plagues PHP).
Comment: Floating point can also be an issue, even in a small script.  ksh93 supports floating point, the others do not.
Comment: ...also, until bash 4.x (which has closed the gaps quite effectively), ksh93 had a substantial lead in features -- associative arrays, namevars, etc; I can think of substantial non-performance-related reasons to prefer ksh93 over a pre-4.0 bash.
Comment: @CharlesDuffy Remember that this is in the context of a couple of scripts that are "typically less than 10 lines". I doubt that either speed or features are a major consideration here!


Distance from center of circle to point on line segment

Question: Imagine any two fixed points $A$, $B$ inside a circle, and add a third point $C$ on the line segment $\overline{AB}$.
We may write
$$
\vec{c}=\vec{a}+\mu(\vec{b}-\vec{a})
$$
and name $a$, $b$ and $c=c(\mu)$ the distance of each of those points from the center of the circle.
I'm looking for any simple relation of $c$ in terms of $\mu$ and given $a$ and $b$, because what I could come up with so far does look far more complicated than one might expect, so maybe I'm missing something.
From law of sines:
$$
c = \mu(1-\mu)d\left(\frac{\sin\alpha}{\sin\delta_1}+\frac{\sin\beta}{\sin\delta_2}\right)
$$
(actually looks quite nice, but $\delta_1$ and $\delta_2$ are dependent of $\mu$).
From law of cosines:
$$
c^2=\tfrac12(d^2\mu^2+d^2(1-\mu)^2+a^2+b^2)-d(a\cos\beta\cdot\mu+b\cos\alpha\cdot(1-\mu))
$$
Comment: The circle seems irrelevant. It may constrain the positions of $A$ and $B,$ but to actually answer the question you only need to know those positions, not the reason why other positions were not chosen.
Answer: Note
$$
\vec{c}=\vec{a}+\mu(\vec{b}-\vec{a})=(1-\mu)\vec a +\mu \vec b
$$
Then
$$c^2 = (1-\mu)^2a^2 +\mu^2 b^2 +2\mu(1-\mu)\vec a \cdot \vec b$$


Creating a new table with a column for count of values for another column

Question: I have a table aisle_list that has columns order_id and aisle_id.
Below is an example:
order_id aisle_id
1        21
1        24
1        83
1        95
1        108
1        120
36       0
36       2

I want to create a new table with a column that lists the count of the count of unique aisle_ids for each order_id where the count is 4, 5, or 6. So I need to have a nested select with one group by.
CREATE TABLE sample_path AS
SELECT a.order_id, a.aisle_id, x.count_num_aisles
FROM aisle_list as a,
(SELECT count(*) as count_num_aisles FROM aisle_list
GROUP BY order_id) as x
WHERE count_num_aisles IN (4, 5, 6);

Desired result:
order_id aisle_id count_num_aisles
1        21       6
1        24       6
1        83       6
1        95       6
1        108      6
1        120      6

The query is taking forever to run. Can someone offer a solution?
Answer: Why not just use group by and having?
SELECT a.order_id, count(distinct aisle_id) as num_aisles
FROM aisle_list a
GROUP BY a.order_id
HAVING count(distinct aisle_id) BETWEEN 4 and 6;

Comment: A much easier solution! I just started with SQL so I'm still learning. Thank you.


Why are 16th notes in groups of 3 not adding up to 4/4?

Question: So whats up with the last measure?
It seems that the last two notes are too much.
There are already 4 times 4 1/16 notes?

It's a piece from Bach; BWV 597
Comment: Need more info. Composer/title/period? Does look like it's gone into 5/4 but forgotten to tell the bass line. Wonder if the next bar's in 3/4...
Comment: Next bar is 4/4 again
Answer: The pitches were correct - but the beaming was wrong and the tuplets omitted entirely
Comment: And this is why un-notated triplets (most common with eighth-note triplets) will come back and bite you in the butt some day.


Next.js server component when converting to client component giving issues

Question: I am working on a blog site with next.js. I have a home page which is a server component but now I wanted it to change to a client component so that I can make it interactive( integrate pagination).
But when I converted the code to client component, it started giving me issues such as browser window seems stuck from time to time with localhost opened. Also the api requests getPosts method is not storing by react's useState's setState function somehow strangely.
given below is the previous server component for the home page -
import { getCategoryPosts, getPosts } from '@/services'
import styles from '../../app/page.module.scss'
import PostCard from './PostCard'

type Props = { categorySlug?: string }

async function HomePagePosts({ categorySlug = '' }: Props) {
  const { postsContainer } = styles
  let posts
  if (!categorySlug) {
    posts = await getPosts()
  } else {
    posts = await getCategoryPosts(categorySlug)
  }

  return (

      {posts.map((post) => (
        <PostCard post={post} key={post.title}></PostCard>
      ))}

  )
}

export default HomePagePosts

and below is the new client component -
'use client'

import { useEffect, useState } from 'react'
import { getCategoryPosts, getPosts } from '@/services'
import styles from '../../app/page.module.scss'
import PostCard from './PostCard'

type Props = { categorySlug?: string }

function HomePagePosts({ categorySlug = '' }: Props) {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    async function setAllPosts() {
      if (!categorySlug) {
        setPosts(await getPosts())
      } else {
        setPosts(await getCategoryPosts(categorySlug))
      }
    }
    setAllPosts()
  }, [])

  const { postsContainer } = styles

  return (

      {posts.map((post) => (
        <PostCard post={post} key={post.title}></PostCard>
      ))}

  )
}

export default HomePagePosts

The above code is causing infinite loop resulting in window being stuck and also posts state is rendering to be empty and not updating.
Though if I console log the getPosts() method it gives me the correct content in return, so something is wrong with this conversion.
EDIT -
I have noticed something -
return (

      help
      {posts?.map((post) => (

{post.title}

        // <PostCard post={post} key={post.title}></PostCard>
      ))}

  )

the above code gives the correct post.title content
but if I use the <PostCard/> component then only its keep loading and goes to infinite loop and do not show any content in posts state.
PostCard component is a server component which is an async functional compoenent, so can that be issue ?
Here is the PostCard code -
import { postsType } from '@/utils/types/types'
import styles from '../../app/page.module.scss'
import moment from 'moment'
import Link from 'next/link'
import Image from 'next/image'
import { myPortfolioURL } from '@/services'
import LikeButton from '../buttons/LikeButton'
import CommentButton from '../buttons/CommentButton'

type Props = { post: postsType }

async function PostCard({ post }: Props) {
  const {
    postCard,
    postImage,
    title,
    summary,
    authorName,
    authorInfo,
    authorInfoContainer,
    authorImage,
    date,
    icon,
    userFeedbackContainer,
    leftAlign,
    rightAlign,
    readTimeContainer,
    postReactionSection,
  } = styles
  const authorId: string = (await myPortfolioURL(post.author.id)) || '/'
  return (

        <Link
          href={authorId}
          className={authorInfo}
          rel="noopener noreferrer"
          target="_blank"
        >

            <Image
              src={post.author.photo.url}
              style={{ objectFit: 'cover', borderRadius: '50%' }}
              sizes="(max-width: 768px) 40px, (max-width: 1200px) 50px, 40px"
              fill={true}
              alt={post.author.name}
            />

{post.author.name}

        </Link>

{moment(post.createdAt).format('MMM DD, YYYY')}

      <Link href={`/post/${post.slug}`}>

          <Image
            src={post.featuredImage.url}
            style={{ objectFit: 'cover', borderRadius: '.5rem' }}
            fill={true}
            alt={post.title}
          />

      </Link>

        <Link href={`/post/${post.slug}`} className={title}>
          {post.title}
        </Link>

{post.summary}

            <LikeButton postId={post.id} />
            <CommentButton postId={post.id} />

{post.readTime} min read

  )
}

export default PostCard

Comment: `setPosts(await getPosts())`  That shouldn't even work, as you have not marked the `useEffect` as been `async`  are you not getting a compiler error?
Comment: Please share full code. including code for getPosts()
Comment: @Keith sorry for the partial code but I have just updated the code now it has async func but the issue remains the same
Answer: You can not have async effect. Thus you need to do following
 useEffect(() => {
    getPosts().then(data => setPosts(data));
  }, [])

Update:
As per the updated question. I notice that you are using Server component PostCard as a child of client component. This is the cause of the error. All children of client component are always client components.
Thus, you should remove server side code from the client component and also make it not async.
Comment: thanks for the help but its still not working!
Comment: What's the error message?
Comment: Also share your getPosts code
Comment: there is no error message, it just keep loading infinitely and also getPosts is working fine (actually I am using graphql so its code is pretty long). You can see my editted question I have updated some of my insights that the Child component is making some issue in this.
Comment: Please share your PostCard code
Comment: shared it on the editted part of the question
Comment: Updated the answer - basically you can not use server side code on client component or it's children
Comment: okay this seems to be promising, will try.