Single value list index into integer in Python?

Question: Is it possible to turn a single value list (e.g. [5]) index (e.g. 4) into an integer when enumerating it? I'm trying to make a program that creates a random username with given words and numbers, and I want to delete a word if it has already been used before:
import random

# data (words/numbers)
words = ['Cool', 'Boring', 'Tall', 'Short']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

# words
word_1 = random.choice(words)
selected_word = [i for i,x in enumerate(words) if x == word_1]
words.pop(selected_word)
word_2 = random.choice(words)

# numbers
number_1 = random.choice(numbers)
number_2 = random.choice(numbers)

# printing username
print(word_1+word_2+number_1+number_2)

Comment: What exactly are you asking here? If you have a single-value list `lst=[5]`, and you index it with `lst[4]`, that's going to be an `IndexError`, because there aren't that many values.
Comment: Or are you just asking how to turn a string into an int, so in `for number in numbers:`, you can do something with `4`, `5`, etc. instead of `'4'`, `'5'`, etc.? If so, you just use `int(number)` in the code inside the loop instead of `number`.
Comment: FWIW, deleting stuff from the middle of a list isn't very efficient, so it's generally better to use different logic when you have a choice. Also, what happens if you want to create more than one username? I recommend abarnert's approach: use `sample`. And I'd probably use `randrange` to generate a 2 digit number, and then convert that to a string, rather than choosing from a list of digit strings.
Answer: Looking at your code… I'm not sure what it's supposed to be doing, but I can make some guesses.
First you pick a random word. Then you look up the indices of all words that match that word. Then you want to use that list of indices with pop.
Well, you can fix that:
for idx in reversed(selected_word):
    words.pop(idx)

(The reversed is important so you pop the rightmost ones first.)
But there's no need for that, because there should only ever be one copy of word_1 in words, and therefore only one index in selected_word. So you can just do this:
words.pop(selected_word[0])

But in that case, the comprehension is unnecessary. Getting all matches and taking the first does the same thing as taking the first match, and lists already have a method for that: index.
words.pop(words.index(word_1))

But really, instead of picking a word and then looking it up to get the index, you could just get the index:
index = random.randrange(len(words))
word_1 = words.pop(index)

Or, most simply of all, just replace the whole thing with:
word_1, word_2 = random.sample(words, 2)

Answer: May be you wanted this (without deleting any word)?:
>>> import random
>>> words = ['Cool', 'Boring', 'Tall', 'Short']
>>> numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> selected_word_indices = set()
>>> def select_word():
        if len(selected_word_indices) == len(words):
            raise Exception("No More Unique Word Left")
        while True:
            chosen_index = random.randint(0,len(words)-1)
            if chosen_index not in selected_word_indices:
                chosen = words[chosen_index]
                selected_word_indices.add(chosen_index)
                return chosen

>>> word_1 = select_word()
>>> word_2 = select_word()

>>> number_1 = random.choice(numbers)
>>> number_2 = random.choice(numbers)

>>> print(word_1+word_2+number_1+number_2)

With del selecting will be simpler but a copy of words will be required (if you want the original list, words unchanged):
>>> words_copy = words.copy()
>>> def select_word():
        if len(words_copy) == 0:
            raise Exception("No More Unique Word Left")
        chosen_index = random.randint(0,len(words_copy)-1)
        chosen_word = words_copy[chosen_index]
        del words_copy[chosen_index]
        return chosen_word


Tabela responsivo fica desformatada

Question: Estou a criar a seguinte tabela responsivo, mas não está de acordo com o que pretendo:
CSS:
table {
    max-width: 100%;
    background-color: transparent;
    border-collapse: collapse;
    border-spacing: 0;
    font-family: arial;
  }

  .table {
    border-bottom: #999999 solid 1px;
    width: 100%;
    margin-bottom: 20px;
  }

  .table th,
  .table td {
    border-right: #999999 solid 1px;
    font-size: 8px;
    padding: 8px;
    line-height: 10px;
    text-align: left;
    vertical-align: middle;
  }

  .table td:last-child {
     border-right: 0;
  }

  .table thead th {
    font-weight: normal;
    background-color: #005dab;
    color: #fff;
    font-size: 8px;
  }

  .table tbody > tr:nth-child(odd) > td,
  .table tbody > tr:nth-child(odd) > th {
    background-color: #f8f8f8;
  }

/* Small Sizes */
@media (max-width: 767px) {

  /* Responsive Table */
  .table-responsive {
    display: block;
    position: relative;
    width: 100%;
  }

  .table-responsive thead,
  .table-responsive tbody,
  .table-responsive th,
  .table-responsive td,
  .table-responsive tr {
    display: block;
  }
  .table-responsive td,
  .table-responsive th {
    height: 35px;
  }

  .table-responsive thead {
    float: left;
  }

  .table-responsive tbody {
    width: auto;
    position: relative;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    white-space: nowrap;
  }

  .table-responsive tbody tr {
    display: inline-block;
  }

  .table td:last-child {
     border-right: #999999 solid 1px;
  }
}

Code:
$result_cursos = "SELECT * FROM raddb.ListagemPrduto WHERE Ativo = '1'";
$resultado_cursos = mysqli_query($conn, $result_cursos);

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .= '
';

$tabela1 .= 'Produtos	';

$tabela1 .= 'No Carro	';

$tabela1 .= 'Na Prateleira	';

$tabela1 .= 'Data na Emb.	';

$tabela1 .= 'Observação	';

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .= 'Tem	';

$tabela1 .= 'Não Tem	';

$tabela1 .= 'Tem	';

$tabela1 .= 'Não Tem	';

$tabela1 .= 'Tem	';

$tabela1 .= 'Não Tem	';

$tabela1 .= '
';

$tabela1 .='
';

$tabela1 .='
';

$y = 0;
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .= ' <input type="text" readonly="true" size="20" name= "Produto['.$y.']" class= "Produto" value="'.$rows_cursos['Descricao'].'">	';

$tabela1 .= ' <input type="radio" class="r" name= "Sim['.$y.']" value="Ok" required>	';

$tabela1 .= ' <input type="radio" class="r" name= "Sim['.$y.']" value="Não Ok" required>	';

$tabela1 .= ' <input type="radio" class="p" name= "Stock['.$y.']" value="Ok">	';

$tabela1 .= ' <input type="radio" class="p" name= "Stock['.$y.']" value="Não Ok">	';

$tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Ok" '.$property.'>	';

$tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Não Ok" '.$property.'>	';

$tabela1 .= ' <textarea type="text" class= "Observacao" name="Observacao['.$y.']" rows="2" cols="30"></textarea>	';

$tabela1 .= '
';
$y++;
}

$tabela1 .='
';

$tabela1 .= '
';

$tabela1 .= '
';

$tabela1 .= '
';

echo $tabela1;

Se visualizar em tela de computador, retorna assim:

Se for na tela de telemóvel fica desta forma:

Os cabeçalhos ficam de forma diferente, mesmo na vertical devia ficar com o formato igual ao do cabeçalho na horizontal
HTML renderizado:

            Quarto
            Utente
            Inicio Tarefa
            Tarefa
            Fim Tarefa
            Colaborador
            Observações

            <?php
        do{
    ?>
            <?php echo $produto["Quarto"]; ?>
            <?php echo $produto["nome"]; ?>
            <?php echo $produto["IniciarTarefa"]; ?>
            <?php echo $produto["Descricao"]; ?>
            <?php echo $produto["FimTarefa"]; ?>
            <?php echo $produto["Colaborador"]; ?>
            <?php echo $produto["Observacao"]; ?>

<?php } while($produto = $result1->fetch_assoc()); ?>

Comment: Cara e pq que vc está mexendo com o display da tabela. Pq vc esta mudando ele o os demais display de tr/td? A tabela era para funcionar perfeitamente, o que está "estragando" e vc mudando o display original para outro... Se puder edita a pergunta tb, e coloca uma tabela que já tenha side renderizada no HTML, com o código em HTML mesmo
Comment: @hugocsl  já editei a pergunta e adicionei tabela com o código html
Comment: Vc está usando Bootstrap? Se sim qual versão?
Answer: Como te alertei no comentário, tabela é uma coisa que não se deve mudar os display, pois ela é uma estrutura complexa, com relação Intrínseco entra as partes table>tr>td
Removendo os display ela fica estável, mesmo em telas pequenas.

Segue o código.

table {
    max-width: 100%;
    background-color: transparent;
    border-collapse: collapse;
    border-spacing: 0;
    font-family: arial;
}

.table {
    border-bottom: #999999 solid 1px;
    width: 100%;
    margin-bottom: 20px;
}

.table th,
.table td {
    border-right: #999999 solid 1px;
    font-size: 8px;
    padding: 8px;
    line-height: 10px;
    text-align: left;
    vertical-align: middle;
}

.table td:last-child {
    border-right: 0;
}

.table thead th {
    font-weight: normal;
    background-color: #005dab;
    color: #fff;
    font-size: 8px;
}

.table tbody > tr:nth-child(odd) > td,
.table tbody > tr:nth-child(odd) > th {
    background-color: #f8f8f8;
}

/* Small Sizes */
@media (max-width: 767px) {

    /* Responsive Table */
    .table-responsive {
        /* display: block; */
        position: relative;
        width: 100%;
    }

    .table-responsive thead,
    .table-responsive tbody,
    .table-responsive th,
    .table-responsive td,
    .table-responsive tr {
        /* display: block; */
    }

    .table-responsive td,
    .table-responsive th {
        height: 35px;
    }

    .table-responsive thead {
        /* float: left; */
    }

    .table-responsive tbody {
        width: auto;
        position: relative;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        white-space: nowrap;
    }

    .table-responsive tbody tr {
        /* display: inline-block; */
    }

    .table td:last-child {
        border-right: #999999 solid 1px;
    }
}

            Quarto
            Utente
            Inicio Tarefa
            Tarefa
            Fim Tarefa
            Colaborador
            Observações

            <?php echo $produto["Quarto"]; ?>
            <?php echo $produto["nome"]; ?>
            <?php echo $produto["IniciarTarefa"]; ?>
            <?php echo $produto["Descricao"]; ?>
            <?php echo $produto["FimTarefa"]; ?>
            <?php echo $produto["Colaborador"]; ?>
            <?php echo $produto["Observacao"]; ?>

            <?php echo $produto["Quarto"]; ?>
            <?php echo $produto["nome"]; ?>
            <?php echo $produto["IniciarTarefa"]; ?>
            <?php echo $produto["Descricao"]; ?>
            <?php echo $produto["FimTarefa"]; ?>
            <?php echo $produto["Colaborador"]; ?>
            <?php echo $produto["Observacao"]; ?>

            <?php echo $produto["Quarto"]; ?>
            <?php echo $produto["nome"]; ?>
            <?php echo $produto["IniciarTarefa"]; ?>
            <?php echo $produto["Descricao"]; ?>
            <?php echo $produto["FimTarefa"]; ?>
            <?php echo $produto["Colaborador"]; ?>
            <?php echo $produto["Observacao"]; ?>

            <?php echo $produto["Quarto"]; ?>
            <?php echo $produto["nome"]; ?>
            <?php echo $produto["IniciarTarefa"]; ?>
            <?php echo $produto["Descricao"]; ?>
            <?php echo $produto["FimTarefa"]; ?>
            <?php echo $produto["Colaborador"]; ?>
            <?php echo $produto["Observacao"]; ?>

Comment: o problema é que se abir uma pergunta nova irão colocar como duplicada, por isso perguntei se poderia falar no chat e expor o problema
Comment: estou com problema nesta pergunta que já foi respondida. Será que posso colocar uma dúvida no [chat](https://chat.stackexchange.com/rooms/98361/discussion-between-bruno-and-ivan-ferrer) uma vez que já fiz a pergunta e foi respondida?
Comment: @Bruno se for algo simples pergunta aqui que te respondo. Se for algo que vai precisar de mais código ai seria legal abrir uma nova pergunta e colocar seu código atual explicando o problema que encontrou etc, pois aqui não da para colocar código etc, então só daria para te responder em uma pergunta nova. Assim  agente não bagunça essa pergunta que já foi finalzada etc

Tabela responsivo fica desformatada


Vaadin 7 url navigation hashbang

Question: I'm trying to fully understand Navigation in Vaadin 7. I read the Navigator Chapter in the Vaadin book but still have some practical questions.
Basically it is about using the bang (!). When do I need to set it and why?

There is a view (myview)
There is a parameter (param=X)
The parameter is identifying a displayed label

Example for browser history:
I need to set the bang (!) or clicking back in the browser does not work, because the parameters is not passed the the views enter function:
<code>private void showInfo(String info) {
    infoLabel.setValue(info);
    Page.getCurrent().setUriFragment("!" + "myview/param=" + info, false);
}
</code>
Example for navigation after button click:
I must not set the bang (!) or else the url fragment changes to "#!myview//param=X" (contains double /)
<code>@Override
public void buttonClick(ClickEvent event) {
    getUI().getNavigator().navigateTo("myview/param=X")
}
</code>
Am I mixing two concepts here or is there a utility that does that for me and I'm not knowing it? Or do I just have to know about these 2 cases and decide about the bang myself?
Thanks
Answer: You don't need to set the '!' at all - except you want force your sites to be crawled by search engines (see GoogleDevelopers Spec). Some people even say, these hash bangs are very bad UI practice.
Or is it a requirement for your application that its whole content is indexed by search engines ?
Comment: I don't care about indexed by search engines at all, but as I wrote, the back (history) function from the browser does not work in vaadin if it is not set. The `Navigator` from vaadin ignores the parameters.

Vaadin 7 url navigation hashbang


this dentro de um construtor, o que faz?

Question: boas , alguém me pode dizer o que é que este this faz ?
public Tempo (){
    this(0,0,0);
}
public Tempo (int h){

    this(h,0,0);
}
public Tempo ( int h,int m){

    this (h,m,0);
}
public Tempo (int h,int m , int s){
    SetTime(h,m,s);

}

Answer: A construção this dentro do construtor serve para chamar outro construtor.
Ou seja this(0,0,0); vai chamar o construtor
public Tempo (int h,int m , int s){
    SetTime(h,m,s);
}

Ela não pode ser usada num método convencional e tem que ser obrigatoriamente a primeira instrução dentro do construtor, isto é, se pretender usá-la. É só uma forma de manter a lógica de inicialização do objeto em apenas um dos construtores.
Comment: Ao chamar o construtor significa que vai executar o conteúdo desse construtor ,ou seja o método setTime ?
Comment: Perfeito, Bruno.
Só para complementar, o que vai definir qual construtor que será chamado, são os tipos e a quantidade de parâmetros passada no método this().
Comment: @PedroGouveia Sim Pedro, ele vai chamar o `setTime`


How many circular distinct compositions of $n$ into $k$ parts at most $g$

Question: how many circular distinct sequences (e.g. $(4124)\equiv(4412$)) are there that sum up to $n$, have $k$ elements may be non-negative integers at most $g$?
In other words: we're looking for the number of compositions of $n$ into $k$ parts that are at most $g$ and 0 is allowed. Let $C_{k,g}^\prime(n)$ denote that number.
If $n\leq 2g$, I already know, that $$C_{k,g}^\prime(n)=\pmatrix{n-g+k-2 \\ k-2}.$$ The central formula is taken from [1] and I inserted as resuming sum $n-g$ and $k-1$ parts.
Now, whats that number, if $n>2g$?
For example $C_{4,2}^\prime(6)=3$, since the possible sequences are
(2211), (2121), (2220) and all other compositions of 6 into 4 parts circular equivalent to one of those 3 sequences.
[1] http://mathworld.wolfram.com/Composition.html
Answer: We can at least express these numbers in terms of their non-circular analogs. The equivalence classes for circular compositions can be formulated in the language of group actions. Thus, Burnside's lemma is a natural tool to apply here.
A cyclic group element $j \in \mathbb{Z}_k$ acts on the $k$ parts of a non-circular composition by rotating the parts $j$ units to the right. Two compositions are equivalent as circular compositions if they are in the same orbit under this action. Burnside's lemma gives:
$$\text{number of orbits} = \frac{1}{|\mathbb{Z}_k|} \sum_{j \in \mathbb{Z}_k} |X_j|,$$
where $X_j$ is the set of compositions fixed by the action of $j$. We can express $|X_j|$ in terms of the non-circular composition numbers $C_{k,g}(n)$.
If the action of $j$ fixes a composition $c$, then $\text{GCD}(j,k)$ parts determine the composition. Those parts repeat $\frac{k}{\text{GCD}(j,k)}$ times. So, the sum of those parts is $\frac{n}{\frac{k}{\text{GCD}(j,k)}} = \frac{n\text{GCD}(j,k)}{k}$. For example, $\overline{4} \in \mathbb{Z}_6$ fixes $212121$. The composition is determined by the $\text{GCD}(4,6) = 2$ parts $21$. The sum of those parts is $\frac{9\text{GCD}(4,6)}{6} = 3$.
Set $k' = \text{GCD}(j,k)$. There is a correspondence between compositions of $n$ with $k$ parts less than or equal to $g$, fixed by the action of $j$, and compositions of $\frac{nk'}{k}$ with $k'$ parts less than or equal to $g$ as long as $k' | n$. It follows that
$$C_{k,g}'(n) = \frac{1}{k} \sum_{j=1}^k C_{k',g}\left(\frac{nk'}{k}\right),$$
where we take $C_{k',g}(n')$ to be zero if $n'$ is not an integer. (In other words, it's zero if $\frac{k}{k'} \not| n$.)
Note that $j = k$ ensures at least one summand, namely $C_{k,g}(n)$.
This is reasonably usable as long as $C_{k,g}(n)$ is. (See comments.)
Comment: There is a generating function for $C_{k,g}(n)$ given in Theorem 2.2 of Bruce Sagan's paper "Compositions inside a rectangle and unimodality". It's a nice enough generating function that the numbers $C_{k,g}(n)$ should themselves be given by a decent formula or recursion.


Computing spectra in Banach algebras

Question: In general, computing the spectrum of a specific element in a Banach algebra can be very difficult. What are some of the less obvious tricks that you've encountered?
Answer: Some important tricks/theorems:

The spectrum is non-empty for Banach algebras (over $\mathbb{C}$)
The spectral radius formula
$$
r(a) = \lim \|a^n\|^{1/n}
$$
tells you that if $a$ is nilpotent, then $\sigma(a) = \{0\}$
If $A$ is commutative, then
$$
\sigma(a) = \{\tau(a) : \tau \in \Omega(A)\}
$$
where $\Omega(A)$ denotes the set of non-zero multiplicative linear functionals on $A$
If $B$ is a unital subalgebra of $A$ with the same unit as $A$, and $a\in B$, then
$$
\sigma_A(a) \subset \sigma_B(a)
$$
and
$$
\partial \sigma_B(a) \subset \sigma_A(b)
$$
where $\sigma_A(a)$ and $\sigma_B(a)$ denote the spectra in relative to those algebras.
In particular, if $\sigma_A(b)$ has no "holes" (bounded connected components of $\mathbb{C}\setminus \sigma_A(b)$), then
$$
\sigma_B(a) = \sigma_A(b)
$$
This is often handy when $B$ can be chosen to be commutative.
If $A$ is a $C^{\ast}$-algebra, then we get
$$
\sigma_B(a) = \sigma_A(a)
$$
for any element $a$ (regardless of whether $\sigma_A(a)$ has holes or not)
Furthermore, if $A$ is a $C^{\ast}$-algebra, then knowing the relationship between $a$ and $a^{\ast}$ is often helpful. For instance, if $a = a^{\ast}$, then
$$
\sigma(a) \subset \mathbb{R}
$$
If $aa^{\ast} = a^{\ast}a = 1_A$, then
$$
\sigma(a) \subset \mathbb{T}
$$
and so on.

Computing spectra in Banach algebras


Using existing questionnaire

Question: I will be doing my colloquium and will be using existing questionnaires. I would like to know if there are authors/authorities who say that an existing questionnaire need not be validated.
The questionnaires I will use were already validated and the reliability is good; even their cross-cultural validity and reliability were good. I just want to cite or mention some authors saying that an existing questionnaire does not need further validation.
Comment: This seems a curious request. If you know that your questionnaire already has good credentials, you can explain that fact directly with as much as detail as needed. You don't need another layer of references; in fact wanting authorities for use of authorities puts you at risk of an infinite regress of citations.
Answer: You will rarely encounter the word "validated" in the psychometrics literature. Current thinking is that validation is an on-going process on which many type of evidence can be brought to bear. The validity of a particular measurement instrument also depends on the interpretations you want to draw from it and the specific population you are studying (see e.g. Messick, 1995). Consequently, a questionnaire can hardly be validated once and for all.
Many techniques that could be relevant (say factor analysis) also often require quite a large sample size to yield stable results, so if you plan to run a relatively small study (either because it is convenient and accepted in your field or better yet because a power analysis suggests it is appropriate), it would not necessarily be very useful to try to "validate" the scale again with these techniques as any discrepant result could/should reasonably be explained away as a consequence of the sample size and you will have extremely low power to empirically distinguish between various potential models.
Regarding reliability, there are some authors who indeed recommend computing reliability estimates on your own data instead of relying on published estimates, see Reliability and validity of a standard survey. The idea is that reliability is not so much a property of a scale per se as it a property of the scores (i.e. a set of measures on a specific population).
At the same time, computing and reporting usability estimates is fine but what do you intend to do with them? There are many ways to use them of course (correcting other estimates, redesigning the scale…) but they are not always relevant in typical psychology experiments. It is also important to note that reliability is not limited to item-related variance (see generalizability theory for a systematic account) and that popular thresholds are completely arbitrary (see Lance, Butts, & Michels, 2006). In fact, published guidelines vary quite a lot and I can provide well-known "authorities" recommending anything from .5 to .9 as a minimum and even some other authorities arguing against internal consistency as a valuable characteristic for psychological scales. Computing Cronbach's $\alpha$ and writing "it's over .8 so I'm fine", as many people do, therefore does not seem very useful.
All this would seem to make the question moot. You do need to think about the appropriateness of the measurement procedures for your purpose but even if you had the inclination and resources to conduct an ambitious validation study, you would not conclude that your scale is absolutely "valid", just that it has this or that structure, is related to this or that other measure, etc. It is therefore more fruitful to think about the meaning of your measures and the inferences warranted by your study than to worry about "validating" or not "validating".
One final point to consider is that using well-known scales also increases the comparability between different studies. Even if a particular questionnaire has some well-known limitations, it can be reasonable to use it for that reason alone (possibly together with other scales).

References cited:

Lance, C.E., Butts, M.M., & Michels, L.C. (2006). The sources of four commonly reported cutoff criteria: What did they really say? Organizational Research Methods, 9 (2), 202-220.
Messick, S. (1995). Validity of psychological assessment: Validation of inferences from persons' responses and performances as scientific inquiry into score meaning. American Psychologist, 50 (9), 741-749.
Comment: I wish I could give you more than one vote.  That is a great answer!

Using existing questionnaire


Migrate to the Twilio Voice 5.0 (iOS 13, Xcode 11): Custom incoming call view controller, reject incoming call issue

Question: I'm migrating iOS app to the Twilio Voice 5.x API (iOS 13 & Xcode 11) and have some questions:

My app uses incoming calls. Twilio requires: 3. Report the call to CallKit. Refer to this example for how to report the call to CallKit.
My question: Does it mean I can't use more custom incoming call view controller in foreground mode?
Right after getting call invite I send request to get info about caller and show it. I do it in background. It worked in previous versions but
doesn't work now because interruption and handler must work at the same thread and immediately. What do you advise?
Answer:
You can update value on the CallKit inbound call screen by using reportCall like this:
extension TwilioInteractor: TVONotificationDelegate {
<code>func callInviteReceived(_ callInvite: TVOCallInvite) {
    let from = callInvite.from ?? "?"
    let uuid = callInvite.uuid
    displayIncomingCall(from: from, uuid: uuid)
    fetcher.fetchCaller(for: from, callInvite: callInvite) { caller in
        self.updateIncomingCall(from: caller, uuid: uuid)
    }
}

private func displayIncomingCall(from: String, uuid: UUID) {
    let callHandle = CXHandle(type: .generic, value: from)
    let callUpdate = CXCallUpdate()
    callUpdate.remoteHandle = callHandle
    callUpdate.hasVideo = false
    callUpdate.supportsDTMF = true
    callUpdate.supportsHolding = false
    callUpdate.supportsGrouping = false
    callUpdate.supportsUngrouping = false

    self.callKitProvider.reportNewIncomingCall(with: uuid, update: callUpdate) { (error) in
        if let error = error {
            Log.e("Failed to report incoming call successfully: \(error.localizedDescription).")
        } else {
            Log.twilio("Incoming call successfully reported.")
        }
    }
}

private func updateIncomingCall(from: String, uuid: UUID) {
    let callHandle = CXHandle(type: .generic, value: from)
    let callUpdate = CXCallUpdate()
    callUpdate.remoteHandle = callHandle
    self.callKitProvider.reportCall(with: uuid, updated: callUpdate)
}
</code>
}


Remover dados de um arquivo C++

Question: Estou fazendo um banco de dados para armazenar nomes de bandas de rock. Mas não estou conseguindo implementar a remoção de bandas separadamente. Alguém pode ajudar? Segue o código.
<code>#include <iostream>
#include <fstream>

using namespace std;

void banda(){
    ifstream arquivo("layout.txt");
    if(arquivo){
        string bandas;
    while(getline(arquivo,bandas)){
        cout<<bandas<<endl;
    }
    arquivo.close();
    }
    else{
        cout<<"erro";
    }
}

void inserir(){
    ofstream arquivo("bandass.txt", ios::app);
    if(arquivo){
        int a;
        string g;
        int b;
        string c;
        string nome;
        cout<<"nome da banda"<<endl;
        cin>>nome;
        arquivo<<nome<<endl;

        cout<<"genero"<<endl;
        cin>>g;
        arquivo<<"Genero: "<<g<<endl;

        cout<<"ano de criacao"<<endl;
        cin>>a;
        arquivo<<"Ano de criacao: "<<a<<endl;

        cout<<"ano de encerramento"<<endl;
        cin>>b;
        arquivo<<"Ano de enceramento: "<<b<<endl;

        cout<<"descrição"<<endl;
        cin>>c;
        arquivo<<"Descricao: "<<c<<endl;

    arquivo.close();
    }
    else{
        cout<<"erro";
    }
}

void remover(){
    ifstream arquivos("bandas.txt");
    ofstream arquivon("bandas.txt");
    string c;
    cout<<"Digite o nome da banda que deseja remover"<<endl;
    cin>>c;
    string aux;
    if(arquivos and arquivon){
        while (arquivos>>aux){
            if ( aux!= c ){
                arquivon<<aux;
                }
        }
    }
}
void buscar(){

    string a;
    cout<<"Digite o nome da banda desejada"<<endl;
    cin>>a;
    ifstream arquivo("bandass.txt");
    string aux;
    bool x=false;
    if(arquivo){
        while( arquivo>>aux){
            if( aux==a){
                cout<<"Essa banda encontra-se no arquivo"<<endl;
                x=true;
                }
            }
    arquivo.close();
    }
    if( x==false){
        cout<<"Banda nao encontrada no Arquivo."<<endl;
        cout<<"Tenha certeza que escreveu o nome corretamente"<<endl;
        }
}

void exibir(){
    ifstream arquivo("bandass.txt");
    if(arquivo){
        string bandas;
    while(getline(arquivo,bandas)){
        cout<<bandas<<endl;
    }
    arquivo.close();
    }
    else{
        cout<<"erro";
    }
}
int main(int argc, char **argv)
{
    bool n=false;
    char x;

    while( n==false){

        banda(); //cabeçario

        cout<<"Inserir uma letra"<<endl;

        cin>>x; //opção escolhida

        if( x=='i' or x=='I'){
            inserir();

            char u;
            cout<<"Deseja retornar ao menu? Se nao, pressione a letra n, caso contrario letra s"<<endl;
            cin>>u;
            if( u=='n' or u=='N' ){
                n=true;
            }
        }
        else if( x=='r' or x=='R'){
            remover();
        }
        else if( x=='b' or x=='B'){
            buscar();
        }
        else if( x=='e' or x=='E'){
            exibir();
        }
        else if( x=='s' or x=='S'){
            n=true;
        }
        else{
            cout<<"Foi inserido uma letra nao existente no menu. Deseja continuar? Se nao, pressione a letra n, caso contrario aperte qualquer letra"<<endl;
            char y;
            cin>>y;
            if( y=='n' or y=='N'){
                n=true;
            }
        }
    }

    return 0;
}
</code>

Não dá erro, ele apenas não está removendo os dados do arquivo. No caso as bandas cadastradas
Comment: Qual o problema que o código apresenta ? Dá erro ? Se sim qual ?
Comment: Não dá erro, ele apenas não está removendo os dados do arquivo. No caso as bandas cadastradas
Comment: Eu não testei o seu código no entanto tenho pelo menos duas coisas a dizer. Você está sempre a mexer como tudo direto no arquivo, e isso regra geral não é boa ideia pelos mais variados motivos. Melhor é ler tudo para memoria, fazer todas as manipulações que pretende em memoria e quando é necessário grava para arquivo. Isto simplifica bastante em coisas como alterar 1 registo apenas. Outro ponto que tem errado no seu código é que na função `remover` você abre o mesmo arquivo para leitura e escrita simultaneamente. Isso é errado e não irá funcionar corretamente.
Answer: Olá Rafael seja bem vindo.
Uma solução para o seu problema seria você copiar tudo em um novo arquivo .txt menos a linha/banda que você quer tirar, então deletar o .txt antigo e renomear o .txt novo para o nome do antigo.
Diga-se de passagem que essa solução não se aplica só em C/C++/C# - ao se tratar de arquivos texto/fichários em .txt, em qualquer linguagem, a única forma de criar alterações é escrever um arquivo novo.
Outra solução seria colocar os dados numa base SQL, onde cada registro pode ser atualizado/removido de forma independente.
Segue um exemplo de codigo para deletar algo de um txt:
Eliminar linha de um arquivo em C
Apagar linha específica de um arquivo de texto

Remover dados de um arquivo C++


Listagem automática PDO e MYSQL

Question: Boa tarde. Estou tentando fazer com que as tabelas sejam listadas automáticas, sem eu ter que por o nome do campo da mesma. Porém está apresentando erros.
$conn = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$result = $conn->query("SHOW TABLES");

                while ($row = $result->fetch(PDO::FETCH_NUM)){

                    $table = $conn->query("SHOW FULL COLUMNS FROM ".$row[0]);
                    $busca = $conn->query("SELECT * FROM ".$row[0]);
                    $rows = '';
                    echo '
';

                    while ($res = $table->fetch(PDO::FETCH_NUM)){
                        echo $res[0].'
';

                        while ($resS = $busca->fetch(PDO::FETCH_ASSOC)){
                            $rows = $res[0] .' - '. $resS[$res[0]].'
';
                            echo $rows;
                        }
                    }

                }

$res[0] está listando certo o nome dos campos:
idCliente
cliente_Nome
cliente_Cpf
cliente_Endereco
cliente_Numero
cliente_Bairro
cliente_Cidade
cliente_Estado

Porém quando tento usar os dados de cada tabela, retornados pelo $resS, não apresenta os valores inseridos, ou quando apresenta fica somente o id ou duplicados.
Answer: José, consegui fazer algo aqui.
Pelo que entendi, faltou percorrer os dados no $resS.
Veja o código que fiz abaixo e veja se lhe atende:
$result = $conn->query("SHOW TABLES");

while ($row = $result->fetch(PDO::FETCH_NUM)){
    $table = $conn->query("SHOW FULL COLUMNS FROM " . $row[0]);
    $busca = $conn->query("SELECT * FROM " . $row[0]);
    $rows = '';

    while($res = $table->fetch(PDO::FETCH_NUM)){
       while ($resS = $busca->fetch(PDO::FETCH_ASSOC)){
          foreach ($resS as $chv => $vlr){
             echo $chv . ' - ' . $vlr . '
';
          }
       }
    }
}

Comment: Deu certo amigo. Isso tudo que estou fazendo é para tentar verificar dois bancos de dados e após a comparação fazer uma sincronização. Tens uma base além disso para eu seguir?
Comment: Vou tentar, pois tem um cliente que quer meu sistema tanto local quanto web. Dai não achei nenhum biblioteca que faça essa sincronização. To meio que desesperado. Já tentei por mysqldump, porém não deu certo. Se soubre de algo, pff. Ficaria eternamente grato!! Vlw desde já.
Comment: Sim, eu tinha feito assim, os dois acessavam o web, porém o cliente tem medo de que se faltar internet e tal.
Comment: Olha, se eu fosse fazer algo parecido, eu iria ler os registros de um banco e pegar alguns campos-chave para ver se esses campos existem no outro banco. Por exemplo em um cadastro de clientes, eu pegaria o campo CPF para fazer essa comparação. Se não existir, gravar lá. Acredito que alguém com mais experiência já tenha passado por isso.
Comment: Só uma coisa, Luis, se a solução lhe atendeu, por favor, marque a resposta como Resolvida. Obrigado!
Comment: Abra uma pergunta sobre isso aqui, Luis. Tem muita gente experiente que provavelmente pode te ajudar. Sincronização de banco de dados é algo interessante. Porém, será que após o fim da sincronização, seria mais adequado ambos os sistemas acessar apenas um banco?
Comment: Entendi... uma sugestão (sou leigo...) que eu dou seria a cada gravação local e na web, se der problema na gravação da web cria algum "flag", alguma coisa falando que deverá ser feita a sincronização e daí deixaria um serviço a ser executado de madrugada, por exemplo, para realizar essa sincronização caso o "flag" estiver criado. Aí estaria garantindo que sempre que der algum problema, em um certo momento irá entrar a sincronização.
Comment: Ta ok. Obrigado. Vamos tentar.

Listagem automática PDO e MYSQL


Timeout pattern on task-based asynchronous method in C#

Question: As far as I know, there're two possible patterns to implement a timeout to task-based asynchronous methods:
Built-in timeout
public Task DoStuffAsync(TimeSpan timeout)

This approach is harder to implement because it's not easy to implement a global timeout for the entire call stack. For example, a Web API controller receives an HTTP request and it calls DoStuffAsync, and the caller wants a global timeout of 3 seconds.
That is, each inner async method call will need to receive the subtract of already used time...
No built-in timeout
public Task DoStuffAsync(CancellationToken cancellationToken)

..........

CancellationTokenSource cancellationSource = new CancellationTokenSource();
Task timeoutTask = Task.Delay(3000);

if(await Task.WhenAny(DoStuffAsync(cancellationTokenSource), timeoutTask) == timeoutTask)
{
     cancellationSource.Cancel();

     throw new TimeoutException();
}

This seems to be the most reliable and easy to implement pattern. The first caller defines a global timeout, and if it time outs, all pending operations will be cancelled. Also, it provides a cancellation token to the immediate caller and inner calls will share the same cancellation token reference. Thus, if the top caller time outs, it will be able to cancel any working thread.
The whole question
Is there any pattern that I'm missing or, am I in the right way if I develop APIs using the no built-in timeout?
Comment: Some official guidance: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time
Answer: While you can reuse WithCancellation for both cancellations and timeouts I think it's an overkill for what you need.
A simpler and clearer solution for an async operation timeout would be to await both the actual operation and a timeout task using Task.WhenAny. If the timeout task completes first, you got yourself a timeout. Otherwise, the operation completed successfully:
public static async Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout)
{
    if (task == await Task.WhenAny(task, Task.Delay(timeout)))
    {
        return await task;
    }
    throw new TimeoutException();
}

Usage:
try
{
    await DoStuffAsync().WithTimeout(TimeSpan.FromSeconds(5));
}
catch (TimeoutException)
{
    // Handle timeout.
}

If you prefer to not throw an exception (as I do) it's even simpler, just return the default value:
public static Task<TResult> WithTimeout<TResult>(this Task<TResult> task, TimeSpan timeout)
{
    var timeoutTask = Task.Delay(timeout).ContinueWith(_ => default(TResult), TaskContinuationOptions.ExecuteSynchronously);
    return Task.WhenAny(task, timeoutTask).Unwrap();
}

Comment: @MatíasFidemraizer Using an exception is the way the .Net library operates. It also throws when there's cancellation. I do prefer to avoid these exceptions but instead of a tuple I return the default value (added to the answer). Another option would by to use the `TryX(out result)` paradigm.
Comment: @cd491415 what do you mean implement? You have your own `NetworkStream`? The one is .NET doesn't override `WriteAsync`/`ReadAsync`, so you get the `Stream` implementation that only looks at the `CancellationToken` if it's cancelled before the operation starts. So, these operations aren't really cancellable.
Comment: Hey. Actually this is what I was doing before I asked the question without a generalization like your extension method, but you're right that mostly this should work. BTW I'm not sure if controlling flow with exception is a good idea. I wouldn't do that. I would return a tuple with a boolean to specify if the operation was completed or not
Comment: @i3arnon any place where this is explaining how to implement NetworkStream's ReadAsync and WriteAsync cancellation.  I am getting no where, keeps deadlocking on me all the time as per this post https://stackoverflow.com/questions/54816114/c-sharp-setting-writetimeout-readtimeout-on-network-stream-makes-no-difference
Comment: @i3arnon No, I am talking about NetworkStream from .NET.  I am trying to figure out how to properly use WriteAsync and ReadAsync as I cannot use networking on main thread in Xamarin.Forms.  So, I have to use WriteAsync to get info to remote and then if there is response, use ReadAsync to read response I got back.
Comment: Could anyone provide code explaining how to implement timeout cancellation when using NetworkStream and TcpClient in a method that would (a) call TcpClient.Connect(ipAddress, Port), (b) would call NetworkStream.WriteAsync() to send some data to an ip / port, and (c) call ReadAsync() to read response so that all 3 of these have a timeout set on them.  So, if either of (a), (b), (c) fails within 3 seconds an OpCancelledException is handled.  If any other exception it is also handled.  If no exception, the response is processed.  And all objects are disposed properly.  MS docs dont show this
Comment: @cd491415 https://devblogs.microsoft.com/pfxteam/how-do-i-cancel-non-cancelable-async-operations/
Answer:
Is there any pattern that I'm missing or, am I in the right way if I develop APIs using the no built-in timeout?

Disclaimer:
When we talk about a Task in a cancelled state, we mean that we cancel the operation as it proceeds. This might not be the case here when we talk about cancellation, as we simply discard the task if it completed after the specified interval. This is discussed to extent in Stephan Toubs article below as to why the BCL does not provide OOTB features of cancelling an ongoing operation.

The common approach i see nowadays is the no build-in approach and the one i find myself using mostly to implement a cancelling mechanism. It is definitely the easier of the two, leaving the highest frame to be in charge of cancellation while passing the inner frames the cancellation token. If you find yourself repeating this pattern, you can use the known WithCancellation extension method:
public static async Task<T> WithCancellation<T>(
    this Task<T> task, CancellationToken cancellationToken)
{
    var cancellationCompletionSource = new TaskCompletionSource<bool>();

    using (cancellationToken.Register(() => cancellationCompletionSource.TrySetResult(true)))
    {
        if (task != await Task.WhenAny(task, cancellationCompletionSource.Task))
        {
            throw new OperationCanceledException(cancellationToken);
        }
    }

    return await task;
}

This is from Stephen Toub's How do I cancel non-cancelable async operations? which isn't exactly spot on to what you're asking, but is definitely worth a read.
The Task Cancellation docs go on to specify two ways of task cancellation:

You can terminate the operation by using one of these options:

By simply returning from the delegate. In many scenarios this is sufficient; however, a task instance that is canceled in this way transitions to the TaskStatus.RanToCompletion state, not to the TaskStatus.Canceled state.

By throwing a OperationCanceledException and passing it the token on which cancellation was requested. The preferred way to do this is to use the ThrowIfCancellationRequested method. A task that is canceled in this way transitions to the Canceled state, which the calling code can use to verify that the task responded to its cancellation request

Edit
As for you concern with using a TimeSpan to specify the desired interval, use the overload of CancellationTokenSource constructor which takes a TimeSpan parameter:
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));

var task = Task.Run(() => DoStuff()).WithCancellation(cts.Token);

Comment: This works, though "cancellation" implies that the operation did not (and will not) complete, which is not necessarily true with this code. To quote [Toub](http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx), this is *not* included in the BCL "out of concern that it would become a crutch too quickly used without thinking through the ramifications, which are subtle."
Comment: I think the OP understands the semantics of "cancellation" being talked about here. Though ill edit my answer to make that clear.
Comment: Is there a way to achieve this for multiple tasks (using `Task.WhenAll`)? I have tried it but throwing the exception from one task caused the other tasks to be aborted as well. PS - I need to use `await` rather than `Task.Run` since I need the `HttpContext` in the tasks.
Comment: @YuvalItzchakov Does Stephen's Taub article you provided above and written in 2012 (https://blogs.msdn.microsoft.com/pfxteam/2012/10/05/how-do-i-cancel-non-cancelable-async-operations/) really applies still today in 2019?  Don't we have a better way now or?  Sorry just asking because I am reading about lots of complain when using NetworkStream's ReadAsync and WriteAsync and lots of complains are from that time plust Microsoft documentation on this sucks
Comment: The token does not pass into `DoStuff`.So the inner call does not actually cancel?


AppEngine: sending email to admin, billed as "Recipients Emailed" instead of "Admins Emailed"

Question: My apps uses email to notify me about important events. It's doing so (using Python runtime) by sending email to my email address -- marked as owner of the app.
The free tier allows 100 emails per day to receipients, but 5,000 to admins. I expected these notification emails to be billed as "admin" emails.
Am I missing something?
Answer: Did you use the mail.send_mail_to_admins() method?
https://developers.google.com/appengine/docs/python/mail/functions
Comment: Thanks. No, I missed that one. I *did* actually expect to find something like that (that treats email-to-admin as a special case), but I only looked at the Mail->Overview page.


CNAME and TXT record for same subdomain not working

Question: I need to add a TXT record for the subdomain test.domain.com in the zone file. In this zone file there is an existing CNAME for the same subdomain. The two records looking like this:
test IN CNAME asdf.someotherdomain.com.
test IN TXT "Some text i need to add"

But when I try to save this I get an error:
dns_master_load: :45: test.domain.com: CNAME and other data
zone domain.com/IN: loading from master file  failed: CNAME and other data
zone domain.com/IN: not loaded due to errors.
status: FAIL

It works if I do it with different subdomains, for example:
test IN CNAME asdf.someotherdomain.com.
testing IN TXT "Some text i need to add"

I'm not exactly the best there is when it comes to DNS. Is it not possible to have the same subdomain in this scenario? Or am I missing something?
The servers are running bind.
Answer: The problem you're having is an issue with the rules of DNS, which forbid a CNAME record where another record exists.

If a CNAME RR is present at a node, no other data should be
present; this ensures that the data for a canonical name and its aliases
cannot be different.  This rule also insures that a cached CNAME can be
used without checking with an authoritative server for other RR types.
Comment: Hi and thanks for your answer. Yeah that seems to it. That RFC could be a good thing to read.


about publish() method in NetStream AS3

Question: Can i use publish method to record flv file with streaming servers other than Flash Media Server, or it is just meant for FMS? How about crtmp server?
Answer: Yes you can! RED5 or Wowza may record a published stream.
Answer: crtmp (or rtmpd) server can definitely be used too, as long as this error doesn't bother you.

about publish() method in NetStream AS3


Nginx with php7.1-fpm showing blank php pages

Question: Background & Environment
I am attempting to deploy a Nginx server with PHP7.1-FPM, following the instructions here and here:

The server is Ubuntu 16.04
Nginx version is 1.13.3
PHP version is
PHP 7.1.9-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Sep  2 2017 05:56:43) ( NTS )

I am fairly new to all this, so compared to a seasoned linux admin, I am still somewhat ignorant of what's what, but I know enough to handle the basics.
The Issue
When I browse to a URL with as inspired01.DOMAIN.com/application/ I get a blank page. There is no entry in the nginx error log.
When I browse to a URL such as inspired01.DOMAIN.com/application/index.php I get a 404 error.
Tried so far
I have attempted the suggestions in the stackoverflow post here. As far as I could tell, my configuration already has the suggested entries that people are saying fixed this problem for them.
I was not able to resolve the issue with those answers. As that post is a few years old, I am thinking perhaps requirements have changed since then.
My Nginx configuration
My nginx.conf is:
user inspired786;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 1024;
    multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 25;
    types_hash_max_size 2048;
    server_tokens off;
    client_max_body_size 64m;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;
    gzip_disable "msie6";

    gzip_proxied any;
    gzip_comp_level 2;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # Virtual Host Configs

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 444;
    }
}

The site's conf file is:
server {
    listen 80;
    listen [::]:80;

    server_name inspired01.DOMAIN.com;

    access_log /home/inspired786/DOMAIN.com/logs/access.log;
    error_log /home/inspired786/DOMAIN.com/logs/error.log;

    root /home/inspired786/DOMAIN.com/public/;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php7.1-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Logs
No entry is generated in the Nginx server or site log.
No relevant entry is recorded to the FPM log at /var/log/php7.1-fpm.log
Question
I would like to know if there is anything obvious missing or wrong in this configuration, which would potentially result in php files not being parsed.
UPDATE
As per comment below, pasting here so anyone new sees it:

I enabled debug_connection and went through the masses of log output
  that produced. As far as I could tell, there were no issues being
  reported. Well, no obvious errors or warnings. So I created a
  basic hello.php file including a basic echo command, and also
  phpinfo. The file worked fine. So I suspect the issue is something
  else. Continuing to investigate.

Consider this question on hold for now, whilst I look into some other possibilities for the blank pages issue.
Comment: Look in the FPM logs and/or at least the nginx logs
Comment: There's nothing related showing up in the logs. I've updated the question to clarify this (re Nginx log) and added info re FPM log.
Comment: http://nginx.org/en/docs/ngx_core_module.html#debug_connection
Comment: I enabled `debug_connection` and went through the masses of log output that produced. As far as I could tell, there were no issues being reported. Well, no obvious `errors` or `warnings`. So I created a basic `hello.php` file including a basic echo command, and also phpinfo. The file worked fine. So I suspect the issue is something else. Continuing to investigate.
Comment: Blank page is often a PHP error. PHP errors can be logged to `nginx` (it used to be the default on some platforms), but `phpinfo` should tell you what your `error_log` settings are. You probably need to log PHP errors to get to the bottom of this problem.
Comment: Thanks guys. Digging around, I've solved the issue. After setting up the VM I migrated a root folder from another server. It included a Wordpress installation, and numerous other PHP applications. It looks like the issue was not server related, but simply the various applications (including WP) having issues in the new environment. I've managed to iron most of them out.   HOW DO I MARK A QUESTION AS SOLVED when there's really no answer, per se?
Answer: I run on Linux 2.6, PHP5 and nginx
my PHP file was shown as text
After many test i change the default file in
C:\username\etc\nginx\sites-enabled
as follow:
location ~ [^/]\.php(/|$) {
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  include fastcgi_params;
  # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  # With php5-cgi alone:
  fastcgi_pass 127.0.0.1:9000;
  # With php5-fpm:
  #fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_index index.php;
  fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

After restart of nginx and PHP services PHP started working!
Check also if yours php files are under root path set in the default file
and begin tests with a test.php file as follow:
<?php
/* test.php */
  phpinfo();
?>

Answer: Try to fix permissions in your project directory. In Linux this worked for me:
sudo chown -R www-data:www-data .


definition of chi-square statistic

Question: The chi-squared statistic is defined as
\begin{equation}
\chi^{2} = \sum_{i=1}^{N} \frac{(O_{i} - E_{i})^{2}}{E_{i}}
\end{equation}
The $O_{i}$ is observed value and $E_{i}$ is expected value.
But it seems that sometimes the statistic is defined differently as
\begin{equation}
\chi^{2} = \sum_{i=1}^{N} \frac{(O_{i} - E_{i})^{2}}{{\sigma_{i}}^{2}}
\end{equation}
The $\sigma_{i}^{2}$ is variance. I found this definition in this Wikipedia page for reduced chi-square
Are both of them called "chi-squared statistic"? When do you need the former and when do you need the latter?
Comment: Both are chi-squared statistics.  It is important for readers to consult that Wikipedia page on "reduced chi-square" because it uses nonstandard notation: "$\sigma_i^2$" is an (unbiased) *estimate* of variance, not a model parameter.
Comment: As currently posted, neither is a chi-squared statistic. numerator needs to be squared.
Comment: @BruceET I'm sorry that I missed it. The formulas are corrected now.
Answer: To my understanding there are different types of chi-squared statistic. You can use the first formula to calculate the chi-squared test statistic as in Pearson's test independence while the second formula is applied in goodness of fit statistic tests. So it depends on the situation what formula you use.
Comment: In light of the edit that was made to the question, this answer is not correct: it will help to read the referenced Wikipedia article, which makes it clear the second statistic is the one that appears in goodness-of-fit tests.
Comment: Thank you. I adjusted the answer to the edit in the question.
Answer: The latter definition is the general definition of the chi-square statistic. The former definition is for a special case where the parameter $\theta$ is Poisson distributed. Note that in a Poisson distribution expected value is the same as variance.

definition of chi-square statistic


Undefined Element Returned From Array in React

Question: I have a class component which  makes an async call before render() and stores the result into its state. The async call is called before render with componentWillMount() which uses this.renderData(). The async response returns an array of arrays but in this case I am only interested in the first array. So I store the result collections.first into the state arrayData. I can successfully console.log the state arrayData which shows 8 elements (see screenshow). However, when I try to access an element with an index using Array.at(index) or Array[index] I get an undefined error.
How do I properly retrieve the index? The overall goal is to retrieve a value from the result and display an image in the render function  / But Im unsure why Undefined is happening.
Here is what I have so far:
class Gallery extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      arrayData: null,
    };
  }

  renderData = async () => {
      // async request code here which sets fetchURL and requestOptions
      const collections = await fetch(fetchURL, requestOptions).then((data) =>
        data.json()
      );
      if (collections ) {
        this.setState({ arrayData: collections.first });
      }
    }
  };

  componentWillMount() {
    this.renderData ();
  }

  render() {

     console.log(this.state.arrayData); // correctly outputs array of length 8 (see output below)
     console.log(this.state.arrayData[2]); // undefined error
     console.log(this.state.arrayData.at(2); // undefined error

     return(
         // some render code
           // cant retrieve
    );
  }
}

Array output from response shows 8 items fine when logging as this.state.arrayData

Error Code when logging with console.log(this.state.arrayData[2]);
react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of null (reading '2')
    at Gallery.render (Gallery.jsx:61:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25850:1)
    at performSyncWorkOnRoot (react-dom.development.js:26096:1)

Error Code when logging with console.log(this.state.arrayData.at(2));
Uncaught TypeError: Cannot read properties of null (reading 'at')
    at Gallery.render (Gallery.jsx:61:1)
    at finishClassComponent (react-dom.development.js:19752:1)
    at updateClassComponent (react-dom.development.js:19698:1)
    at beginWork (react-dom.development.js:21611:1)
    at beginWork$1 (react-dom.development.js:27426:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)
    at renderRootSync (react-dom.development.js:26434:1)
    at recoverFromConcurrentError (react-dom.development.js:25850:1)
    at performSyncWorkOnRoot (react-dom.development.js:26096:1)

Answer: I will explain what is happening here :
In the first time when you render the component the this.state.arrayData it's undefined , and after the data it's fetched from the server the component render again and you can see the result of the responce in your console , but when you try to access the the array at index 2 and the data is undefined you will get this error .
So the solution it's easy check if the this.state.arrayData it's true then display the component else make a loading component .
  render() {
    if (!this.state.arrayData) {
        return
...Loading

    }
     return(
         // some render code
           // cant
      retrieve
    );
  }

Comment: Ah, it makes perfect sense to check the state of the data from the request because it is async. Thank you!


Does GarageBand have an oscillator and where do I find it?

Question: Does GarageBand have an oscillator/waveform generator like other DAWs such as FL Studio or Cubase?
I'm basically trying to create my own waveforms (to create bass, pads, chords, etc) from scracth, which you usually do using subtractive synthesis (e.g. with an oscillator).
I can't believe GarageBand would lack this key feature, so I'm pretty sure it's just sitting there somewhere waiting for me to find it.
Edit:
Platform: GarageBand for Mac (macOS 12.1 Monterey)
Note: The "Alchemy Synth" version of GarageBand for Mac lacks the Synth/waveform generator feature (which is the exact feature i'm looking for); it just allows you to apply presets to existing sounds
Here are some examples from other DAWs of what I'm looking for:
Cubase 3x Oscillator:

FL Studio 3x Oscillator:
Comment: There are 3rd party plugins that would let you do subtractive synthesis in garageband, is that a solution you'd consider?
Comment: Thanks, I would certainly consider it as there seems to be no built-in solution to this day. Any free plugins for GarageBand/macOS you would recommend?
Answer: You can use third-party plugins in Garageband, as long as they are in the Audio Unit (AU) format.  Unfortunately I can't personally recommend a plugin here, since the ones I use are VST only, but I do know that Helm is pretty popular, and it looks like it covers your needs.  It gives you three oscillators (osc1, osc2, sub) and a variety of ways to modulate the sound.
Comment: Thanks, this is exactly what I was looking for. Helm looks great. I'm currently trying to install it as a GarageBand plugin in Audio Unit format but that is a different question. Thanks!


Working with few data examples

Question: I have been asked often in some interview, that how we should proceed when we have less data examples(say 50 or 100). What considerations needs to be made while choosing any algorithm.
few points that came into my mind
1.check if the algorithm is flexible(SVM, kNN) and so avoid them as they would over fit the data easily. naïve bayes seems to be a nice choice as it would be more robust even when the data has some noise.
2.Use of regularization
3.Use of PCA or SVD perhaps to reduce the multicollinearity.
any other things to be considered?
Comment: I disagree with your first point. If regularized properly, flexible models are certainly usable on small data sets.
Comment: @MarcClaesen thanks. are there any other points i am missing?
Answer: I'd add

look for a model that fits as closely as possible to the application and data generation process
I work with data from physico-chemical measurements, and there we have certain ideas how the data should behave (for physical and chemical reasons).

E.g. for my measurements/applications it often makes sense that the data can approximately be described by linear changes in not-too-large numbers of chemical species. This would fit well with a PLS or PCA regularization.
Also, the physical nature of the spectra together with the settings of the measurements typically mean that in the end, coefficients for neighbour variates should be correlated (smooth). This agrees better with, say a ridge (or PCA or PLS) regularization than with LASSO.
LASSO would agree better with, say, the situation in gene microarray studies where you expect few informative variates among lots of noise-only channels, and where no relation between neighbour tests on the microarray is expected.

If the number of cases is small, testing/validation/proving the performance of the obtained model can become the more difficult part compared to training: For training you can restrict the model complexity/regularize according to what you can afford with the given number of cases (and you can be lucky and face an easy problem), but testing depends on the absolute number of test cases (as the model is treated like a black box).

One conclusion from that is that with too few cases, data-driven optimization (if you cannot measure the performance well, model comparison may become meaningless) may not work at all.
To cope with that, you could choose a model where hyperparameters can be fixed by external knowledge
E.g. the number of PLS or PCA components may be guesstimated from expectations about the number of chemical species that I expect to play a role.

The typical problem with too complex models wrt. the available training sample size is instability.

So measure the (in)stability of the model and/or its predictions
And consider model aggregation (e.g. bagging) if stability turns out to be a problem.

Working with few data examples


Is every permutation group isomorphic to a 'familiar' group?

Question: This may be a very simple question, but I do not know how to approach it.
Cayley's theorem states that every group G is isomorphic to a subgroup of the symmetric group acting on G (in other words, isomorphic to a permutation group, a permutation group just being a subgroup of a symmetric group).
What I am curious about is:

Is every permutation group isomorphic to some 'familiar' group?

(Feel free to read as "finite permutation group" if it makes a difference.)
What I mean by a 'familiar' group is a group that isn't typically viewed as a group of permutations, such as cyclic groups, dihedral groups, groups of matrices like the general linear group, etc.  Phrased another way, is there a 'nice' description of every permutation group in terms of common groups and not depending on a presentation with generators and relations or reference to the object that the permutation groups acts on?
It seems there should be some hope for this, since a fundamental notion of groups is that they describe symmetries.  But perhaps this does not mean that every permutation group is a 'nice enough' or 'interesting enough' permutation that it receives a nice name to go by.
I really hope my question is clear, even if the language may not be the best with which to describe what I'm after.
What I have so far is that if our permutation group is abelian, it seems it should be easy to classify it by the fundamental theorem of finitely generated abelian groups, thus providing an answer in that case.
In addition, some subgroups of symmetric groups are recognized as familiar groups, as shown here.
Thanks in advance for the input.
EDIT: What I want to know, if this is any better (and maybe I should have stated it this way in the first place), is just if there are any permutation groups for which the sole, or by far best, description is as a group of permutations, instead of in terms of any kind of combination of groups that do have a description not in terms of the set of permutations on some object.
Comment: Look up the classification of finite simple groups. There are some very strange cases even when dealing with just finite simple groups. http://en.wikipedia.org/wiki/Classification_of_finite_simple_groups
Comment: Despite the fact there are many diverse opinions as to which groups are familiar, I think the answer to your question is a clear no - not all finite groups are familiar!
Comment: Also, given that every group is isomorphic to a permutation group, as you've already shown, why do you continue to distinguish between groups which are "permutation groups" in your question?
Comment: By Cayley's theorem, every group is a permutation group. So why are you using the phrase "permutation group" instead of "group"?
Comment: (I only ask that question for clarity - it feels like maybe you mean something more than just a subgroup of a full symmetric group.)
Comment: Yes, they have a name: symmetric groups $S_n$
Comment: Please see the edit above.
Comment: "...groups for which the sole, or by far best, description is as a group of permutations...." Different descriptions are appropriate for different purposes. What purpose is "best" describing here?
Answer: It's pretty hard to answer this question when 'familiar' isn't defined further.
Every finite group (and thus every permutation group) has a composition series, which is unique in the sense that the length and composition factors of any two composition series are the same up to permutation and isomorphism.  If you define familiar groups to be simple groups, then these quotients are the familiar pieces you're looking for.
Defining familiar as simple is a stretch, though.  You'd be hard pressed to find someone who found the Held group especially recognizable.
The other problem is that two nonisomorphic groups can have the same composition factors.  The factors do help you break the group into smaller, more recongizable chunks, but they don't tell you how those chunks interact.
There are so many variations on combinations of smaller groups that it is difficult to imagine how we could recognize them all without group presentations.  Another way of breaking down a group into recognizable groups is by looking at its Sylow subgroups and seeing how they interact (this is local group theory).  But for this, we need to understand $p$-groups enough to call them recognizable. My answer to this question should give you an idea of the magnitude of what we're dealing with just in the world of $p$-groups.
Take for example $\text{SmallGroup}(16,3)$.  There is no other name for that group, as far as I know.  It is isomorphic to $(\mathbb{Z}_4\times\mathbb{Z}_2)\rtimes \mathbb{Z}_2$, which shows us it can be split into those recognizable pieces.  This decomposition uses semidirect products, however, which is basically the same as the relations / presentation concept we are trying to avoid.
So in summary, there are many a lot of different ways to divide a group up into pieces that are as familiar as possible, to gain understanding about it and how it works.  However, to achieve a full description of the group, most of the time we need to use specific relations in a group presentation to show the way those pieces fit together.
Answer: Just looking at finite simple groups, the classification is fairly complex, and I doubt you'd call all of the examples, "familiar."
In particular, the odd examples are the so-called Sporadic Groups. These are a $26$ specific finite groups that do not fit into broad infinite classes. Indeed, some of them were initially discovered during the attempt to classify the finite simple groups - they were not initially found in terms of the groups of symmetries of any mathematical object.
One of the stranger results is that almost all groups of order less than 2000 have order 1024. There are $49,487,365,422$ distinct groups of order $1024$. That is more than 99% of the distinct groups of order less than 2000.  Certainly, some of these must not be "familiar."
Comment: I find it strange that people are mentioning the finite simple groups. I would have rated all of them among the most familiar groups around, but that just indicates that familiarity is a personal concept. On the other hand, there are vast numbers of virtually indistinguishable $p$-groups, and I don't think of them as being familiar.
Comment: @DerekHolt I was basing my interpretation or "familiar" on the presumed level of the poster. The fact that the most primitive finite groups includes such strange exceptional cases is a strong hint that non-commutative groups are a much hairier thing than the commutative case.


Finding the equation of a function

Question:
Find the function $y=f(x)$ whose graph is the curve $C$ passing through the point $(2,1)$ and satisfying the following property: each point $(x,y)$ of $C$ is the midpoint of $L(x,y)$ where $L(x,y)$ denotes the segment of the tangent line to $C$ at $(x,y)$ which lies in the first quadrant.

Okay, so with $(2,1)$ being the midpoint of the line segment $L(2,1)$, we have that the $L(2,1)$ must lie on the line $y=2-x/2$. This gives us that that slope of $C$ at $(2,1)$ is $-\frac{1}{2}$. Now I'm not really sure where to go from here.
Comment: You should have mentioned about x- y- coordinate axes and intercept or segment, to be clearer. It took me some time to figure out what you meant, so I made a sketch also.
Answer: At any point of your curve you have information about the slope of the curve at your point. This means that you have to solve a differential equation.
Suppose $(x_0,y_0) \in C$ is a point of your curve. Then (I skip boring computations) you have that the slope of the curve at $x_0$ is
$$f'(x_0)=-\frac{y_0}{x_0}$$
so you have to solve the Cauchy problem
$$\left\{ \begin{matrix}
y'=-\frac{y}{x} \\
y(2)=1
\end{matrix} \right.$$
with constraints $y >0, x>0$.
The solution is $f(x)=\frac{2}{x}$
EDIT: How did I find $f'(x_0)=-\frac{y_0}{x_0}$? Here I show my boring (actually there is nothing smart in here) computations.
Let $m= f'(x_0)$. The line $L$ passing through $(x_0,y_0)$ of slope $m$ has equation
$$L: \ \ y-y_0=m(x-x_0)$$
Intersecting $L$ with the $x$ axis we get the point $(-\frac{y_0}{m}+x_0, 0)$.
Intersecting $L$ with the $y$ axis we get the point $(0, y_0-mx_0)$.
So we get the conditions
$$\left\{\begin{matrix}2x_0 = -\frac{y_0}{m}+x_0 \\
2y_0 = y_0-mx_0\end{matrix}\right.$$
which are equivalent to $m= -\frac{y_0}{x_0}$.
Comment: @lamyvista   It is not clear what you want. Tangent at point T of C, cuts the co-ordinate axes at points A and B with AT=TB, is it so? This is trivially true for all curves through the origin.
Comment: @Narasimham what do you mean by AT=TB?
Comment: I introduced the symbols as I could not understand. AB is segment intercepted by x- and y- axes. T is the middle point of AB. T is also point of tangency. It is better if you show in a sketch.
Comment: @ Crostul where did you use (2,1)  being midpoint of L ?
Comment: @Narasimham Using the fact that POints of the curva are midpoints I got $y'=-y/x$. Using $(2,1) \in C$ I got $y(2)=1$. Then I solved the Cauchy problem.
Comment: @Crostul I can justify the slope at x0 being -y0/x0 via an argument using similar triangles like Narasimham, but is there another way to see why this is true?
Answer: From the bisecting similar triangles shown
slope of ATB is $ - y^{'}$
$ AT = TB, OS = SB $
$$ x = u = \dfrac {-y}{y^{'}} $$
$$ x dy + y dx =0 $$
Integrating
$$ x \ y = const = 2, $$ using given boundary conditions. It is one of the properties of the rectangular hyperbola.
Comment: where is x=u=-y/y' coming from here?
Comment: @lamyvista  $ y/u = \tan TBx = -y^{'}$, and T is mid-point of AB, S is midpoint of OB, x=u.

Finding the equation of a function


Get a most recent update of an RSS feed

Question: I'm using C# but this would apply to any other language out there.  I found a couple of questions on here that stated an RSS feed will only respond with the last 10 documents but that doesn't seem to be the case on the RSS feeds I'm trying to access.
Example code in C#:
rssXmlDoc.Load("http://sampleRSSfeed.com/rss");
foreach (XmlNode rssNode in rssNodes)
{
     // process rssNode...
}

I can pull the pubDate along with all the other fields.
My problem is that I can't find any way to limit the incoming docs based on date/time of the pubDate.  Each call pulls all records which is rather large (hundreds).
Is there a way to request only the documents since the last check?
Answer: Unfortunately, you probably can't rely on pubDate because not all feeds will have correct dates in there, and not all feeds have them sorted in reverse chronological order. If you want the most recent, you'll have to fetch the whole feed and keep track of a unique id for each entry (usually the guid element for RSS) and then pull again the feed after a little time and idenity new content. Another option is to use a service like Superfeedr which handles all this for you.
Comment: I had a feeling about this; thanks for confirming it.

Get a most recent update of an RSS feed


Difference between raising exception and automatically causing an exception

Question: Currently using the wxPython framework and my code looks like this:
Event bind:
self.frequency_grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.on_cell_changed)

Function that handles changed cells:
def on_cell_changed(self, event):
    self.current_grid = event.GetEventObject()
    try:
        new_value= self.get_cell_value()
        if new_value < 0:
            raise AttributeError
        #allow the cell to update
    except AttributeError:
        event.Veto()
        wx.MessageBox(_("Positive values only."), "", wx.OK|wx.ICON_WARNING)
    except:
        wx.MessageBox(_("Invalid value for cell."), "", wx.OK|wx.ICON_WARNING)
        event.Veto()

The function get_cell_value() reads the value from the current cell and converts it to an integer simply by using int(). If the user enters a character like 'a' into the cell, obviously this function fails and the exception is raised. In this case the messagebox comes out telling the user the cell has an invalid value. This is what I call the automatically caused exception, and the final exception block is executed.
In the case of negative values, I manually raise an AttributeError (just wanted to see something different from ValueError which is what happens when user inputs characters).
In this case however, the wxPython sends the EVT_GRID_CELL_CHANGE event twice, so there must be something different about manually raised exceptions.
I've separately raised a ticket about the duplicated events at http://trac.wxwidgets.org/ticket/16333 but just trying to understand how the first scenario doesn't make wxPython send 2 events compared to the second scenario.
Answer: There is no difference in the Exceptions, but you are processing them in a different way, at a different place in the code.
I suspect it's the veto() call that causes the extra event. But why not validate the input in one place only? i.e have your get_cell_value() function should make sure it's an integer >0.
Also, this structure is both a recipe for circular events, and a painfully annoying UI. People should be able to make a typo and go back and correct it without an annoying dialog popping up.
Maybe provide an indicator of a problem, like making the cell background red, but only go the dialog route once the user tries to move on to the next step.
Comment: the veto does not cause the extra event. If I do not use the messagebox, the event is somehow not duplicated. How am I processing the exceptions in a different way? If there is no difference in the Exceptions, then me raising the Exception and the code automatically triggering the Exception from an invalid int() conversion should lead to both exceptions treated similarly. You may be right about the UI design or the validation in 1 place, but my original question is to ask why this particular situation happens in the first place.
Answer: Don't use except: if you really want to catch any possible error(even system memory or anything else non-related).
To make your code look better, I'd suggest to cast value to int with try...except block, then check for negative values.
try:
    value = int(text)
except:
    return MessageBox('Enter digit')
if value < 0:
    return MessageBox('Enter positive digit')

Comment: that's what the try statement there does, it doesn't matter to my original question if I call another function from the try block with the int(text) within that function or directly do the int() within that same try block.
Answer: After a bit more tracing, I found that creating the MessageBox causes the EVT_GRID_CELL_CHANGING event to occur, which then leads to the EVT_GRID_CELL_CHANGED event to occur, which is why I saw duplicated events.
The reason why I did not see duplicated events during the entry of a character was because a Veto() was called in the event handler for the EVT_GRID_CELL_CHANGING if an int() conversion was invalid because my handler for that event gets the grid input and tries to convert it.
In conclusion, there is no difference in Python exception handling, but however, a better wxPython demo should be implemented to prevent the duplicated message box during the demo and show other users how to better use the grid mechanism.


How to get img data (like pixel) from an ajax call?

Question: I have a image here : https://tx3.travian.fr/hero_body.php?uid=446, by using a userscript (with Tampermonkey) I know how to read pixel data but this script runs on the page itself, so it has to be open :
var img = $('img')[0];
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var pixelData = canvas.getContext('2d').getImageData(195, 56, 1, 1).data;

If possible, I want to achieve that from another page of the website, make a get call and manipulate the img, but I only get weird data (unknown encoding or something else) and I don't know how to deal with the result :
$.get(link , function( data ) {
    // test 1
    //let obj = $(data).find('img');

    // test 2
    $$("#content").html('');

    // test 3
    let img = data;

    let canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

    var pixelData = canvas.getContext('2d').getImageData(195, 56, 1, 1).data;
});

The image is well-load, i can see in "preview" tab, and everything is ok here :

But then how to deal with it :

Edit
$.get( link, function( data ) {

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext("2d");

    var image = new Image();
    image.onload = function() {
        ctx.drawImage(this, 0, 0);
    };
    image.src = "data:image/png;base64," + data;   // ERROR GET data:image/png;base64,%EF%B ... F%BD net::ERR_INVALID_URL

});

To try : just open the dev console on the login page https://tx3.travian.fr/ and execute (the img page does not require login) :
$.get("/hero_body.php?uid=446" , function( data ) { console.log(data) });

Comment: Possible duplicate of [Base64 PNG data to HTML5 canvas](https://stackoverflow.com/questions/4409445/base64-png-data-to-html5-canvas)
Comment: @showdev this pointed me to a good direction, I now have an image and I'm able to look pixels, but the image I get does ot fit `GET data:image/png;base64,%EF%B ... F%BD net::ERR_INVALID_URL`
Comment: Sorry, I'm not sure what you mean.
Comment: @showdev I've edit my post and add the code I write and the error linked
Comment: @showdev also, I add a `console.log` into the .onload function but it's never triggered, is that because there is no real element in my DOM ?
Comment: Are you sure that the data is returned as a base64 encoded string? It looks like it might be raw image or blob data.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/182964/discussion-between-azro-and-showdev).
Answer: There is no reason to make an AJAX call to get the image, and as you have seen, making the AJAX call has problems, although it is possible. Just load the image as an image, draw it into a Canvas, and proceed as before.
const link = "https://tx3.travian.fr/hero_body.php?uid=446";

var img = new Image();
img.onload = function() {
    var canvas = document.createElement('canvas');
    canvas.width = this.naturalWidth;
    canvas.height = this.naturalHeight;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(this, 0, 0);
    var pixelData = canvas.getContext('2d').getImageData(200, 200, 1, 1).data;
    console.log('pixelData', pixelData);
}
img.src = link

Note that this is subject to Same Origin Policy limitations, but if you are accessing the image from a page on the same domain, that will not be an issue. (Otherwise you need to have an appropriate CORS policy on the image and set img.crossOrigin = "Anonymous".)
Note to readers: to run the code above while avoiding CORS issues, open the image link in your browser and then run the code in your browser's JavaScript console for that page.
Comment: I'm trying that later and I'll tell you
Comment: @azro The pixel shows up as 0,0,0,0 because the picture is transparent black at the point you chose. I changed the sampling point so you get non-zero data.
Comment: 15h until bounty for you ;)


As there's a "double" bass, is there such a thing as a "single" bass?

Question: The lowest stringed instrument that is typically played in orchestras is sometimes termed a "double bass". Is there a corresponding "single bass"?
Naively, one might think that it would be the cello, but I was under the impression that the cello was a "tenor" instrument, rather than a "bass" one. Then there's the whole stringed instrument family issue (violin vs. viola da gamba vs. ...), which may complicate what a "true" single bass is.
Is there such a thing as a "single bass", and does it (roughly) correspond to any instrument in current widespread use?
Comment: Couple of tenuous ideas why 'double' - doubled the cello parts; played two octaves below middle C, transposes down an octave. Similar question - 'what is double about the double bass?'
Comment: The double bass is the bass of the viola family, not the violin family. The range of viola instruments does include a normal bass, we just don't know it very well because the entire family has gone out of fashion (except for the double bass).
Comment: @KilianFoth - are you mixing up _viola_ with _viol_?  The **_viola_** is a member of the violin family.  [_**The viol /ˈvaɪəl/, viola da gamba_**](https://en.wikipedia.org/wiki/Viol) is indeed something else.  And no, the modern double bass is not a _viola da gamba_ - in spite of its shape. It is a bass violin according to many, or its own family. There are many differences between the double bass and viola da gambas - most significantly, **frets**: [_**Viola da Gamba**_](https://en.wikipedia.org/wiki/Viol#/media/File:GambeUilderks.png). (And we know plenty about  the viola da gamba family.)
Answer: Double Bass does not imply a Single Bass instrument:

but I was under the impression that the cello was a "tenor"
  instrument, rather than a "bass" one.

Perhaps the cello is a tenor instrument in terms of the entire range of instruments, but until the double bass was invented, it was the bass voice relative to the rest of the violin family.
During the Baroque and Classical eras, in quartets and orchestras the cello traditionally played "bass" parts, until Beethoven made a mission of "liberating the cello", by writing more lyrical music for the cello for virtuoso players he knew personally - music that exploited its higher registers.
Still, the origin of the name Double Bass does not seem clear. Here are some ideas:
New World Encyclopedia - Double bass

The instrument's standard English name, double bass, may be derived
  from the fact that it is approximately twice as large as the cello, or
  because the double bass was originally used to double the cello part
  an octave lower.
  It has also been suggested that the name derives from its viol family
  heritage, in that it is tuned lower than the standard bass viola da
  gamba. The name also refers to the fact that the sounding pitch of the
  double bass is an octave below the bass clef. The name contrabass
  comes from the instrument's Italian name, contrabbasso.

IMO, <code>"the sounding pitch of the double bass is an octave below the bass clef"</code> is the best reason offered for calling it the double bass: Its voice is in the 'bass-bass clef' range, although we use the 'single bass' clef to notate its music.
Comment: It sounds an octave lower than the written note in ALL the clefs that it uses (bass clef, tenor clef and treble clef), not just the bass clef.
Answer: The violoncello has never been considered a tenor instrument, it has always been a bass. This question really is about what are considered the four main voices in voice leading, which is what all instrument families are based off of. These are of course based off of the main instrument known to humanity; the human voice. Those would be:

Soprano, with its main octave being from C4 (middle C) to C5.
Alto, ranged from F3 to F4.
Tenor, ranged from C3 to C4
Bass, ranged from F2 to F3

Of course human voices can sing around these single octave limitations, but in practice these tend to be the strongest octaves for each voice. Instruments totally eclipse these ranges, so the most important aspect comes from the timbre. This is why despite having a range that could be considered bass according to this definition, the trombone is considered a tenor instrument. In the case of strings, take a look at the string quartet: violin I as soprano, violin II as alto, viola as tenor, and cello as bass.
When looking at the string section in this way it makes much more sense why the contrabass would be nicknamed "double bass". Not only does it double the bass voice (cello), but it sounds an octave below, being doubly bass-y.


How can I locate a specific file in a directory within a loop?

Question: I'm having trouble pointing to a specific file containing part of the string of another file in another directory.
If you look at the following command, lets say I have a file abc.foo in ./A, I need to apply a function by using abc_extendedname1.jpeg which is in ./B
for file in ./A/*;

do echo $file;
function $file -opt ./B/${file%.foo}_extendedname1.jpeg ./B/${file%.foo}_extendedname2.jpeg;

done

Any help would be greatly appreciated!
Comment: FYI, `function` is a reserved keyword. Saying `my_function` would be clearer.
Comment: so basically you are trying to extract the basename w/o extension: http://stackoverflow.com/questions/2664740/extract-file-basename-without-path-and-extension-in-bash
Answer: for file in ./A/*; do
  basename=${file##*/}
  basename_noext=${basename%.*}
  echo "$file"
  your_function "$file" -out \
    "./B/${basename_noext}_extendedname1.jpeg" \
    "./B/${basename_noext}_extendedname2.jpeg"
done

Comment: You're a life saver! Works beautifully. So I take it my mistake was in using $file without removing the directory info?
Comment: Pretty much, yes. By the way, next time, try using `set -x` within your script (or `bash -x` to start it) to see what your script is doing wrong. (For bigger scripts it's worth also learning how to use `PS4` to include line numbers and such in that trace, but... well, baby steps).
Answer: try
export d="`pwd`"
find ./A/*|while read file
do
    echo "$file"
    if [ -f  "$d/B/${file}_extendedname1.jpeg" ]
    then
        echo "$d/B/${file}_extendedname1.jpeg" found
    fi
done

Comment: Needs more quotes -- right now, this won't correctly handle filenames with spaces.
Comment: ...and backticks are more or less deprecated, use `$(...)` instead
Comment: And it will break if the working directory (not just a filename) contains spaces, and [pipelining into a loop will break as soon as it's called upon to increment a variable (or something else with side effects)](http://mywiki.wooledge.org/BashPitfalls#grep_foo_bar_.7C_while_read_-r.3B_do_.28.28count.2B-.2B-.29.29.3B_done), and the semicolon after the first `echo` is useless and looks like a PHP coder's work, and the `export ` is unnecessary, and `$d` is unnecessary and can be replaced by `.` (making the backquotes unnecessary), and it's lucky that's all I can see because I'm out of characters.
Comment: ...also, using `read` instead of `read -r` means that backspaces inside the filenames are interpreted instead of read literally. And using `find`'s default `-print` behavior means that filenames with newlines in their names won't work right (yup, they're legal on UNIX), and... so forth.


Verificação de base64?

Question: Estou fazendo uma aplicação de emails(HapiJS) e descobri que alguns emails tem o texto dele codificado para base64, porém outros não.
Nessa minha aplicação precisarei receber emails de todos os serviços(Gmail, Hotmail, ...) e preciso fazer um método para verificar se o texto está em base64 ou não, para somente aí encaminhar para decodificação ou direto para o cliente.
Já procurei bastante e até agora não consegui achar nada que funcionasse 100% como eu preciso, e como sou novato em programação, ainda não possuo conhecimento suficiente para descobrir sozinho como fazer isso...
Código que estou usando para tentar verificar:
let base64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;

        let isBase64Valid = base64.test(mail.text); // base64Data is the base64 string

        if (isBase64Valid) {
            // true if base64 formate
            console.log('base64');
        } else {
            // false if not in base64 formate
            console.log('String');
        }

Comment: Isso ajuda? https://stackoverflow.com/questions/8571501/how-to-check-whether-the-string-is-base64-encoded-or-not
Comment: Ajudou bastante, esclareceu muita coisa, mas ainda não resolveu o problema...
Comment: Então talvez seja uma boa hora para [edit] a pergunta e incrementá-la. Você já deve ter testado algum código, então coloque-o na pergunta e indique quais foram os erros ou dificuldades encontradas.
Comment: Usei alguns códigos do link que você me passou eles funcionam mas não corretamente, pois até os emails que estão em base64 ele está identificando como se não estivesse, e vou editar a pergunta e adicionar código nela para esclarecer melhor a dúvida
Comment: Todo o e-mail está em base64 ou somente parte dele?
Comment: O texto dele está em base64 e se tiver alguma imagem ela também é convertida para base64
Answer: Usando javascript a abordagem mais correta de verificar se uma dada {String} foi (está) codificada em base64 no front-end é envelopando em um bloco try\catch o retorno da função atob() em comparação ao próprio retorno encodado visto que, a VM do javascript do navegador já lançará uma exceção no caso de falha.
Alguns exemplos aqui da comunidade StackOverflow (portuguesa, inglesa) dizem que a seguinte abordagem é o mais correto:
function isBase64(str) {
    try {
        return atob(str) ? true : false
    } catch(e) {
        return false
    }
}

Contudo esta abordagem está incorreta visto que o seguinte exemplo retornaria um "falso-positivo":
isBase64('jgjhgj hg') // true

Quando na verdade o retorno do exemplo acima usando atob() seria:
console.log(atob('jgjhgj hg')) // "á8`"

A abordagem front-end mais correta

O correto seria "encodar" a "decodificação" e compara-lá a entrada assim:
function isBase64(str) {
    try {
        return btoa(atob(str)) === str ? true : false
    } catch(e) {
        return false
    }
}

Deste modo refuta-se os casos de "falsos-positivos":
isBase64('jgjhgj hg') // false

No back-end (NodeJs)

Não exitem funções nativas em NodeJS como btoa() ou atob() por isso é muito comum o uso de módulos de terceiros ou o uso de Buffer para se chegar ao mesmo resultado.
É importante ressaltar que nem todas as bibliotecas de terceiros reportam "exceções" ou fazem uma comparação contra a entrada e assim é fácil passar por "falsos-positivos".
O seguinte exemplo utiliza Buffer para encodar e decodificar além de verificar contra a entrada:
function atob(str) {
    return new Buffer(str, 'base64').toString('binary');
}

function btoa(str) {
    let buffer;
    if ( str instanceof Buffer ) {
        buffer = str
    } else {
        buffer = new Buffer(str.toString(), 'binary')
    }
    return buffer.toString('base64')
}

function isBase64(str) {
    try {
         return btoa(atob(str)) === str ? true : false
    } catch(ex) {
        false
    }
}

Testando é possível perceber que não reporta "falsos-positivos":
console.log(isBase64('SGVsbG8gV29ybGQh')) // true

console.log(isBase64('jgjhgj hg')) // false

O uso de RegExp (questão opinativa)

Se não é possível creditar que a entrada (origem) da {String} de fato seja encodada (e por isto a necessidade de verificação) nem sempre o uso de RegExp deve ser entendido como "a melhor opção" o seguinte exemplo expressa esta questão:
function isBase64(str) {
    return /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/.test(str)
}

isBase64('SGVsbG8gV29ybGQh') // true

isBase64('jgjhgj hg') // false

isBase64("regexnaofunciona") // true

isBase64("hoje") // true

isBase64("errado+tanto+faz") // true

A expressão acima é falha pois valida qualquer {String} com comprimento de 4 ou múltiplo de 4.
Vale ressaltar que se não é possível afirmar que a {String} de entrada de fato foi encodada em base64 não existe garantia que o RegExp acima não valide-a formando assim um "falso-positivo".
Comment: Excelente resposta, buscando abstrair os `falsos-positivos` coisa que acontece com bastante frequência principalmente falando de **javascript**.
Answer: As strings em base64 tem apenas os caracteres de a-z, A-Z, 0-9,'+','/' e '=' ou seja, se existir qualquer caracter que não sejam estes, como por exemplo um espaço ' ', então essa string não está em base64. Esse é o teste que deve ser feito por regex.
Tente alterar o Regex para este aqui:
^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$
Para codificar e decodificar utilize as funções btoa() para codificar e atob() para decodificar. Segue referência para as funções:
JS base64 Encode and Decode
Comment: Desculpe a opinião más não acredito que este regex esteja correto pois ele valida qualquer conjunto com comprimento múltiplo de quatro ex: **"regexnaofunciona"**, **"hoje"**, **"errado+tanto+faz"**... o correto seria envelopar em um `try\catch` o retorno da função `atob` usando a possível string encodada. Isso de fato definiria se a string foi encodada em base64
Comment: Muito obrigado Alexandre...

Verificação de base64?