Root of a simple equation with imaginary exponent

Question: Let $i=\sqrt{-1}$. What is the solution of $(x-1)^i = 0$?
EDIT: I try to solve the following boundary value problem for $a>0$:

with $\lambda>0$ and $y(a)=0$. It is corresponding to the radial part of the Klein-Gordon equation of a scalar field inside its own Schwarzschild radius $a$. The solution of this equation is (from Maple)

I try to find the (spectrum) values of $\lambda$, for which the boundary condition $y(a)=0$ is satisfied. Since $HeunC(...)$, for $x=a$, is constant ($\neq 0$), I have to ask for a solution of $(a-x)^{i\times const}=0$.
I have not expressed this context in the initial question because I don't think that somebody finds it interesting...
Comment: Apparently $0^{-i}$ is undefined, at least according to Wolfram alpha.
Comment: Also $z^i$ is undefined.The complex logarithm has many branches. On the other hand we expect that exponential functions, if well-defined, do not vanish.
Answer: Hint: If $z, \alpha \in  {\Bbb C}$, define $z^\alpha= \exp(\alpha \log z)$,
where $\exp$ is defined in some independent manner such as by a power
series.


In how many ways can a selection be done of $5$ letters?

Question:
In how many ways can a selection be done of $5$ letters out of $5 A's, 4B's, 3C's, 2D's $ and $1 E$.

$ a) 60 \\
b) 75 \\
\color{green}{c) 71} \\
d.) \text{none of these} $

Number of ways of selecting $5$ different letters = $\dbinom{5}{5} = 1$ way
Number of ways to select $2$ similar and $3$ different letter = $\dbinom{4}{1}\times \dbinom{4}{3}=16$.
Number of ways of selecting $2$ similar + $2$ more similar letter and $1$ different letter = $\dbinom{4}{2}\times \dbinom{3}{1}=18$.
Number of ways to select $3$ similar and $2$ different letter = $\dbinom{4}{2}\times \dbinom{3}{1}=18$.
Number of ways to select $3$ similar and another $2$ other similar = $\dbinom{3}{1}\times \dbinom{3}{1}=9$
Number of ways to select $4$ similar and $1$ different letter = $\dbinom{2}{1}\times \dbinom{4}{1}=8$
Ways of selecting
$5$ similar letters = $1$
Total ways = $1+16+18+18+9+8+1= 71$

Well I have the solution But I am not able to fully understand it.
Or if their could be an $\color{red}{\text{alternate way}}$ than it would be great.
I have studied maths up to $12$th grade.
Comment: Does this answer your question? [How to find the number of $k$-permutations of $n$ objects with $x$ types, and $r_1, r_2, r_3, \cdots , r_x$ = the number of each type of object?](https://math.stackexchange.com/questions/2372/how-to-find-the-number-of-k-permutations-of-n-objects-with-x-types-and-r)
Comment: What *exactly* is it that you don't understand ? It has been laid out pretty clearly case by case....
Comment: For example just from the second line $\dbinom{4}{1}\times \dbinom{4}{3}$ till last one $\dbinom{2}{1}\times \dbinom{4}{1}=8$
Comment: Is this the book solution ?
Comment: @true: Yes from book
Comment: Ok, I am explaining in answer,
Answer: If Order is Unimportant
The number of ways to choose $5$ letters (if their order is unimportant) is the coefficient of $x^5$ in
$$
\begin{align}
&\small\overbrace{(1+x)\vphantom{x^2}}^{1\text{ E}}
\overbrace{\left(1+x+x^2\right)}^{2\text{ D's}}
\overbrace{\left(1+x+x^2+x^3\right)}^{3\text{ C's}}
\overbrace{\left(1+x+x^2+x^3+x^4\right)}^{4\text{ B's}}
\overbrace{\left(1+x+x^2+x^3+x^4+x^5\right)}^{5\text{ A's}}\\
&=\frac{1-x^2}{1-x}\frac{1-x^3}{1-x}\frac{1-x^4}{1-x}\frac{1-x^5}{1-x}\frac{1-x^6}{1-x}\\
&=\frac{1-x^2-x^3-x^4+O\left(x^7\right)}{(1-x)^5}\\[3pt]
&=\small\left[1-x^2-x^3-x^4+O\!\left(x^7\right)\right]\!\left[1+5x+15x^2+35x^3+70x^4+126x^5+210x^6+O\!\left(x^7\right)\right]\\[9pt]
&=1+5x+14x^2+29x^3+49x^4+71x^5+90x^6+O\!\left(x^7\right)\tag{1}
\end{align}
$$
where we used the Binomial Theorem for $(1-x)^{-5}$ above.

The coefficient of $x^5$ in $(1)$ is $71$.

If Order is Important
If the order of the letters is important, we can compute the exponential generating function with
$$
\begin{align}
&\small\overbrace{(1+x)\vphantom{\frac{x^2}{2!}}}^{1\text{ E}}
\overbrace{\left(1{+}x{+}\frac{x^2}{2!}\right)}^{2\text{ D's}}
\overbrace{\!\left(1{+}x{+}\frac{x^2}{2!}{+}\frac{x^3}{3!}\right)}^{3\text{ C's}}
\overbrace{\!\left(1{+}x{+}\frac{x^2}{2!}{+}\frac{x^3}{3}{+}\frac{x^4}{4!}\right)}^{4\text{ B's}}
\overbrace{\!\left(1{+}x{+}\frac{x^2}{2!}{+}\frac{x^3}{3!}{+}\frac{x^4}{4!}{+}\frac{x^5}{5!}\right)}^{5\text{ A's}}\\[3pt]
&=\small1+5x+24\frac{x^2}{2!}+111\frac{x^3}{3!}+494\frac{x^4}{4!}+2111\frac{x^5}{5!}+8634\frac{x^6}{6!}+O\left(x^7\right)\tag{2}
\end{align}
$$

The coefficient of $\frac{x^5}{5!}$ in $(2)$ is $2111$.
Answer: Let $x_i$ be the number of letter $i$ chosen for $1\le i\le 5$, where we number the letters in alphabetical order.
We want to find the number of solutions in nonnegative integers to the equation $x_1+\cdots+x_5=5$
$\hspace{.5 in}$with the restrictions $x_1\le5,\; x_2\le4, \;x_3\le3,\; x_4\le2, \;x_5\le1$.
Let $S$ be the set of all solutions, and let $A_i$ be the set of solutions with $x_i\ge7-i$ for $i=2,\cdots,5$.
Using Inclusion-Exclusion, we have that
$\hspace{.15 in}\displaystyle\big|\overline{A_2}\cap\overline{A_3}\cap\overline{A_4}\cap\overline{A_5}\big|=|S|-\sum_{i}|A_i|+\sum_{i<j}|A_i\cap A_j|-\sum_{i<j<k}|A_i\cap A_j\cap A_k|+\cdots$
$\hspace{1.53 in}=|S|-|A_2|-|A_3|-|A_4|-|A_5|+|A_4\cap A_5|$
$\displaystyle\hspace{1.53 in}=\binom{9}{4}-\binom{4}{4}-\binom{5}{4}-\binom{6}{4}-\binom{7}{4}+\binom{4}{4}=\color{red}{71}$.
Answer: Second line: You can get 2 of a type  from A,B,C or D so $4\choose 1$. Then ${4\choose3}$ to select 3 different letters from the 4 types not yet selected, and finally, apply multiplication principle.
Second last line: 4 of a type only from A or B, so ${2\choose1}$, 1 more selection from the remaining 4 types, ${4\choose 1}$, and multiply.
You should be able to understand the remaining along similar lines.
Answer: Ok so we are breaking this down by case:
<code>Case 1: none of our letters are the same and we pick 5 distinct letters

Case 2a: exactly 2 of the letters are the same and the other 3 are distinct.

Case 2b: 2 of the letters are the same, 2 others are the same, and the fifth is distinct.

Case 3a: exactly 3 of the letters are the same and the other 2 are distinct.

Case 3b: exactly 3 of the letters are the same and the other 2 are also the same.

Case 4: exactly 4 of the letters are the same and the other 1 is distinct.

Case 5: all 5 letters are the same.
</code>
We see that any combination must be one of these $5$ cases, and there is no overlap in the $5$ cases. Thus we are going to sum up the number of total possibilities for each case.

Case 1: If we pick $5$ distinct letters, we pick one of each letter, so there is only $1$ way to do this.
Case 2a: First lets count the ways to pick the $2$ letters which are the same. It can't be E, so there are only $4$ ways to pick them. Second, we must pick $3$ more from the remaining $4$ letters (none of these can be the same letter as the first $2$ since that would be a different case). Thus we use $4$ choose $3$, which turns out to be $4$ options. We multiply these together to see that we have $4\times 4=16$ options for case 1.
Case 2b: We are now picking two pairs from four possible letters which have sufficient quantities. Thus the ways to pick the two pairs is $4$ choose $2$. The fifth letter is any of the remaining $3$ letters, so we have $6\times 3=18$ for this case.
Case 3a: Similarly, there are only $3$ ways to pick $3$ matching letters. Then we proceed to pick the other $2$ from $4$ choices, so we multiply $3$ by $4$ choose $2$ to get $3\times 6=18$ options for case 3.
Case 3b: There are $3$ ways to pick the triplet and the other pair only has $3$ options also, since it can't be the same letter as the triplet (that would be case 5). Thus there are $3\times 3=9$ possibilities.
Case 4: Hopefully you follow the pattern: there are only $2$ ways to pick $4$ of the same letter, and $4$ ways to pick the fifth letter, so we have $2\times 4=8$ for this case.
Case 5: Finally, there is only one way to pick $5$ of the same number.

Summing those together we get $1+16+18+18+9+8+1=71$ options. For me, this is the most straightforward approach once you understand it.
Answer: Well, you could just hammer through all of the possibilities. (You'll also appreciate why the shortcuts are there.)
Number of ways of selecting 5 different letters:
ABCDE  (1)
Number of ways to select 2 similar and 3 different letter:
AABCD AABCE AABDE AACDE
BBCDE ABBCD ABBCE ABBDE
ACCDE ABCCD ABCCE BCCDE
ABCDD ABDDE ABCDD BCDDE (16)
Number of ways of selecting 2 similar + 2 more similar letter and 1 different letter:
AABBC AABBD AABBE
AACCD AACCE AABCC
AABDD AACDD AADDE
BBCCD BBCCE ABBCC
ABBDD BBCDD BBDDE
ACCDD BCCDD CCDDE (18)
Number of ways to select 3 similar and 2 different letters:
AAABC AAABD AAABE AAACD AAACE AAADE
ABBBC ABBBD ABBBE BBBCD BBBCE BBBDE
ABCCC ACCCD ACCCE BCCCD BCCCE CCCDE (18)
Number of ways to select 3 similar and another 2 other similar:
AAABB AAACC AAADD
AABBB BBBCC BBBDD
AACCC BBCCC CCCDD (9)
Number of ways to select 4 similar and 1 different letter:
AAAAB AAAAC AAAAD AAAAE
ABBBB BBBBC BBBBD BBBBE (8)
Number of ways to select 5 similar letters:
AAAAA (1)
Let's look at just one of these sets to see if we can get a feel for the nomenclature:
Number of ways to select 3 similar and 2 different:
$$\dbinom{4}{2}\times \dbinom{3}{1}=18$$
This is read "$4$ choose $2$ times $3$ choose $1$." This is shorthand for:
$$\frac{4!}{2!(4-2)!}\times\frac{3!}{1!(3-1)!}$$
which is shorthand for:
$$\frac{4\times 3\times 2 \times 1}{2 \times 2 \times 1} \times
\frac{3\times 2 \times 1}{1 \times 2 \times 1} = 18$$
Okay, but why?
One of those "chooses" refers to the 2 similar, and the other to the 3 similar. Note that they are all laid out in 3 groups of 6.
Perhaps I will come back later to go over the theory in more detail....


Powershell is it possible to store csv headers and value in hashtable

Question: Is it possible to store entire CSV file data in hashtable as headers as keys and respective values as value pair?
I wanted this use in pushing correct data in SQL table.
Sample csv file:
id,fname,lname,shift,day,night
1,ert,sdf,08/21/2017 Day,2,-
2,wer,asdf,08/21/2017 Day,-,1
3,rty,adsf,08/21/2017 Day,1,-
4,yui,adsf,08/21/2017 Day,-,-
5,qwe,asdf,08/21/2017 Day,-,-
6,ret,asdf,08/21/2017 Day,-,-
7,chh,asdf,08/21/2017 Day,-,-
8,sdf,cxvv,08/21/2017 Day,1,-

I wanted to access in values so I can loop over keys, something like:
id => 1
fname => ert
lname => sdf
shift => 08/21/2017 Day
day => 2
night => -
id => 2
fname => wer
lname => asdf
shift => 08/21/2017 Day
day => -
night => 1
...
So on

Comment: [`Import-CSV`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/import-csv?view=powershell-5.1). Please consider editing your question. It's hard to understand.
Comment: How would you distinguish the rows if they're all keyed by column header?
Comment: Each row is an indexed element in the returned object, as already shown by Nahuel
Answer: Have you tried Import-Csv Cmdlet
>  $csvData=Import-Csv example.csv

>  $csvData[0]

id    : 1
fname : ert
lname : sdf
shift : 08/21/2017 Day
day   : 2
night : -

>  $csvData[0].shift

08/21/2017 Day

>  $csvData.length

8

so valid keys are 0..7
EDIT : to loop over keys
$keys = $csvData[0].psobject.properties | % { ,@( $_.name ) }

$csvData[0].($keys[0])

or
$keys | %{ echo "$_ => $($csvData[0].$_)" }

and
0..7 |%{ $i=$_; $keys |%{ echo "$i,$_ => $($csvData[$i].$_)" } }

Comment: In addition to your answer, as OP wants to loop through keys: `$csvData.Keys | ForEach-Object {Write-Host "`$_ => $($csvData[$_])"}` edit:Sure, it has to be in it's own iteration.
Answer: In adition to Nahuel's answer, looping through the item's keys looks as follows:
$csvData = Import-CSV data.csv

foreach ($element in $csvData) {
    Write-Host "Element:"
    $element.Keys | ForEach-Object {Write-Host "`t$($_) => $($element[$_])"}
}


Guardar alguns elementos de um struct array em outro struct array

Question: Tenho definido um struct array struct CAMPO campo[2] na qual será apontado por um ponteiro struct CAMPO *ptr_campo e esse ponteiro será apontado aos jogadores inseridos no campo, eis o código definido...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 10
#define MAX_PONTOS 10

typedef struct JOGADOR JOGADOR;
typedef struct CAMPO CAMPO;

struct JOGADOR {
    int num_jogador;
    int pontos;
};

struct CAMPO {
    struct JOGADOR jogadores[MAX];
};

/*novo jogador*/
struct JOGADOR novo_jogador;
/*apontador para  novo jogador*/
struct JOGADOR *ptr_jogador;
/*Array campo jogo e campo prolonagamento*/
struct CAMPO campo[2];
/*apontador para campo jogo e campo prolonagamento */
struct CAMPO *ptr_campo;

/*Prototipos das funções*/
void criar_jogador_no_campo0(void);
void definir_vencedor_ou_empate_jogo(void);
void adicionar_jogadores_empatados_campo1(int, int);
void mostrar_jogadores_no_prolongamento(void);
...
}

nesta função cria o jogador e insere no campo de jogo, ou seja o campo[0]
void criar_jogador_no_campo0(void) {

    int i, j;
    //aponta para campo de jogo
    ptr_campo = &campo[0];

    for (i = 0, j = 0; i < MAX; i++) {
        campo[0] = *(ptr_campo);
        novo_jogador.num_jogador++;
        novo_jogador.pontos = 1 + rand() % MAX_PONTOS;
        ptr_jogador = &novo_jogador;
        campo[0].jogadores[i] = *ptr_jogador;
        *(ptr_campo) = campo[0];
        printf(">> Criar jogador %d com pontos %d no campo[0]...\n",
                ptr_campo->jogadores[i].num_jogador,
                ptr_campo->jogadores[i].pontos);
        j++;
    }

    if (j == MAX) {
        definir_vencedor_ou_empate_jogo();
    }
}

nesta função definir jogador vencedor com maior numero de pontos ou em caso de empate irão ao campo de prologamento, ou seja o campo[1]
void definir_vencedor_ou_empate_jogo(void) {

    int j, k, m, t;
    int contador = 0;
    int max = 0;

    puts("\n Determinar o jogador vencedor ou em situação de empate\n");
    //para todos os jogadores
    for (j = 0; j < MAX; j++) {
        //se o jogador listado tiver mais pontos marcados do que max
        if (ptr_campo->jogadores[j].pontos > max) {
            //max = pontos do jogador
            max = ptr_campo->jogadores[j].pontos;
            //contador será igual a um
            contador = 1;
            //se tiver os mesmo pontos que max
        } else if (ptr_campo->jogadores[j].pontos == max) {
            //incrementa o contador
            contador++;
        }
    }//se contador for igual a um
    if (contador == 1) {
        //para todos os jogadores
        for (k = 0; k < MAX; k++) {
            //se o jogador listado tiver mais do que max pontos
            if (ptr_campo->jogadores[k].pontos == max) {
                //o jogador iterado é o vencedor
                printf(">> Jogador %d é o VENCEDOR com %d pontos(s)\n",
                        ptr_campo->jogadores[k].num_jogador,
                        ptr_campo->jogadores[k].pontos);
            }
        }//caso contrário (contador diferente de um)
    } else {
        //iterar todos os jogadores
        for (m = 0; m < MAX; m++) {
            //se os pontos do jogador listado for igual a max
            if (ptr_campo->jogadores[m].pontos == max) {
                //o jogador iterado faz parte do prolongamento
                printf(">> Jogador %d com %d pontos(s) e vai para campo[1]\n",
                        ptr_campo->jogadores[m].num_jogador,
                        ptr_campo->jogadores[m].pontos);
            }
        }
        puts("\n\t\t--- Lista de Jogadores para campo[1] ---");
        //iterar todos os jogadores
        for (t = 0; t < MAX; t++) {
            //se os pontos do jogador listado for igual a max
            if (ptr_campo->jogadores[t].pontos == max) {
                //o jogador iterado faz parte
               //da lista de jogadores para prolongamento
                 adicionar_jogadores_empatados_campo1
                       (ptr_campo->jogadores[t].num_jogador, contador);
            }
        }
    }
}

a minha duvida começa nesta função em adicionar apenas os jogadores empatadas no campo[0] para campo[1], afim de obter o vencedor, tipo depois de empatar irão ao prolongamento, só que não sei se será necessario,adiciona-los ao novo array campo ou não sei bem o que perguntar....
void adicionar_jogadores_empatados_campo1(int num_jogador, int quant_jogador) {

    int j = 0;
    //aponta para campo de prolongamento
    //*(ptr_campo + 1) = &campo[1]; //-> dá erro

    for (int i = 0; i < MAX; i++) {
        if (num_jogador == ptr_campo->jogadores[i].num_jogador) {
            campo[1] = *(ptr_campo + i);
            campo[1].jogadores[i] = ptr_campo->jogadores[i];
            *(ptr_campo + i) = campo[1];
            printf("\t\t\t Jogador %d com %d pontos(s) adicionado no campo[1]\n",
                    (ptr_campo + i)->jogadores[i].num_jogador,
                    (ptr_campo + i)->jogadores[i].pontos);
            j++;
        }
    }

    if (j == quant_jogador) {
        //mostra os jogadores no prolongamento
        mostrar_jogadores_no_prolongamento();
    }
}

nesta função irá mostrar os jogadores adicionada no campo[1]
void mostrar_jogadores_no_prolongamento(void) {
    printf("\n\n--- Ponteiro para Campo 1 ---");
    for (int i = 0; i < MAX; i++) {
        //mostra os valores do novo ponteiro
        printf("\nAponta para ->Jogador %d com pontos %d no campo[1]",
                (ptr_campo + i)->jogadores[i].num_jogador,
                (ptr_campo + i)->jogadores[i].pontos);
    }
}

função main
int main(void) {

    criar_jogador_no_campo0();

    return 0;
}

cada vez que testo o programa, mostra somente esses dados em baixo,
nunca dá empate apesar de testar varias vezes

Esta dúvida é similar a dúvida que foi resolvida ontem ver link
só que post de ontem foi usado um array de inteiros e nessa duvida é usado um struct array para armazenar jogadores em diferentes situações
Veja funcionando no ideone.
Comment: @bigown, a dúvida que tinha perguntado sobre se poderia usar `struct array` para guardar elementos dentro de uma outra `struct array` e confirmaste que não se deve usar isto mas por acaso, resolvi desenvolver este exemplo para servir de base para minha duvida
Comment: Essa pergunta ficou um pouco comprida, você não acha? :)
Comment: @hugomg é verdade mas não foi minha intenção, dá próxima vez irei colocar resumidamente
Comment: não se preocupe. É só que uma ótima técnica para resolver problemas é tentar criar o menor exemplo possível que demonstre o comportamento indesejado.
Answer: Um primeiro problema com o seu código é que que você não está alimentando a semente do gerador de números pseudoaleatorios corretamente, dessa forma o resultado de rand será previsível.
Para mudar o valor da semente, use a função srand. Uma boa semente é a hora atual:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {

    srand((unsigned int)time(NULL));

    criar_jogador_no_campo0();

    return 0;
}

Adicionalmente, há confusão sobre ponteiros nas funções adicionar_jogadores_empatados_campo1 e mostrar_jogadores_no_prolongamento.
Um ponteiro para o campo do prolongamento pode ser obtido da seguinte forma:
struct CAMPO *ptr_campo_2 = ptr_campo + 1;

Usando esse ponteiro você pode reescrever sua função da seguinte maneira:
void adicionar_jogadores_empatados_campo1(int num_jogador, int quant_jogador) {

    int j = 0;

    for (int i = 0; i < MAX; i++) {
        if (num_jogador == ptr_campo->jogadores[i].num_jogador) {
            ptr_campo_2->jogadores[i] = ptr_campo->jogadores[i];
            printf("\t\t\t Jogador %d com %d pontos(s) adicionado no campo[1]\n",
                    ptr_campo_2->jogadores[i].num_jogador,
                    ptr_campo_2->jogadores[i].pontos);
            j++;
        }
    }
    // O maior valor possível de j eh quant_jogador - 1
    if (j + 1 == quant_jogador) {
        //mostra os jogadores no prolongamento
        mostrar_jogadores_no_prolongamento();
    }
}

É claro que você também pode obter o ponteiro para o campo de prolongamento a partir do endereço do campo do jogo com a expressão (ptr_campo + 1), dessa forma, você poderia reescrever a sua função mostrar_jogadores_no_prolongamento assim:
void mostrar_jogadores_no_prolongamento(void) {
    printf("\n\n--- Ponteiro para Campo 1 ---");
    for (int i = 0; i < MAX; i++) {
        //mostra os valores do novo ponteiro
        printf("\nAponta para ->Jogador %d com pontos %d no campo[1]",
                (ptr_campo + 1)->jogadores[i].num_jogador,
                (ptr_campo + 1)->jogadores[i].pontos);
    }
}

Mas se você já tem um ponteiro para o campo de prolongamento não há motivo para repetir a aritmética de ponteiros. Apenas use o ponteiro original:
printf("\nAponta para ->Jogador %d com pontos %d no campo[1]",
         ptr_campo_2->jogadores[i].num_jogador,
         ptr_campo_2->jogadores[i].pontos);

Comment: obrigado pela orientação, por acaso, eu estava a fazer confusão nos ponteiros mas resolveu a minha duvida


A function to find and substitute specific text?

Question: Is there a function which I can use that which will allow me to replace a specific texts.
For example:
char *test = "^Hello world^"; would be replaced with char *test = "<s>Hello world</s>";
Another example: char *test2 = "This is ~my house~ bud" would be replaced with char *test2 = "This is my house bud"
Comment: The problem with strings in C is that memory management is *not* automatic. So replacing `^` with `` requires allocation of a bigger buffer, and writing the new string into the buffer. Which is to say that the function you seek is a function that you need to write. Standard functions like `malloc`, `strcpy`, `strcat`, `memcpy`, `sprintf`, and `snprintf` may be useful, but only to help you write your function.
Comment: Another problem is that strings like `char *test = "^Hello world^";` should not be modified.  Any attempts to do so lead to undefined behaviour, and usually lead to a crash.  This is different from `char test[] = "^Hello world^";` where the value of the string is stored in the array and the array is modifiable.  However, to extend a string, you're going to have to indulge in memory management; you need more space for the larger string, so you have to allocate that space somehow.  And, because memory management is involved, there is no standard C library function that handles the replace part.
Comment: There is no library function that does that for you, but it is something you can do with a few lines of code. C provides the tools to do whatever can be done on a computer -- it is up to you to put the pieces together to finish the puzzle. In the case of substitution, the easiest case is knowing how long the *final* string needs to be (+1 for the *nul-terminating* character). That way you can simply allocate *final length + 1* bytes (using `malloc`) and then fill the newly allocated buffer with the reformed text. There are many many examples on this site of just that. Let us know.
Comment: See: https://github.com/antirez/sds suggested by https://stackoverflow.com/questions/4688041/good-c-string-library
Answer: Before you can begin to replace substrings within a string, you have to understand what you are dealing with. In your example you want to know whether you can replace characters within a string, and you give as an example:
char *test = "^Hello world^";

By being declared and initialized as shown above test, is a string-literal created in read-only memory (on virtually all systems) and any attempt to modify characters stored in read-only memory invokes Undefined Behavior (and most likely a Segmentation Fault)
As noted in the comments, test could be declared and initialized as a character array, e.g. char test[] = "^Hello world^"; and insure that test is modifiable, but that does not address the problem where your replacement strings are longer than the substrings being replaced.
To handle the additional characters, you have two options (1) you can declare test[] to be sufficiently large to accommodate the substitutions, or (2) you can dynamically allocate storage for the replacement string, and realloc additional memory if you reach your original allocation limit.
For instance if you limit the code associated with test to a single function, you could declare test with a sufficient number of characters to handle the replacements, e.g.
#define MAXC 1024  /* define a constant for the maximum number of characters */
...
    test[MAXC] = "^Hello world^";

You would then simply need to keep track of the original string length plus the number of character added with each replacement and insure that the total never exceeds MAXC-1 (reserving space for the nul-terminating character).
However, if you decided to move the replacement code to a separate function -- you now have the problem that you cannot return a pointer to a locally declared array (because the locally declared array is declared within the function stack space -- which is destroyed (released for reuse) when the function returns) A locally declared array has automatic storage duration. See: C11 Standard - 6.2.4 Storage durations of objects
To avoid the problem of a locally declared array not surviving the function return, you can simply dynamically allocate storage for your new string which results in the new string having allocated storage duration which is good for the life of the program, or until the memory is freed by calling free(). This allows you to declare and allocate storage for a new string within a function, make your substring replacements, and then return a pointer to the new string for use back in the calling function.
For you circumstance, a simple declaration of a new string within a function and allocating twice the amount of storage as the original string is a reasonable approach to take. (you still must keep track of the number of bytes of memory you use, but you then have the ability to realloc additional memory if you should reach your original allocation limit) This process can continue and accommodate any number of strings and substitutions, up to the available memory on your system.
While there are a number of ways to approach the substitutions, simply searching the original string for each substring, and then copying the text up to the substring to the new string, then copying the replacement substring allows you to "inch-worm" from the beginning to the end of your original string making replacement substitutions as you go. The only challenge you have is keeping track of the number of characters used (so you can reallocate if necessary) and advancing your read position within the original from the beginning to the end as you go.
Your example somewhat complicates the process by needing to alternate between one of two replacement strings as you work your way down the string. This can be handled with a simple toggle flag. (a variable you alternate 0,1,0,1,...) which will then determine the proper replacement string to use where needed.
The ternary operator (e.g. test ? if_true : if_false; can help reduce the number of if (test) { if_true; } else { if_false; } blocks you have sprinkled through your code -- it's up to you. If the if (test) {} format is more readable to you -- use that, otherwise, use the ternary.
The following example takes the (1) original string, (2) the find substring, (3) the 1st replacement substring, and (4) the 2nd replacement substring as arguments to the program. It allocates for the new string within the strreplace() function, makes the substitutions requested and returns a pointer to the new string to the calling function. The code is heavily commented to help you follow along, e.g.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* replace all instances of 'find' in 's' with 'r1' and `r2`, alternating.
 * allocate memory, as required, to hold string with replacements,
 * returns allocated string with replacements on success, NULL otherwise.
 */
char *strreplace (const char *s, const char *find,
                    const char *r1, const char *r2)
{
    const char *p = s,              /* pointer to s */
        *sp = s;                    /* 2nd substring pointer */
    char *newstr = NULL,            /* newsting pointer to allocate/return */
        *np = newstr;               /* pointer to newstring to fill */
    size_t newlen = 0,              /* length for newstr */
        used = 0,                   /* amount of allocated space used */
        slen = strlen (s),          /* length of s */
        findlen = strlen (find),    /* length of find string */
        r1len = strlen (r1),        /* length of replace string 1 */
        r2len = strlen (r2);        /* length of replace string 2 */
    int toggle = 0;                 /* simple 0/1 toggle flag for r1/r2 */

    if (s == NULL || *s == 0) { /* validate s not NULL or empty */
        fputs ("strreplace() error: input NULL or empty\n", stderr);
        return NULL;
    }

    newlen = slen * 2;              /* double length of s for newstr */
    newstr = calloc (1, newlen);    /* allocate twice length of s */

    if (newstr == NULL) {           /* validate ALL memory allocations */
        perror ("calloc-newstr");
        return NULL;
    }
    np = newstr;                    /* initialize newpointer to newstr */

    /* locate each substring using strstr */
    while ((sp = strstr (p, find))) {   /* find beginning of each substring */
        size_t len = sp - p;            /* length to substring */

        /* check if realloc needed? */
        if (used + len + (toggle ? r2len : r1len) + 1 > newlen) {
            void *tmp = realloc (newstr, newlen * 2);   /* realloc to temp */
            if (!tmp) {                     /* validate realloc succeeded */
                perror ("realloc-newstr");
                return NULL;
            }
            newstr = tmp;       /* assign realloc'ed block to newstr */
            newlen *= 2;        /* update newlen */
        }
        strncpy (np, p, len);   /* copy from pointer to substring */
        np += len;              /* advance newstr pointer by len */
        *np = 0;                /* nul-terminate (already done by calloc) */
        strcpy (np, toggle ? r2 : r1);  /* copy r2/r1 string to end */
        np += toggle ? r2len : r1len;   /* advance newstr pointer by r12len */
        *np = 0;                /* <ditto> */
        p += len + findlen;     /* advance p by len + findlen */
        used += len + (toggle ? r2len : r1len); /* update used characters */
        toggle = toggle ? 0 : 1;    /* toggle 0,1,0,1,... */
    }

    /* handle segment of s after last find substring */
    slen = strlen (p);          /* get remaining length */
    if (slen) {                 /* if not at end */
        if (used + slen + 1 > newlen) { /* check if realloc needed? */
            void *tmp = realloc (newstr, used + slen + 1);  /* realloc */
            if (!tmp) {         /* validate */
                perror ("realloc-newstr");
                return NULL;
            }
            newstr = tmp;       /* assign */
            newlen += slen + 1; /* update (not required here, know why? */
        }
        strcpy (np, p);         /* add final segment to string */
        *(np + slen) = 0;       /* nul-terminate */
    }

    return newstr;  /* return newstr */
}

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

    const char  *s = NULL,
                *find = NULL,
                *r1 = NULL,
                *r2 = NULL;
    char *newstr = NULL;

    if (argc < 5) { /* validate required no. or arguments given */
        fprintf (stderr, "error: insufficient arguments,\n"
                        "usage: %s <find> <rep1> <rep2>\n", argv[0]);
        return 1;
    }
    s = argv[1];        /* assign arguments to poitners */
    find = argv[2];
    r1 = argv[3];
    r2 = argv[4];

    newstr = strreplace (s, find, r1, r2);  /* replace substrings in s */

    if (newstr) {   /* validate return */
        printf ("oldstr: %s\nnewstr: %s\n", s, newstr);
        free (newstr);  /* don't forget to free what you allocate */
    }
    else {  /* handle error */
        fputs ("strreplace() returned NULL\n", stderr);
        return 1;
    }

    return 0;
}

(above, the strreplace function uses pointers to walk ("inch-worm") down the original string making replacement, but you can use string indexes and index variables if that makes more sense to you)
(also note the use of calloc for the original allocation. calloc allocates and sets the new memory to all zero which can aid in insuring you don't forget to nul-terminate your string, but note any memory added by realloc will not be zeroed -- unless you manually zero it with memset or the like. The code above manually terminates the new string after each copy, so you can use either malloc or calloc for the allocation)
Example Use/Output
First example:
$ ./bin/str_substr_replace2 "^Hello world^" "^" "<s>" "</s>"
oldstr: ^Hello world^
newstr: <s>Hello world</s>

Second example:
$ ./bin/str_substr_replace2 "This is ~my house~ bud" "~" "" ""
oldstr: This is ~my house~ bud
newstr: This is my house bud

Memory Use/Error Check
In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.
It is imperative that you use a memory error checking program to insure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.
For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.
$ valgrind ./bin/str_substr_replace2 "This is ~my house~ bud" "~" "" ""
==8962== Memcheck, a memory error detector
==8962== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==8962== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==8962== Command: ./bin/str_substr_replace2 This\ is\ ~my\ house~\ bud ~ \ \
==8962==
oldstr: This is ~my house~ bud
newstr: This is my house bud
==8962==
==8962== HEAP SUMMARY:
==8962==     in use at exit: 0 bytes in 0 blocks
==8962==   total heap usage: 1 allocs, 1 frees, 44 bytes allocated
==8962==
==8962== All heap blocks were freed -- no leaks are possible
==8962==
==8962== For counts of detected and suppressed errors, rerun with: -v
==8962== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.
Look things over and let me know if you have any further questions.


Is there a way to count all elements of an index in ElasticSearch or Tire?

Question: It would be nice to have a count of elements without having to do a search like
Obj.search("id:*").count

Is this possible?
Answer: First, you should use the match_all query: MyModel.search( { query { all } }).results.total. (In Lucene, avoid wildcard queries at all costs.)
Presently, Tire does not expose the "count" API. That will change.
Comment: Isn't there the count query available in tire?
Comment: If I use `MyModel.search(query: { match_all: {} }).results.total` I get a max count of 10000, the default value for the setting "index.max_result_window".
Answer: In ElasticSearch you can count all elements using the count API
curl -XGET http://localhost:9200/index/_count

See the Count API docs on their site.
Answer: Just got a hint from Karmi. The count API is available now.
You can do the following:
s = Tire.search 'articles-test', :search_type => 'count' do
  query { term :tags, 'ruby' }
end

Only then s.results.total is defined.
See here: https://github.com/karmi/tire/blob/master/test/integration/count_test.rb
Answer: In case you are using gem 'elasticsearch-model', here is a nice one liner:
Elasticsearch::Model.client.count(index: 'your_index_name_here')['count']

Answer: From console:
Model.search("*:*").results.total

maybe help someone ;)
Answer: You can do this in the elasticsearch-model gem as well:
Article.search("cats", search_type: 'count').results.total
# => 2026

And you won't cause a fetch...
Article.search("cats", search_type: 'count').map {|r| r.title}
# => []

Answer: If you want to get number of documents inside index, you could also just check index stats, like this:
curl -XGET localhost:9200/_stats

In result you will get number of docs / deleted docs (docs not yet merged out).
Answer: When I use MyModel.search(query: { match_all: {} }).results.total, the maximum count I receive is 10000, which is the default value for the "index.max_result_window" setting. Therefore, I don't believe this is the correct answer.
Instead, my solution is to utilize the count API, which in Ruby would look like this:
Elasticsearch::Model.client.count(index: MyModel.index_name)['count']


a cube is a source for another cube

Question: i have a similar case like the following example and i need somebody to suggest a good practice in such case.
say that you have two cubes, the first one is a timesheet cube, where you can find how many hours an employee worked on a project in a specific date. an employee can work on many projects in a day and many employees can work on one project. some employees do not work on projects, such as the employees under the supporting departments (like accounting, ISD, HR ...etc) they write there hours on let's say "general".
The second cube is project_funder, that shows how much money a funder put in a project. a project can be funded by many funders, and a funder can provide many projects.
how can i bring the relation between the project and the funder from the second cube and use it in the first cube (timesheet cube), to find something like: employee emp1 worked 8 hours on project proj1 which was funded by funder1 and funder2 ? ... i'm using SSAS 2008
Answer: It's not known for having good perfomance on large datasets, but have you read up on LOOKUPCUBE
http://msdn.microsoft.com/en-us/library/ms144720.aspx
Returns the value of a Multidimensional Expressions (MDX) expression
evaluated over another specified cube in the same database.

Here's a nice example:
WITH MEMBER [Measures].[Lookup Internet Order Count] AS
LOOKUPCUBE("Mined Customers", "([Measures].[Internet Order Count],
[Customer].[Customer Geography].[Country].&[" +
[Customer].[Customer Geography].CurrentMember.Name + "])")

SELECT [Customer].[Customer Geography].[Country] ON COLUMNS,
{
 [Measures].[Internet Sales Amount],
 [Measures].[Lookup Internet Order Count]
} ON ROWS
FROM [ADVENTURE WORKS]

Taken from: http://www.bidn.com/blogs/DustinRyan/ssis/814/lookupcube-function-mdx-query-performance-test

a cube is a source for another cube


Logic Pro overload bottleneck

Question: A rather technical question but I was wondering if someone has an answer to this:
I'm using a Mid 2010 Mac Mini (2,66Ghz Core 2 Duo, extended 8BG of RAM) running the latest Logic Pro X on OSX 10.11 for recording which usually is working very nicely, meaning
16-track simultaneuous audio recording or up to 10 tracks of software instruments usually works pretty smoothly.
But I have recently started using more tools using NI's Kontakt and Reaktor Plugins which seem to be a little heavy on the system.
As soon as I hit 3 or 4 tracks with the mentioned plugins it will not play back even a second of the mix before overloading and telling me it could not calculate everything in time.
I have even tried out setting the I/O Buffer from 128 up to a staggering 1024   but it had no effect on the result.
Now my question is: Does someone know what the bottleneck is here? CPU or RAM?
If it's RAM I could bump it up to 16GB if the system supports it, if it's the processor I'll have to think about upgrading.
Thanks
Comment: I'm with @ToddWilcox on this, but with one additional caveat. The Mac Mini was quite a low end machine even when new. A fully loaded Mac Pro from the same year wouldn't yet be feeling quite so arthritic, assuming it had been taking its meds [new SSD, GPU, big RAM, dual 6-core etc]
Comment: You have a pretty old processor so that's a likely issue, but it could even be the hard disk where the samples are stored or your interface. What interface are you using?
Comment: As an IT professional, I'm often talking to people about computer performance. I've started talking about the age of a computer in a similar way to the age of a dog, in the sense of "dog years" (I.e., one year of life for a dog is about equivalent to seven years of life for a human). But computer years are more like one year for a computer is as aging as twenty years would be for a human. At three years (like a sixty year old human) a computer is nearing retirement age. At four years (like 80), it's showing its age but not dead yet. At five (100) it's positively venerable. Seven is extreme.
Comment: You seem to be correct :-( Recently this function must have been added : Open the dropdown on the Time/Sample Status and choose "Custom" and there is now a CPU / Disk status bar. The CPU seems to be the problem here. Too bad, that machine was top shelf, too.
Comment: But I have been wondering about the disk-thing. It's a 500GB HDD RAID 1 which I would assume relatively fast. @ToddWilcox I was under the impression that the whole VST would be loaded into RAM,  would put zero load on the disk on playback. So are the samples loaded from disk each and every time?
Comment: @Tetsujin I see where you are coming from but that seems a little harsh. I have been sucessfully working with that machine for 7 years recording and producing and there has not been a single day it as given me a headache. It's its first time showing signs of old age so credit where it's due. It was the top of the line model plus has gotten a RAM upgrade a couple years back. Though I'm not sure where to go from here. The newer models of the mini all still have HDDs, so I'd have to modify it but the Pro series is overpriced in my opinion.
Comment: @Halest I've been watching the Mac market for a few years now to try to figure what my next one will be and I would love to have a Mini that will perform (e.g., have at least quad core i7) but they just don't make em powerful enough. Looks to me like the MacBook Pro line is the best compromise on portability, power, and price. Sometimes I think about Windows but I love Logic and Mainstage too much. If you've decided that the processor is your problem because of looking at utilization, then I think you should put that as the answer and accept your own answer.
Answer: Open the dropdown on the Time/Sample Status and choose "Custom" and there is now a CPU / Disk status bar.
It seems to be a mix between Disk and CPU.

Logic Pro overload bottleneck


How do I close a card when onclick on a button in react?

Question: I have a material-ui card in which it contains image, input field, check-box and a submit button. In which card is displaying onclick on some other option which is not mentioned in the below code. I want to close a card when I click on submit. How can I achieve this?
     <Card
          className="details-card"
          style={{ paddingTop: "0px" }}
          color="primary"
        >
          <CardHeader
            style={{
              paddingBottom: 0,
              paddingTop: 0
            }}
            title="Image"
          />

          <CardContent className="details-card-body">
            <TextField label="Name" fullWidth />
            <Grid container>
              <Grid item xs={4}>
                <Typography>
                  New User
                  <Checkbox
                    checked={this.state.addNew}
                    name="addNew"
                    onChange={this.handleCheckBox("addNew")}
                    value="new user"
                    inputProps={{ "aria-label": "Checkbox B" }}
                  />
                </Typography>
              </Grid>
            </Grid>
            <Button variant="contained" color="primary">
              Click to Tag
            </Button>
          </CardContent>
        </Card>

Here below is my code on CodeSandbox
https://codesandbox.io/embed/lppzx48r0m
Answer: There are multiple ways to achieve what you want to do
you'll need a flag to conditionally hide or show the card.
For example lets take flag variable in state, and change state variable flag based on submit button and on the basis of this.state.flag you can do
{this.state.flag ?
    (<Card
        className="details-card"
        style={{ paddingTop: "0px" }}
        color="primary"
    >
        //Card content
    </Card>)
    :
    null
}

You can also provide conditional css based on this.state.flag
<Card
    className="details-card"
    style={{ paddingTop: "0px", display: this.state.flag ? block : 'none'}}
    color="primary"
>
    //Card content
</Card>

P.S.: The second approach is not recommended because we are rendering element even if it is not needed.


How to notate harmonic sequences in roman numerals analysis in main theme from Beethoven Symphony 7 2nd movement Alegretto?

Question: Q1: How would you notate the first four bars of the second system?
I'm trying to understand the introductory theme from the Alegretto in Beethoven's 7th Symphony. Here's what I have so far, which doesn't seem right in the first four bars of the 2nd system.

Q2: Is there a standard way to annotate harmonic sequences like ↓4↑M3(6)?
There's a sequence at the beginning of the second system. To me this sounds like a portion of a "down a fourth up a minor third" descending sequence pattern, using inversions to make a chromatically descending bassline, except that the starting chord is e minor instead of E major as notated here (please forgive my musescore skills, I wouldn't normally place the accidentals this way).
Answer: Answer for Q1:
Beat 2.5 of the 3rd bar of System 2 is a vii°6 chord, a dominant-function chord. It resolves to I(!) and is therefore not passing.
Also note that the first 2 bars and the next 2 bars of System 2 both try to pull off a localized I-i chord progression (the first time between the 2nd and 3rd bars, the second time within the 4th bar). Outright saying that the 2nd and 3rd bars of System 2 are just Em: V into A: ii - vii°6 isn't telling the whole story.


Zerar Page a cada click

Question:
Tenho na figura acima este UserForm pequeno com três pages.
Na primeira page, ao clicar no botão Habilitar, é inserido a próxima data com o TextBox Data como False, para o usuário não alterar.
O botão Habilitar habilita também o TextBox Previsto e os botões Inserir e Limpar.
Ao clicar na segunda page, tenho outra configuração, claro, e posso inserir dados atualizados.
Ao clicar novamente na primeira page, caso o usuário não tenha tomada nenhuma ação ao clicar no botão Habilitar, gostaria que a page volte ao seu estado original.
Estou utilizando este código, e gostaria de saber sé é realmente desta forma.
Vou utilizar para as três pages.
Private Sub MultiPage1_Click(ByVal Index As Long)
    With Me.MultiPage1
        If .Value = 0 Then Call Me.RestauraControles0
        If .Value = 1 Then Call Me.RestauraControles1
    End With
End Sub

Me.RestauraControles0 limpa tudo e deixa habilitado somente o botão Habilitar.
Comment: `RestauraControles0` isto é uma função dentro do formulário ou de um módulo?
Comment: RestauraControles0 está dentro do formulário.
Simplesmente deixa habilitado somente o botão Habilitar.
Comment: RestauraControles0 está dentro do formulário. Simplesmente deixa habilitado somente o botão Habilitar. Limpa todos os controles textbox da primeira page. E é isso que eu estou querendo: selecionou a primeira page, limpa tudo com o RestauraCOntroles0.
Comment: RestauraControles1 faz o mesmo ao clicar na segunda page. Ou deveria.
Comment: `Sub RestauraControles0()
    Me.tbData0.Enabled = True
    Me.tbData0.Text = ""
    Me.tbData0.Enabled = False
    Me.tbPrevisto0.Enabled = True
    Me.tbPrevisto0.Text = ""
    Me.tbPrevisto0.Enabled = False
    Me.btInserir0.Enabled = False
    Me.btLimpar0.Enabled = False
    Me.btHabilitar0.SetFocus
End Sub`
Answer: O código funciona da maneira que você está realizando, mas se quiser algo mais genérico crie um Módulo de Classe ou faça da seguinte maneira:
Como não sei como está toda estrutura do seu formulário e o que realmente deseja da página 2, este é um exemplo para aprender a realizar loops nos controles do formulário e generalizar algumas tarefas que podem funcionar em todas as páginas.
Código
Option Explicit
Private Sub MultiPage1_Change()
    Dim controle As Control
    Dim pagina_atual As Long
    Dim tudo_vazio As Boolean
    tudo_vazio = True
    With Me.MultiPage1
        pagina_atual = .Value
        For Each controle In .Pages(pagina_atual).Controls
            If TypeName(controle) = "TextBox" Then
                If Trim(controle.Value) <> "" Then
                    'Debug.Print controle.Name
                    tudo_vazio = False
                    Exit For
                End If
            End If
        Next controle
        If tudo_vazio Then
            For Each controle In .Pages(pagina_atual).Controls
                If TypeName(controle) = "CommandButton" Then
                    'Debug.Print controle.Name
                    If Not Trim(controle.Name) Like "*habilitar*" Then
                        controle.Enabled = False
                    End If
                End If
            Next controle
        End If
    End With
End Sub

Explicação
Em que realiza o loop nos controles de formulário da página atual e verifica se não há Caixas de Textos vazias.
Página Atual
O código pagina_atual = Me.MultiPage1.Value retorna o valor da página da multipágina selecionada.
Loop nos controles
For Each controle In Me.MultiPage1.Pages(pagina_atual).Controls
Next controle

Realiza o loop em todos os controles da página da multipágina selecionada.
Verificar se é caixa de texto
If TypeName(controle) = "TextBox" Then
End If

Verifica se o controle é uma caixa de texto.
Verificar se algo foi escrito na Caixa de Texto
If Trim(controle.Value) <> "" Then
End If

Verifica se o valor da caixa de texto é diferente de vazio.
Caso não seja vazio
tudo_vazio = False
Exit For

Caso o controle não esteja vazio, ou seja, com algum valor. Altera a flag tudo_vazio para False e sai do loop.
Verifica a flag tudo_vazio
If tudo_vazio Then
End If

Caso tudo_vazio seja verdadeiro, continua com o código.
Loop controles e verificação botão
Da mesma forma que anteriormente, o loop nos controles é relizado e é verificado se é Botão de Comando.
Verifica Nome do Botão de Comando
Como os Text_Box estão todos vazios, quer dizer que não houve alteração. Então todos os botões que não contenham a palavra habilitar no nome serão desabilitadas com controle.Enabled = False
If Not Trim(controle.Name) Like "*habilitar*" Then
End If

Comment: Valeu e muito obrigado!
Comment: @PauloSemblano Você pode também utilizar como função genérica para "zerar" cada página desejada... Ao inves de utilizar o evento `MultiPage1_Change`
Comment: Em função me embaralho um pouco. Rsrsrsrsrsrs

Zerar Page a cada click


autolink body content to node

Question: I want to do this: If I enter a body in content type, on save the content type body searched and  automatically link to exists node title.
As example :
body:   The drupal is one of best CMS systems,
If I have a node with title "drupal" I want  the drupal link to it automatically on save,
is there any module to do this? If not appreciate any idea help me to implement it.
I found Alinks module, it similar to what I want but It not link to existing nodes, it just link to some user defined word and links.
The main problem is searching for existing node title not linking to them,
we have body with many word,I want if a word equal node title that exist , it link to it
Comment: do you found a way?
Answer: You may consider the FreeLinking module.
The Freelinking module adds a text filter for using Wiki-style markup for creating links automatically, by searching the node body for markup.  It supports a number of methods for creating the link, including Nodetitle (which sounds like the one you're looking for). You may even add methods by adding your own link plugin.
However, you need to indicate the text you want to be considered as a candidate for automatic linking by markup: i.e. by surrounding it with double square brackets.  This is how your example will look like:
<code>The [[drupal]] is one of best CMS systems
</code>
It even lets you create placeholder links to pages that has not been created yet. Both internal and external links are supported by the module.
There tutorial is about using the Freelinking module, with a little help from the companion WikiTools module, here.
If the way Freelinking does this is not good enough for you, here are a couple of alternative solutions:
Alternative solution #1: You can write your own custom text filter for this.  I suspect that to create something that works during node saves without freezing or killing your site will be very hard to do.
Alternative solution #2: If you can accept a solution that delays the creation of links, you can place new and altered links in a queue, and then use a cron job  to parse them for links.  This allows you to space out the parsing of node bodies over time and will avoid the performance problems a real-time text filter would create.  For the record: There exists no module that does the parsing of node bodies and add links like this.  You'll need to write it yourself.
Comment: Hannemeyr, tnx for your attention, you first part of answer is good,but my problem is searching for exist tile in body, you thing I have 20000 node and body with 3000 world, what is your suggestion to search ?
I want something like [rule_autotag](https://drupal.org/project/rules_autotag) but search in titles,
Comment: The main problem is searching for existing node title not linking to them,
we have body with many world,I want if a word equal node title that exist , it link to it
Comment: Searching for *all* the 3000 words in a node body the a dictionary that consistst of 20000 node titles upon saving a node is very resource demanding and it probaly will kill your site. If this is the functionality you want, I can't think of a *simple* way of doing it. I'll offered a couple of alternate suggestions tho'.
Comment: tnx for your suggestion and tnx for your great module , but I mentioned in my question,I want they linked automatically without I do, because I dont know all title of my nodes.
Comment: I have another way,I will use combination of your module and rule_autotag module,in node_save, I add title to my custom vocab and exract them with rule_autotag api ,then replace founded tags in body with your module features,
Comment: your module is great, I have question bout it, it want only this feature if [drupal] link to content that title is drupal, How can I achieve it?

autolink body content to node


como obter o posicionamento de imagem usando draggable

Question: como posso obter através de um input a escala (left e top) de posicionamento da imagem que esta sendo movimentada com o draggable.
O objetivo dessa dúvida é para que possa salvar no Banco de Dados usando PHP e Mysql, o posicionamento desejável da imagem.
Abaixo anexo parte do código usado.
Se alguém puder ajuda, ficarei muito grato.
Desde já meus agradecimentos pela a atenção dos amigos.
Código usado:

<link rel="shortcut icon" href="../images/favicon.ico" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">

<link rel="stylesheet" href="/resources/demos/style.css">

Answer: Precisas de passar um objeto para esse método com a callback para correres o código que queres.
Aqui fica um exemplo da documentação do plugin:
$("#draggable").draggable({
      start: function() {
        // correr código aqui...
      },
      drag: function() {
        // correr código aqui...
      },
      stop: function() {
        // correr código aqui...
      }
});

Neste exemplos tens 3 momentos diferentes que podes oscultar e correr código quando esse evento acontece.
Para saberes a posição podes usar assim dentro dessas funções:
var offset = $(this).offset();
var xPos = offset.left;
var yPos = offset.top;

Exemplo: http://jsfiddle.net/2rf3mxfg/
Comment: Valeu Sergio funcionou, agora eu consigo visualizar as escalas de left e top da imagem ao move-la.
A sua dica foi de grande valia.
Mas abusando um pouco mais, tem como você me mostrar como criar um input para que eu possa pegar essas escalas e enviar para o banco de dados via form php.
Desde já meu obrigado.
Comment: @MuriloCabral precisas de `touch` também ou só `mouse`?


Trying to access modules page callback while authenticated

Question: I have a module below that will only show "hello world" when I am an administrator. I would also like "hello world" to display when I an authenticate user but right now all I am getting is you are not authorised. I have set  mymenuitem as the home page and I am using Drupal 7.
 function mymenuitem_menu() {
  $items = array();
  $items['mymenuitem'] = array(
    'title' => 'mymodule',
    'description' => 'my menu access issue',
    'page callback' => 'mymodule_homepage',
    'access arguments' => array('access mymodule homepage'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function mymodule_homepage(){
  drupal_set_title(t('menu system'));
  return "hello world";
}

How can I achieve this?
Comment: I suspect you're logged in as user 1, who by default has permission to view all the menu links of the site; hence you are able to see this page. The other users are not able to view it because you did not define the permission (the value provided in `'access arguments'`) mentioned. You do so by following the method shown by @Aiias.
Answer:
Make sure you define your new permission using Drupal 7's hook_permission().
Grant your new permission to authenticated user here: /admin/people/permissions/list

Try this:
function mymodule_permission() {
  return array(
    'access mymodule homepage' => array(
      'title' => t('Access My Module homepage'),
      'description' => t('View My Module homepage.'),
    )
  );
}

Comment: This is the right way to implement any custom permissions. However, OP mentioned that he needs to show this to _authenticated_ users not _anonymous_, so you might want to change the point #2 to accommodate it.
Comment: @develkar - Nice catch. I have changed my answer accordingly :).
Comment: That worked perfectly and it was one hook I was missing thanks
Comment: @purencool - No problem, happy to help :)
Comment: @purencool - If this answered your question, please mark your question as answered so others can refer back to this answer and StackExchange will not consider this as an open question.
Comment: It does but how do you check it as answered
Comment: @purencool - There's a checkbox just beneath the down-vote arrow. If you click that, it will mark your question as answered by this answer. Here is the official `how-to` page: http://drupal.stackexchange.com/help/someone-answers


jQuery JTable how to drag rows

Question: I would like to drag rows in a table build with jQuery jTable, on release update sort order  with ajax call.
Is that possible?
Can't find anything about draggable rows
Comment: http://stackoverflow.com/a/16863702/528370
Comment: actually i prefer table, i thought to use query ui drag able but doesn't seem to work, i guess is because record was ad to table via ajax
Answer: i found a solution bind the query ui on recordsLoaded, call each time record are loaded
<code>   $('#mytable').jtable({
        title: 'my title',
        paging: true,
        pageSize: 100,
        sorting: true,
        defaultSorting: 'order ASC',
        selecting: true,
        multiselect: true,
        selectingCheckboxes: true,
        columnSelectable: false,
        gotoPageArea: 'none',
        pageSizeChangeArea: false,
        actions: {
            listAction: '../ajax/myajax.php'
        },
        fields: {
            id: {
                key: true,
                create: false,
                edit: false,
                list: false
            },
            order: {
                title: 'order',
                create: false,
                edit: false,
                sorting: false
            }
        },
        recordsLoaded: function () {

            $(".jtable tbody").sortable({
                cursor: 'move',
                opacity: 0.9,
                axis: 'y',
                start: function (event, ui) {
                    if ($.browser.webkit) {
                        wscrolltop = $(window).scrollTop(); // bug fix
                    }
                },
                sort: function (event, ui) {
                    if ($.browser.webkit) {
                        ui.helper.css({ 'top': ui.position.top + wscrolltop + 'px' });  // bug fix
                    }
                },
                update: function(event, ui) {

                    // do jquery HERE on sort

                }

            }).disableSelection();

        }
    });
</code>

jQuery JTable how to drag rows


Proper syntax for optional header parameter for text/csv mimetype?

Question: According to RFC 4180:

...the presence or absence of the header line
should be indicated via the optional "header" parameter of this
MIME type...

So, does that mean the correct string is:
text/csv; header

Or perhaps:
text/csv; header=true

Or something else?
Answer:
The "header" parameter indicates the presence or absence of the header line.  Valid values are "present" or "absent".

So if you use that parameter, the full MIME type would be text/csv; header=present or text/csv; header=absent.


Check if a general point is inside a given cylinder

Question: For a particular purpose, I want to define a cylinder in 3D space and go through a list of given 3D points and tell if the point is inside or outside the cylinder volume.
I can define the cylinder by specifying 2 points along the axis, and the radius of the cylinder.
A (x1, y1, z1 )
B (x2, y2, z2 )
and radius = R

right now what I'm doing is that I find the vector AB, connecting A and B by
AB = A - B
then calculate the shortest distance from each point to the vector AB, if the distance is less than R, the point is inside.
The problem with this method is that it only works if either A or B is the origin.
for example, If I try to find the points inside the cylinder connecting
p1 ( 100,10,20)
p2 ( 100,-10,20)

we get the points inside the cylinder ( 0,20,0) [ which is actually the cylinder formed by ( 0,0,0) and (0,20,0) ]
certainly, I'm missing something, can anyone point it out?
N.B: For some complicated reason, I can't use an auxiliary coordinate system or shift the origin. What I'm looking for is some pure mathematical expression ( if it exists ), which can take the particulars of the cylinder and the required point and give if it is inside or outside.
similar to Empty2's answer on this question
Comment: Is the cylinder infinite ?
Comment: "it only works if either A or B is the origin": you must compute the distance to the line, not to the vector.
Comment: If your algorithm already works with, say, $A$ is the origin, why don't you "translate" $A$ (to the origin), $B$ (to $B-A$) and every point $X$ (to $X-A$), by the vector $-A$, and just apply your working algorithm.
Comment: The cylinder is not infinite, I wish to contain it between these points A and B. For some complicated reason, I can't use an auxiliary coordinate system or shift the origin. What I'm looking for is some pure mathematical expression ( if it exists ), which can take the particulars of the cylinder and the required point and give if it is inside or outside.

similar to Empty2's answer on this https://math.stackexchange.com/questions/1472049/check-if-a-point-is-inside-a-rectangular-shaped-area-3d
Answer: Solution
Consider the line coordinates with direction $\boldsymbol{e} = \boldsymbol{r}_B-\boldsymbol{r}_A$ and moment $\boldsymbol{m} = \boldsymbol{r}_A \times \boldsymbol{r}_B$. These two vectors represent the infinite line between ${A}$ and ${B}$.
A point ${P}$ with position $\boldsymbol{r}_{P}$ lies in the cylinder between $\boldsymbol{A}$ and $\boldsymbol{B}$ and radius $R$ if:

Distance of $P$ to line $AB$ is equal or less than $R$
$$d = \frac{\|\boldsymbol{m} + \boldsymbol{e}\times\boldsymbol{r}_{P}\|}{\|\boldsymbol{e}\|}\leq R$$
or the alternate formulation of the above
$$d = \frac{\| \boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\boldsymbol{r}_{A}\right) \|}{\|\boldsymbol{e}\|}\leq R$$
Closest point $Q$ on line to $P$ is
$$\boldsymbol{r}_{Q}=\boldsymbol{r}_{P}+\frac{\boldsymbol{e}\times\left(\boldsymbol{m}+\boldsymbol{e}\times\boldsymbol{r}_{P}\right)}{\|\boldsymbol{e}\|^{2}}$$
The barycentric coordinates of $Q$ $\begin{pmatrix}w_{A} & w_{B}\end{pmatrix}$ such that $\boldsymbol{r}_{Q}=w_{A}\boldsymbol{r}_{A}+w_{B}\boldsymbol{r}_{B}$ are
$$\begin{array}{c}
w_{A}=\frac{\|\boldsymbol{r}_{Q}\times\boldsymbol{r}_{B}\|}{\|\boldsymbol{m}\|}\\
w_{B}=\frac{\|\boldsymbol{r}_{Q}\times\boldsymbol{r}_{A}\|}{\|\boldsymbol{m}\|}
\end{array}$$
This works only when $\|\boldsymbol{m}\| >0$, or the cylinder axis does not go through the origin.
Check that point $Q$ lies between $A$ and $B$ by making sure the barycentric coordinates are between 0 and 1
$${\rm inside}=\left(w_{A}\ge0\right){\rm and}\left(w_{A}\le1\right){\rm and}\left(w_{B}\ge0\right){\rm and}\left(w_{B}\le1\right)$$

Example
The end points of a cylinder with $R=1.2$ are located at $$ \begin{aligned} \boldsymbol{r}_A & = \pmatrix{3\\0\\0} \\ \boldsymbol{r}_B & = \pmatrix{0\\7\\0} \end{aligned} $$
The target point has coordinates $$ \boldsymbol{r}_P = \pmatrix{1\\2\\0} $$

The infinite line is described by $$ \begin{aligned} \boldsymbol{e} & = \pmatrix{-3 \\ 7 \\ 0} \\ \boldsymbol{m} & = \pmatrix{0 \\ 0 \\ 21} \end{aligned} $$
The distance of the target point to the line is $$ d = \frac{ \pmatrix{0 \\ 0 \\ 21} + \pmatrix{-3 \\ 7 \\ 0} \times \pmatrix{1\\2\\0}}{ \| \pmatrix{-3 \\ 7 \\ 0} \|} = \frac{\| \pmatrix{0 \\ 0 \\ 8} \|}{\sqrt{58}} = \tfrac{8}{\sqrt{58}} = 1.0505 $$
Point on line closest to target point is $$ \boldsymbol{r}_Q = \pmatrix{1\\2\\0} + \frac{\pmatrix{-3 \\ 7 \\ 0} \times \pmatrix{0 \\ 0 \\ 8}}{58} = \pmatrix{1\\2\\0} + \frac{ \pmatrix{56\\24\\0}}{58} = \pmatrix{\tfrac{57}{29} \\ \tfrac{70}{29} \\ 0} = \pmatrix{1.9655 \\ 2.41379 \\ 0} $$
Barycentric coordinates are $$ \begin{aligned}
 w_A & = \frac{ \| \pmatrix{\tfrac{57}{29} \\ \tfrac{70}{29} \\ 0} \times \pmatrix{0\\7\\0} \|}{\| \pmatrix{0\\0\\21} \|} = \frac{ \| \pmatrix{0\\0\\ \frac{399}{29}} \|}{21} = \tfrac{19}{29} = 0.6552 \\
 w_B & = \frac{ \| \pmatrix{\tfrac{57}{29} \\ \tfrac{70}{29} \\ 0} \times \pmatrix{3\\0\\0} \|}{\| \pmatrix{0\\0\\21} \|} = \frac{ \| \pmatrix{0\\0\\ -\frac{210}{29}} \|}{21} = \tfrac{10}{29} = 0.34483
 \end{aligned}$$
Check that $w_A \ge 0\;\checkmark$, $w_A \le 1\;\checkmark$, $w_B \ge 0\;\checkmark$, $w_B \le 1\;\checkmark$.

Edit 1
As noted this method falls flat when the axis of the cylinder goes through the origin. This is because the barycentric calculation above is actually a shortcut of a more general method. To solve for the barycentric coordinates in the general case, you need to solve the following 2×2 system
$$ \left| \begin{matrix}1 + \boldsymbol{r}_A \cdot \boldsymbol{r}_A & 1 + \boldsymbol{r}_A \cdot \boldsymbol{r}_B \\ 1 + \boldsymbol{r}_A \cdot \boldsymbol{r}_B & 1 + \boldsymbol{r}_B \cdot \boldsymbol{r}_B  \end{matrix} \right| \pmatrix{w_A \\ w_B} = \pmatrix{1 + \boldsymbol{r}_Q \cdot \boldsymbol{r}_A \\ 1 + \boldsymbol{r}_Q \cdot \boldsymbol{r}_B } $$
where $\cdot$ is the dot product of two vectors resulting in a scalar value.
Comment: @user297271 - I have confirmed the equation is correct. You can rewrite it as $$d = \frac{\|\boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\boldsymbol{r}_{A}\right)\|}{\|\boldsymbol{e}\|}$$ where $\boldsymbol{e}=\boldsymbol{r}_{B}-\boldsymbol{r}_{A}$. Maybe this form is less prone to implementation bugs.
Comment: @user297271 - The formula in **your link** is identical to my formula. Here is the proof: $$\begin{aligned}d & =\frac{\|\left(\boldsymbol{r}_{B}-\boldsymbol{r}_{P}\right)\times\boldsymbol{e}\|}{\|\boldsymbol{e}\|}\\
 & =\frac{\|\boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\boldsymbol{r}_{B}\right)\|}{\|\boldsymbol{e}\|}\\
 & =\frac{\|\boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\left(\boldsymbol{r}_{A}+\boldsymbol{e}\right)\right)\|}{\|\boldsymbol{e}\|}\\
 & =\frac{\|\boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\boldsymbol{r}_{A}\right)\|}{\|\boldsymbol{e}\|}
\end{aligned}$$
Comment: Thanks, this is working fine. For future references, can you also tell me, from where did you find this? Book, website etc for future references? As I have to solve more problems like these and I could not find this with a lot of Googling. Thanks in advance :_).
Comment: The math here is something I am very familiar with ever since graduate school. But you can find some of the above information in Chapter 3 of "Foundations of Game Engine Development", Vol 1, Eric Lengyel.
Comment: Also read about [Plucker Coordinates](http://web.cs.iastate.edu/~cs577/handouts/plucker-coordinates.pdf) of a spatial line. This formulation is quite powerful. The concepts here touch also on the subject of Projective Geometry & Homogeneous Coordinates.
Comment: Hi, it's been a while since you posted this answer and I have been using this. but recently I found a small bug in this math, the problem is in finding the distance of the point p to the line AB.  While using the formula which you gave here, I'm getting a wrong value of the distance.   The problem is fixed when I use the formula given here, https://onlinemschool.com/math/library/analytic_geometry/p_line/ can you look into this?
Comment: @user297271 - I will look into it. There is also [this formula](https://www.geometrictools.com/Documentation/DistancePointLine.pdf) to consider too.
Comment: yes, but there is an additional +m in your equation for d in the accepted answer. Can you correct that?
Comment: @user297271 - The **m** is not extra. Since $\boldsymbol{m}=\boldsymbol{r}_{A}\times\boldsymbol{r}_{B}$ then you can expand the numerator as $$\begin{aligned}\boldsymbol{m}+\boldsymbol{e}\times\boldsymbol{r}_{P} & =\boldsymbol{r}_{A}\times\boldsymbol{r}_{B}+\boldsymbol{e}\times\boldsymbol{r}_{P}\\
 & =\boldsymbol{r}_{A}\times\left(\boldsymbol{r}_{A}+\boldsymbol{e}\right)+\boldsymbol{e}\times\boldsymbol{r}_{P}\\
 & =\boldsymbol{r}_{A}\times\boldsymbol{e}+\boldsymbol{e}\times\boldsymbol{r}_{P}\\
 & =\boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\boldsymbol{r}_{A}\right)
\end{aligned}$$
Comment: or $$\begin{aligned}\boldsymbol{m}+\boldsymbol{e}\times\boldsymbol{r}_{P} & =\boldsymbol{r}_{A}\times\boldsymbol{r}_{B}+\boldsymbol{e}\times\boldsymbol{r}_{P}\\
 & =\left(\boldsymbol{r}_{B}-\boldsymbol{e}\right)\times\boldsymbol{r}_{B}+\boldsymbol{e}\times\boldsymbol{r}_{P}\\
 & =\left(-\boldsymbol{e}\right)\times\boldsymbol{r}_{B}+\boldsymbol{e}\times\boldsymbol{r}_{P}\\
 & =\boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\boldsymbol{r}_{B}\right)
\end{aligned}$$ depending on what you want.
Answer: You should consider an auxiliary coordinate frame that has its origin at $A$ and its $z$ axis parallel to $AB$. The coordinate transformation is the combination of a translation and a rotation; it can be obtained by Gram-Schmidt orthogonalization.
Now the inside of the cylinder has the simple equation
$$x^2+y^2\le R^2.$$
(And possibly, $0\le z\le \|AB\|$.)

Alternatively, let the test point be $P$. An arbitrary point along the cylindre axis is given by
$$tA+(1-t)B$$ where $t$ runs from $0$ to $1$.
Now the shortest squared distance from $P$ to $Q$ is the one that minimizes
$$(tPA+(1-t)PB)^2=(PB+tBA)^2=PB^2+2PB\cdot BA\,t+BA^2 t^2.$$
By canceling the derivative we obtain
$$t=-\dfrac{PB\cdot BA}{BA^2},$$ which tells if the point lies between the two basis, and the distance is
$$\left\|PB-\dfrac{PB\cdot BA}{BA^2}BA\right\|=\sqrt{PB^2-\frac{(PB\cdot BA)^2}{BA^2}}.$$
Answer: We can solve this by constructing the cylinder negatively: start with an infinite space, and throw out everything that isn't within the cylinder.  This uses John Alexiou's answer but makes it significantly simpler for the second part, as well as more generally correct as it has no special cases where it doesn't work.
This is done with 3 cuts:
First, a cylindrical cut of radius R about an infinite line that goes through A and B. This proceeds as per John Alexiou's answer above:

Points A and B have vectors $\boldsymbol{r}_A$  and $\boldsymbol{r}_B$ .

Direction between them is:
$$\boldsymbol{e} = \boldsymbol{r}_B-\boldsymbol{r}_A$$

Distance from any point P at $\boldsymbol{r}_P$ to the line is:
$$d = \frac{\| \boldsymbol{e}\times\left(\boldsymbol{r}_{P}-\boldsymbol{r}_{A}\right) \|}{\|\boldsymbol{e}\|}$$

Exclude all points with $d > R$.
This can be optimised slightly by comparing the square of the magnitude and radius, avoiding the square root.

Second, a planar cut that throws away the space above the "top" of the cylinder, which I'm calling A.

The plane is defined by any point on it (A will do), and any normal pointing out of the cylinder, $-\boldsymbol{e}$ will do (i.e. in the opposite direction to $\boldsymbol{e}$ as defined above).

We can see which side a point is of this plane as per Relation between a point and a plane:
The point is "above" the plane (in the direction of the normal) if:
$$(\boldsymbol{r}_P - \boldsymbol{r}_A) \cdot -\boldsymbol{e} > 0$$

Exclude points which match the above.

Third, a planar cut which throws away the space below the bottom of the cylinder B.

Same as the previous step, but with the normal vector in the other direction, so the condition is:
$$(\boldsymbol{r}_P - \boldsymbol{r}_B) \cdot \boldsymbol{e} > 0$$

This process constructs the cylinder negatively, and translates directly into 3 tests which must all pass if a point is within the cylinder.
Answer: For your information: I think you mean by a cilinder a body with a circle (not an eclipse) as a ground surface. In $2D$ it simply means that you want to verify if a point $(x_1, y_1)$ is located within the circle with radius $R$, to which most people will say "Easy: just check if $x_1^2+y_1^2 \le R^2$", which is, mathematically speaking, completely correct.
However, when dealing with computers, the situation becomes more complicated: although the mentioned formula is still correct, an easy improvement is possible:
// This is the normal function
function bool inside(float X1, float Y1, float R)
{
    return X1^2+Y1^2 <= R^2;
}

As you can easily see, you are doing at least two multiplications of floating point numbers, which might be very time consuming (certainly when you start checking hundreds, thousands, ... of numbers).
Therefore you can do the following instead:
// This is a faster function
function bool inside_fast(float X1, float Y1, float R)
{
    if (abs(X1) > R
      return false;
    if (abs(Y1) > R
      return false;
    return X1^2+Y1^2 <= R^2;
}

This will check if your point $(x_1, y_1)$ is located within the square with radius $R$. In most cases, your point will be outside and you get a false result, without needing to do any floating point calculation. Only in the case where your point is inside that square, the complete calculation will be performed.


ActiveMQ Persistence Adapter

Question: I have a network of brokers which works correctly with durable subscribers. They're on "store and forward" with "kahaDB persistence".
I have an available distributed database with its own JDBC Driver.
I want to know if it's worth creating a JDBC Adapter, for the broker to store messages on this shared database to complete this distributed network.
Is it possible? If yes, is it worth it?
My activemq.xml:
<code><beans
      xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <!-- Allows us to use system properties as variables in this configuration file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:${activemq.conf}/credentials.properties</value>
        </property>
    </bean>

    <!-- Allows log searching in hawtio console -->
    <bean id="logQuery" class="org.fusesource.insight.log.log4j.Log4jLogQuery"
              lazy-init="false" scope="singleton"
              init-method="start" destroy-method="stop">
    </bean>

    <!-- We change the factory finder to instanciate the correct RedCurrant-class which are compatible -->
    <bean id="FactoryDefinition" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass">
            <value>org.apache.activemq.util.FactoryFinder</value>
        </property>
        <property name="targetMethod">
            <value>setObjectFactory</value>
        </property>
        <property name="arguments">
            <list>
                <bean id="ObjectFactory" class="io.redcurrant.activemq.util.RedCurrantObjectFactory"/>
            </list>
        </property>
    </bean>

    <!--
            The <broker> element is used to configure the ActiveMQ broker.
        -->
    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="RC1" dataDirectory="${activemq.data}" persistent="true">

        <destinationPolicy>
            <policyMap>
                <policyEntries>
                    <policyEntry topic=">" >
                        <pendingMessageLimitStrategy>
                            <constantPendingMessageLimitStrategy limit="1000"/>
                        </pendingMessageLimitStrategy>
                    </policyEntry>
                </policyEntries>
            </policyMap>
        </destinationPolicy>

        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

        <persistenceAdapter>
            <kahaDB directory="/DATA/TestNS/RC1/activemq-1"
                        concurrentStoreAndDispatchTopics="false"
                        enableJournalDiskSyncs="true"/>
        </persistenceAdapter>

        <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage percentOfJvmHeap="70" />
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="100 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="50 gb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>

        <transportConnectors>
            <transportConnector name="openwire" uri="tcp://0.0.0.0:30000?maximumConnections=1000&wireFormat.maxFrameSize=104857600" discoveryUri="redcurrant://default:30000"/>
        </transportConnectors>

        <networkConnectors>
            <networkConnector uri="redcurrant://default"/>
        </networkConnectors>

        <shutdownHooks>
            <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
        </shutdownHooks>

    </broker>

    <import resource="jetty.xml"/>

</beans>
</code>
I work on the integration of ActiveMQ on a distributed system named "RedCurrant", so I create a correct DiscoveryAgent and make some changes in a "jar" which I include in the ActiveMQ/lib.
What I really want to do is a network of broker with persistence. I currently use KahaDB to do this, but is it possible for the brokers to share a database to share messages of a topic more quickly. Should I create a JDBC Adapter (SQLite)?
Comment: hello new user.  it would be helpful if you posted your activemq configuration and what you have tried to do.  thanks.
Comment: I believe yes you can set a JDBC centralized source for your network of brokers, but probably you won't have any performance gain doing that because kahaDB is faster than a relational DB.
Comment: I'm searching a way to persist and deliver the message in a distributed way without having to set up a Master/Slave architecture.

So the central DataBase is, to me, a way to do this, is'nt it?
Comment: also, you should update your question title to be more meaningful and direct us to what you are really asking.  Please take a look at http://stackoverflow.com/help/how-to-ask
Answer: JDBC/database is not the most performant way to persist messages in ActiveMQ.
I don't see the point in using a database anyway, since JDBC is used to share data between a master and a slave, and not between members in a network of brokers (NoB).
If you want short circuit distribution of messages inside a NoB using a database, you really miss the point of NoB. The brokers in the network should be able to independently handle which destinations to propagate and which to handle locally etc.
If you want the messages to propage through the distributed database instead using the brokers as simple connectors, you have some major work in front of you.

ActiveMQ Persistence Adapter


Adicionar onclick ou Listener a um elemento que ainda não existe

Question: Eu tenho um widget externo que tem um formulário, mas não posso mudar a maneira que ele funciona (porque é proprietário). Porém eu preciso saber quando o usuário clicou nele para preencher automático alguns campos como nome e e-mail, que estão guardados na sessão do meu sistema.
Estava pensando em adicionar elemento.addEventListener('click', inserirDados);.
Mas como ele é assíncrono, eu não sei quando ele vai terminar de ser carregado.  Como eu posso fazer isso? Não sei se é importante, mas tanto meu sistema quanto o widget usam apenas javascript puro.
O widget é inserido na página com:
(function() {
    //criação do


Is there any way to mount an EXT4 file system with errors?

Question: I may have been somewhat foolish, but kept putting off the warning signs about the impending failure of my EXT4-on-LVM Ubuntu machine (like the partition remounting itself R/O, SMART errors, etc.) and one day, the FSCK shows "filesystem still has errors"... gulp
I've bought a replacement drive, and I have confirmed I can still see data using photorec, but I was wondering... is there anyway to mount an EXT4 volume even though the OS knows it's broken?
See, I don't need everything on the drive. I basically would like to recover whatever I can from one directory's worth of text files. Running photorec will (probably) get those files back, but it'll mean running lots of greps against the recovered files to find the one-or-two lines of files that I can then use to figure out the bits I'm missing.
Any guidance gratefully accepted!
UPDATE:
From another machine, when I try to mount the drive, I get:
root@Minilith:~# mount /dev/mapper/xubuntu--vg-root /mnt/
mount: /mnt: mount(2) system call failed: Structure needs cleaning.

Running fsck against that volume, I get:
root@Minilith:~# fsck /dev/mapper/xubuntu--vg-root -y
fsck from util-linux 2.31.1
e2fsck 1.44.1 (24-Mar-2018)
ext2fs_check_desc: Corrupt group descriptor: bad block for block bitmap
fsck.ext4: Group descriptors look bad... trying backup blocks...
Block bitmap for group 0 is not in group.  (block 2553887680)
Relocate? yes

Inode table for group 0 is not in group.  (block 3715727360)
WARNING: SEVERE DATA LOSS POSSIBLE.
Relocate? yes

One or more block group descriptor checksums are invalid.  Fix? yes

Group descriptor 0 checksum is 0x11b0, should be 0xaa26.  FIXED.
Block bitmap for group 1792 is not in group.  (block 2553887680)
Relocate? yes

Inode table for group 1792 is not in group.  (block 3682172928)
WARNING: SEVERE DATA LOSS POSSIBLE.
Relocate? yes

Group descriptor 1792 checksum is 0x89a0, should be 0xbabe.  FIXED.
Inode bitmap for group 1793 is not in group.  (block 2097156110)
Relocate? yes

Group descriptor 1793 checksum is 0x5c04, should be 0xd977.  FIXED.
Inode bitmap for group 1795 is not in group.  (block 419506184)
Relocate? yes

Group descriptor 1795 checksum is 0xb484, should be 0x4875.  FIXED.
Inode bitmap for group 1796 is not in group.  (block 2197819406)
Relocate? yes

Group descriptor 1796 checksum is 0x7b44, should be 0x92f0.  FIXED.
Block bitmap for group 1920 is not in group.  (block 2553887680)
Relocate? yes

Inode table for group 1920 is not in group.  (block 3648618496)
WARNING: SEVERE DATA LOSS POSSIBLE.
Relocate? yes

Group descriptor 1920 checksum is 0x2073, should be 0xab14.  FIXED.
Block bitmap for group 4096 is not in group.  (block 2553887680)
Relocate? yes

Inode table for group 4096 is not in group.  (block 4151934976)
WARNING: SEVERE DATA LOSS POSSIBLE.
Relocate? yes

Group descriptor 4096 checksum is 0xc961, should be 0x6ce7.  FIXED.
Block bitmap for group 6016 is not in group.  (block 2553887680)
Relocate? yes

Inode table for group 6016 is not in group.  (block 4000940032)
WARNING: SEVERE DATA LOSS POSSIBLE.
Relocate? yes

Group descriptor 6016 checksum is 0x9648, should be 0x6dd5.  FIXED.
fsck.ext4: e2fsck_read_bitmaps: illegal bitmap block(s) for /dev/mapper/xubuntu--vg-root

/dev/mapper/xubuntu--vg-root: ***** FILESYSTEM WAS MODIFIED *****

/dev/mapper/xubuntu--vg-root: ********** WARNING: Filesystem still has errors **********

UPDATE 2: Following the advice to use options "noload,ro", and separately, to use "debug", I get these lines:
root@Minilith:~# mount -o noload,ro /dev/mapper/xubuntu--vg-root /mnt/
mount: /mnt: mount(2) system call failed: Structure needs cleaning.

And if I also put debug in the options, tailing /var/log/syslog I get:
Jun 22 13:46:17 Minilith kernel: [145133.789232] EXT4-fs (dm-3): ext4_check_descriptors: Block bitmap for group 0 not in group (block 2553887680)!
Jun 22 13:46:17 Minilith kernel: [145133.789242] EXT4-fs (dm-3): group descriptors corrupted!

Answer: You can use the "noload" mount option to mount ext3/4 filesystems that are flagged 'dirty' but it will be in read-only mode.
mount -t ext4 -o noload,ro /dev/mapper/xubuntu--vg-root /mnt/

Should let you at least mount the drive.
Comment: Nope :( Following these suggestions, I've added some other notes to the question :(


$A+ cE$ invertible when $A^T = - A$

Question: $A^T = - A$
Prove that if $\lambda \neq 0$ is a constant, then $A+ \lambda I$ is always invertible.
(where $I$ is the identity matrix)
My idea is to show that $0$ is the only eigenvalue so that $|A+\lambda I|$
I have shown that if $\lambda$ is an eigenvalue, then so must $-\lambda$. But I'm not sure how to show $0$ is the only eigenvalue from there.
Is my approach correct? Or is there a simpler way to approach this?
Thank you!
Comment: @mechanodroid I have no doubts about that (althougn I think that the OP should have stated it).
Comment: @JoséCarlosSantos Thanks. So $\lambda$ in the question is assumed to be real, I suppose.
Comment: @Arthur  Ah, I'm wrong. Never mind.
Comment: This is clearly wrong. The matrix $A = \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix}$ has eigenvalues $\pm i$ so $A \pm iI$ is noninvertible.
Comment: @mechanodroid Actually, the eigenvalues of your matrix are $\pm i$.
Comment: @JoséCarlosSantos, Yeah. My bad. $\lambda$ is presumed to be real.
Answer: The eigenvalues of a skew-symmetric matrix are all purely imaginary. One proof can be found here, by looking at how the matrix behaves with respect to the complex scalar product using a complex eigenvector of $A$.
Answer: $A$ is skew -symmetric. Try to show that each eigenvalue of $A$ is of the form $it$ with $t \in \mathbb R$, (where $i^2=-1$).
Comment: Thank you! I think I have understood how to approach this question from this hint.

$A+ cE$ invertible when $A^T = - A$


Are there parametric equations with trigonometric functions for the parabola $f(x)=x^2$?

Question: Parametric equations for the circle:
$$
x(t)=\cos(t)\qquad y(t)=\sin(t)
$$
Parametric equations for the ellipse:
$$
x(t,a)=a\cos(t)\qquad y(t,b)=b\sin(t)
$$
Parametric equations for the hyperbola:
$$
x(t)=\cosh(t)\qquad y(t)=\sinh(t)
$$
Are there equations for the parabola that follows this pattern?
Answer: Unfortunately, the parameterization that follows the pattern is simply $$y = \frac{t^2}4\quad x = \frac t2.$$
This is because trigonometric functions come from $e^{it}$ where $i^2 = -1$ in the elliptic case, $i^2 = 1$ in the hyperbolic case, and $i^2= 0$ in the parabolic case. They are known as complex, split complex and dual numbers, respectively.
However you can have trig parameterizations that doesn't follow the pattern. For example $$y = \frac{\cos t}{1-\cos t}\qquad x = \frac{\sin t}{1-\cos t}$$ up to some coefficient.
Comment: Wait, can you elaborate on why we can't define trigonometric identities in the dual number plane or alternatively could you "simulate" a failed attempt at trying to do so?
Comment: @mathcel3000 $e^{it} = 1 + it + 0 + 0 + \cdots$ so it only generates a linear thing.
Answer: By using Equation (10) and Equation (11) from the paper https://www.researchgate.net/publication/327652282_Parabolic_Trigonometry, I tried the following parametric form of the e.g. parabola $x=-\frac{y^{2}}{4}+1$:
$$\left(x,y\right)=\left(3-2\cosh2t,+4\sinh t\right)$$
You may see its plot here https://www.desmos.com/calculator/cmsi6davzl.
You should see that these hyperbolic functions are in fact a parametrization of the parabola by, instead of making the canonical parametrization $y=t \Leftrightarrow x=-\frac{t^{2}}{4}+1$, making it $y=4\sinh t \Leftrightarrow x=-4\sinh^{2} t+1=3-2\cosh2t$.


Montar uma tabela de produtos como vitrine em java jsp

Question: Estou com uma dificuldade em apresentar uma lista de produtos tipo vitrine usando Java e JSP.
Consigo obter os dados, mas não sei preencher essa tabela usando o <c:forEach>
Minha tabela teria essa estrutura:

    <c:forEach items="${produtos}" var="p">

             ${p.nome } 	 ${p.nome } 	 ${p.nome }

    </c:forEach>

Porém o que é exibido é:
**produto 1 produto 1 produto 1**
**produto 2 produto 2 produto 2**
**produto 3 produto 3 produto 3**

Queria que exibisse assim:
**produto 1 produto 2 produto 3**
**produto 4 produto 5 produto 6**

Answer: Para escrever de 3 em 3 produtos você pode fazer algo neste sentido:
Usar um contador varStatus, por exemplo contador, pra saber qual o índice do forEach, dessa forma toda vez que o contador.count for divisível por 3 você fecha a linha atual e adiciona um nova linha na tabela.

    <c:forEach items="${produtos}" var="p" varStatus="contador">

             ${p.nome }
        <c:if test="${contador.count % 3}">

        </c:if>
    </c:forEach>

No final você pode acabar com um
 a mais, deixando o seu HTML inconsistente, para resolver essa situação faça uma checagem c:if antes de escrever o novo
, você deve checar se o contador é menor que o tamanho da lista.
Como não sei se você está usando array ou lista você pode checar o tamanho com .length() e .size() respectivamente.


Simulation algorithm using copulas

Question: Say that I have a bivariate random variable $X=(X_1,X_2)$ with known marginal distributions $F_1$ and $F_2$ and a known covariance matrix $S$. However, I do not know the joint distribution of $(X_1,X_2)$ and therefore not its copula.

If I decide to use a Gaussian copula to simulate from the joint distribution, how do I choose which Gaussian copula to use and what exactly is the simulation algorithm?
Is it correctly understood that because I do not know the joint distribution and therefore not the "correct" copula, that this simulation algorithm will only result in random variables that have the correct marginal distributions and covariance matrix, but not necessarily the correct joint distribution?
Comment: +1 Thank you.  It might be worth pointing out that usually in statistics "known" means *specified with perfect mathematical accuracy* whereas you describe a situation in which the $F_i$ and $S$ are only *estimated*: they are not "known" at all.  If you indeed have historical data sufficient to estimate these quantities with excellent accuracy, then why not use the same data to estimate the entire joint distribution?
Comment: Your question is confusing because a Gaussian copula together with the marginal distributions determines the joint distribution, yet you state you don't know the joint distribution. Do you mean that you don't know the parameters of the Gaussian copula? If so, doesn't that make your question pointless, given that different Gaussian copulas can produce such a huge range of joint distributions?  If not, then how are we to resolve the apparent contradictions in your description?
Comment: I don't know the joint distribution and therefore I don't know the "correct" copula (however, I have historical data to estimate the covariance matrix S). If I now decide to use a Gaussian copula, how do I choose which one to use and what is the simulation algorithm?
Comment: Since that is quite a different question than you have posted, please edit your post so that it articulates what you want to know.
Comment: Yes, that is a very good point. I modified the question again.
Answer: Since you have empirical data to estimate the copula, you have really two questions: 1) How to estimate a copula from empirical data? and 2) How to simulate from some estimated (gaussian) copula.  Both question have been asked here before, separately.
Question 2 is here: How to simulate from a Gaussian copula?  with a good answer. You can find other relevant posts by searching this site for "copula simulation".  For question 1 I cannot find a post with some really good answers, this is the best one:  Estimating joint distributions using copula package in R.  But there are some good information on the internet, have a look at https://firsttimeprogrammer.blogspot.no/2016/03/how-to-fit-copula-model-in-r-heavily.html  and  https://www.r-bloggers.com/how-to-fit-a-copula-model-in-r-heavily-revised-part-2-fitting-the-copula/

Simulation algorithm using copulas


Notation: grace note played on the beat with a chord

Question: I want to write a four note chord in which three notes are held but one note is played and released very quickly. The extra note is played on the beat with the rest of the chord so is not an acciaccatura or appoggiatura. How should I notate this?
If I write it as a normal chord but with different note durations it could look quite confusing depending on note durations and stem directions.
X: 1
K: C
L:1/2
%%score (T1 T2)
V:T1 clef=bass
V:T2 clef=bass
[V:T1] [D,,G,,D,]
[V:T2] _B,,,/8

is understandable, but
X: 1
K: c
L:1/2
%%score (T1 T2)
V:T1 clef=bass stem=up
V:T2 clef=bass stem=up
[V:T1] [A,,/2E,G,]
[V:T2] C,/16

isn't, however much you change the stem directions.
Ideally I'd like a solution that's achievable with pen and paper, musescore and/or lilypond.
Comment: @CarlWitthoft turns out you have to have both X: and K: defined for SE to recognise it as ABCjs.
Comment: Also if someone can tell me how to get my ABCjs to work here that'd be great!
Comment: Well, you could generate the images and post them - more work, I know.
Comment: Without seeing your proposed implementations, I can suggest that you keep all notes on one stem and simply have, e.g., three half-notes on the left side and one staccato sixteenth on the right (with following rests optional)
Comment: I thought that an acciaccatura was played at the same time as the other notes.  Is that not so?
Comment: It's very common to have staccato chord blocks played simultaneously with a melody and to sustain only the melody note. This is notated exactly like you suggest, so your way is perfectly fine.
Answer: If all the stems point outward, it's easy, as you've noticed.  If the  note with a different duration is in the middle of the chord, you can write the noteheads slightly out of alignment so they only touch the stem that applies to them.
For example, if you have, in the right hand of a piano score, a quarter note open fifth with a figure in sixteenth notes comprising pitches between the two quarter notes, you have four options.
If the quarter note stems point down and the sixteenth note stems point up, write the first sixteenth notehead slightly to the right, by perhaps half the width of a notehead.
If the quarter note stems point up and the sixteenth note stems point down, write the first sixteenth notehead slightly to the left instead.
If all the stems have to go in the same direction, give the noteheads a horizontal displacement of just a bit more than one notehead's width.  This can be tricky.  You will need to have the sixteenth notes spaced rather farther from each other than the horizontal distance between the quarter noteheads and the first sixteenth.  I think it would be easier to read if the quarters were to the right of the first sixteenth, but I'm not certain of it.
Bach's solo violin and keyboard works frequently use a notation style in which simultaneously sounded notes do not share their stems.  It might be interesting to look through these for some inspiration.
Lilypond does this automatically to some extent and provides a way of overriding the automatic layout.  MuseScore does it as well.
This can be achieved in ABCjs with y:
X: 1
K: c
L:1/2
%%score (T1 T2)
V:T1 clef=bass stem=up
V:T2 clef=bass stem=up
[V:T1] [A,,/2E,G,]
[V:T2] y/32C,/16

Or
X: 1
K: c
L:1/2
%%score (T1 T2)
V:T1 clef=bass stem=up
V:T2 clef=bass stem=up
[V:T1] [A,,/2E,G,] [A,,/2E,G,] | [F,/2A,/2]
[V:T2] y/32D,/4C,/4 B,,/4^C,/4  D,/2

Clearer:
X: 1
K: c
L:1/2
%%score (T1 T2)
V:T1 clef=bass stem=up
V:T2 clef=bass stem=down
[V:T1] y/32[A,,/2E,G,] [A,,/2E,G,] | [F,/2A,/2]
[V:T2] D,/4C,/4 B,,/4^C,/4  y/32 D,/2

Answer: This can be done with an Acciaccatura. How it is played depends on the time period it was written in, but is largely up to the interpretation of the performer.

In classical music this is often played on the beat with the rest of the chord slightly delayed and played immediately after.

Sometimes, especially if the Acciaccatura falls at the end of the previous measure, it is played slightly before the beat, with the main note/chord falling on the beat.

The last option is played simultaneously with the main note/chord and quickly released. This is more common in 19th century works and in fast passages where the previous options aren't practical.

The last example is what you are looking for (remember to notate it like the first example!), but is the least common overall and is likely to be interpreted differently by the performer. Leaving this open to the performer is standard practice (as with all ornamental expressions) and is probably the best choice. However, if you are really set on it being played a certain way, I would simply notate that in plain text.
Answer: You use two "voices" or "layers" or whatever your favourite notation software calls them, like this.

A good notation program will get the horizontal spacing correct automatically. Whether Lilypond or Musescore are "good" by that definition, I don't know.