The multinomial coefficient and number of unique words

Question: Let's define $C$ as the number of possible sequences of length $N$ we can form using symbols $A_i$ from an alphabet $A = \{A_1,\ldots , A_M\}.$
To my knowledge, we always have $C = M^{N+1}$.
For example, the total count of numbers containing 3 digits that we can form using decimal digits is $10^4$ = 1000, which would be the cardinality of $\{000, 001, ... 999\}$.
Or for example, the total count of binary numbers we can build with 3 bits is $2^4$ = 16, which would be the cardinality of $\{000, ..., 111\}$.
Separately, I have read that the multinomial coefficient ${n \choose k_{1},k_{2},\ldots ,k_{m}}={\frac {n!}{k_{1}!\,k_{2}!\cdots k_{m}!}}$ can be understood as:

The number of distinct ways to permute a multiset of n elements, and $k_i$ are the multiplicities of each of the distinct elements.

How are these problems and quantities related? Are they one and the same for some choices of $k_i$, $n$, $N$ and $M$?
Put another way, can $C$ be written as a multnomial coefficient?
Answer: Suppose that you have an alphabet $A=\{a_1,\ldots,a_m\}$ of $m$ symbols. Using this alphabet we can form $m^n$ distinct sequences of length $n$ (not $m^{n+1}$). Now suppose that $$k_1+k_2+\ldots+k_m=n\;;$$ the multinomial coefficient $\binom{n}{k_1,\ldots,k_m}$ is the number of distinct sequences of length $n$ that contain exactly $k_1$ instances of $a_1$, $k_2$ instances of $a_2$, and so on. The relationship between the two is then straightforward:
$$m^n=\sum_{\substack{\langle k_1,\ldots,k_m\rangle\in\Bbb N^m\\k_1+\ldots+k_m=n}}\binom{n}{k_1,\ldots,k_m}\;:$$
the sum is taken over all possible counts of the different symbols.
Comment: @Josh: The length of a sequence of symbols is the number of symbols in the sequence. If the usual digits are your symbols, the length of $1000$ is $4$. The strings of length $3$ are $000,001,\ldots,999$, and there are $10^3=1000$ of them.
Answer: For example, take $n = 3$, $m=2$, $k_1 = 1$ and $k_2 = 2$.  $${3 \choose 1,2} = \frac{3!}{1!2!}=3$$ is the number of $3$-letter words consisting of one "a" and two "b".
$$ abb, bab, bba $$
On the other hand, $2^3 = 8$ is the total number of
$3$-letter words from this alphabet.  This includes the cases $(k_1,k_2) = (3,0), (2,1), (1,2), (0,3)$.
In general, $$ m^n = \sum_{k} {{n} \choose {k_1,\ldots, k_m}}$$
where the sum is over all $m$-tuples of nonnegative integers whose sum is $n$.
Answer: $C$ represents the number of strings you can write without any limitation, the multinomial coefficient gives you the number of strings you can write when using exactly $k_1$ times $A_1$, $k_2$ times $A_2$ and so on. Hence, the sum of all the multinomial coefficients (going over all $k$s such that $\sum k_i = n$ must give you $C$).
Say $n=2$, and the alphabet has two letters: A,B.
Total number of words ($C$): AA,AB,BA,BB.
$k_1=2,k_2=0$: AA
$k_1=1,k_2=1$: AB,BA
$k_1=0,k_2=2$: BB
Comment: No, $C$ cannot be written as a multinomial coefficient, just as the sum of them. They describe different problems in terms of how many times each letter can be used.
Comment: Thanks - That makes sense, so would you say that $C$ can be written as a multinomial coefficient? or not?


For what $z$ does this series converge?

Question: I am given the following power series:
$$\sum_{n=1}^\infty\frac{z^{n}+z^{-n}}{n^2}$$
My attempt:
$$\sum_{n=1}^\infty\frac{z^{n}+z^{-n}}{n^2}=\sum_{n=1}^\infty\frac{z^{2n}+1}{n^2z^{2n}}\cdot z^n$$
I then tried to solve for the radius using $z_n$ but can't find a solution. Can someone explain me how to get the radius of convergence and then how to calculate the points to which this series converges? Thanks a lot.
Comment: This is a power series? To me a power series have this form $$a=\sum a_k X^k$$
Comment: It's not a power series, so there's no reason to expect it to have a "radius of convergence". It converges if, and only if, $|z|=1$.
Comment: I think so atleast it appears on a bunch of exercises about power series and their radius of convergence. I can do the others because they are in the form you mentioned but this one i cant solve
Comment: (with the typo corrected) this is a (formal) Laurent series, and if $|z| \ne 1$ then $|z^n + z^{-n}| \sim |z|^n$. For $|z|=1$, you have to use the summation by parts : $\sum_{n=1}^N \frac{1}{n} z^n =\frac{1}{N}\sum_{n=1}^Nz^n +\sum_{n=1}^{N-1}(\frac1{n}-\frac{1}{n+1})\sum_{m=1}^nz^m$
Comment: Shouldn´t a Laurent series start in negative infinity?
Comment: Sorry but are formal power series any different from normal power series. I was trying to change the series so that i could put it in a format where i could calcutate the radius and from there the z to which it converges
Comment: You have misstated the problem, with $i$ and $n$ and other things. State it precisely please
Comment: Sorry about that i fixed it now
Comment: Are you still here, Pedro?
Comment: yeah sorry had somethings that took me some time what makes you believe it is not a power series? And if it is a normal series how can i see here it converges normally with other series they either converge or they not rigth?
Comment: If you want to be sure that I see a comment addressed to me, Pedro, you have to include @Gerry in it. It's not a power series because, by definition, a power series only has nonnegative powers of $z$. And I've told you when it converges, and when it doesn't, so what is your problem?
Comment: @Gerry Sorry kinda new to this. I thinks there are some power series with negative powers of z the laurent series for example. You got the same answer as my book could you explain me how you manage to find it. I kind of thought that a series that is not a power series would either converge or diverge not being dependent of where. Thanks for the answer
Answer: If $|z|>1$, then $$\left|{z^n+z^{-n}\over n^2}\right|\ge\left|{z^n\over n^2}\right|-\left|{z^{-n}\over n^2}\right|>1$$ for large $n$ (since $|z^n/n^2|\to\infty$ and $z^{-n}/n^2\to0$ as $n\to\infty$), so the series diverges (a necessary condition for $\sum a_n$ to converge is $a_n\to0$ as $n\to\infty$).
If $|z|<1$, then $$\left|{z^n+z^{-n}\over n^2}\right|\ge\left|{z^{-n}\over n^2}\right|-\left|{z^n\over n^2}\right|>1$$ for large $n$ (since $|z^{-n}/n^2|\to\infty$ and $z^n/n^2\to0$ as $n\to\infty$), so the series diverges.
If $|z|=1$, then the series converges, by comparison to $\sum2n^{-2}$.

For what $z$ does this series converge?


How to move logic to ViewModel?

Question: How i can move logic from fragment in my ViewModel?
override fun onItemClick(titleName: Int) {
    when (titleName) {
        R.string.about_terms_service -> {
            activity?.addFragment(
                WebViewFragment.newInstance(
                    TERMS_LINK,
                    getString(R.string.about_terms_service)
                )
            )
        }
        R.string.about_open_source_licenses -> activity?.addFragment(LicensesFragment())
    }
}

Comment: this is pure view logic, i believe it's ok to be in the view not viewmodel
Comment: @y.allam  I don't agree, but how can I test the logic of clicking on one or the other `titleName`?
Answer: This logic can be moved to ViewModel, with a bit of overhead though. For sure, the decision of which fragment to add should be moved to ViewModel, but the adding fragment's code should stay in Fragment (or Activity). I think it should look something like this:
Fragment:
override fun onItemClick(titleName: Int) {
    viewModel.onTitleClick(titleName)
}

ViewModel:
fun onTitleClick(titleName: Int) {
    when (titleName) {
        R.string.about_terms_service -> {
            postViewModelEvent(ShowWebViewFragmentEvent())
        }
        R.string.about_open_source_licenses -> {
            // TODO: open License fragment
        }
    }
}

In the ViewModel you should replace this // TODOs with a specific command to your View (Fragment, Activity), which will trigger navigating to specific fragment. On how to do that, for example, is written here (but of course, any ViewModel - Fragment solution will work).
In this case, this logic can be easily tested.
If you're connecting your ViewModel with your Fragment via view model events (described in the link), you can do this:
Create an event of showing WebViewFragment like this:
class ShowWebViewFragmentEvent(): ViewModelEvent {
    override fun handle(activity: BaseActivity) {
        super.handle(activity)
        activity?.addFragment(
                WebViewFragment.newInstance(
                    TERMS_LINK,
                    getString(R.string.about_terms_service)
                )
            )
    }
}

and post it in your ViewModel (replacing first // TODO) like this:
postViewModelEvent(ShowWebViewFragmentEvent())

Please note, that all the required changes from the linked post should be done.
Comment: hm, and for example i need to create interface how i created in mvp.
Comment: i use code for my fragment which i see here https://stackoverflow.com/questions/46429511/android-viewmodel-call-activity-methods/58076044#58076044 , but also can't understant what i need to write in my // TODO:
Comment: If you're using code which observes ViewModel events in your Fragment, then you should post/emit your new/specific events in `// TODO`
Comment: can u give please one example for first condition?
Comment: Added as an example to the post. Remember to do all the code changes from the linked post (view model should provide observable events, fragment should subscribe to those and handle once observed)
Comment: but still the event is responsible for navigation here, not the fragment
Answer: Thanks for advice, but i modified this solution with next code:
Fragment:
override fun onItemClick(titleName: Int) {
    viewModel.onTitleClick(titleName)
}

ViewModel:
fun onTitleClick(titleName: Int) {
        when (titleName) {
            R.string.about_terms_service -> {
                termsOfServiceItemClickEvent.postValue(
                    ViewModelEvent(
                        WebViewFragment.newBundle(
                            url = TERMS_LINK,
                            title = appContext.getString(R.string.about_terms_service)
                        )
                    )
                )
            }
            R.string.about_open_source_licenses -> licenseItemClickEvent.postValue(ViewModelEvent(R.string.about_open_source_licenses))
        }
    }

ViewModelEvent:
open class ViewModelEvent<out T>(private val content: T? = null) {

    var hasBeenHandled = false
        private set

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }
}

And again fragment:
viewModel = ViewModelProviders
    .of(this, viewModelFactory)
    .get(AboutViewModel::class.java)

viewModel.licenseItemClickEvent.observe(this, Observer<ViewModelEvent<Int>> {
    it?.getContentIfNotHandled()?.let { activity?.addFragment(LicensesFragment()) }
})
viewModel.termsOfServiceItemClickEvent.observe(this, Observer<ViewModelEvent<Bundle>> {
    it?.getContentIfNotHandled()?.let { args ->
        activity?.addFragment(WebViewFragment.newInstance(args = args))
    }
})

How to move logic to ViewModel?


Get list of all Activities available on the System

Question: Since the system should know about the available Activities as they are declared in the appropriate AndroidManifest.xml files which are evaluated during installation:
Is there a way to query these Activities?
Answer: Sure, have a look at PackageManager.getInstalledPackages method. Here is the example of printing registered activities names:
List<PackageInfo> pInfos = getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);
for (PackageInfo pInfo : pInfos) {
  ActivityInfo[] aInfos = pInfo.activities;
  if (aInfos != null) {
    for (ActivityInfo activityInfo : aInfos) {
      Log.i("ACT", activityInfo.name);
      // do whatever else you like...
    }
  }
}

Answer: ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
PackageManager pm = ctx.getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(0);

for(int i=0;i<packs.size();i++) {
    PackageInfo p = packs.get(i);
    String description = (String) p.applicationInfo.loadDescription(pm);
    String  label= p.applicationInfo.loadLabel(pm).toString();
    String packageName = p.packageName;
    String versionName = p.versionName;
    String versionCode = p.versionCode;
    String icon = p.applicationInfo.loadIcon(pm);
//Continue to extract other info about the app...
}

Note: Add this permission to the manifest file:
<uses-permission android:name="android.permission.GET_TASKS" />

Add this to above code:
PackageManager.getactivities -- I have not used this PackageManager.getactivities but I hope it will work for you....

Comment: `pm.getInstalledPackages(0)` - this will not work since you need to specify what kind of info PackageManager should return (i.e. PackageManager.GET_ACTIVITIES). Check my answer below. Btw, `android.permission.GET_TASKS` is not needed to enumerate activities I was able to deal without it.
Comment: I have mentioned PackageManager.GET_ACTIVITIES to be added as the above code I have used to fetch the list of installed apps in the device...
Comment: You do not need `getApplicationContext()` -- just call `getPackageManager()` on `ctx`.


double x-axis in R native plot, one for double frequency and the second for Dates

Question: I am using native R plot function to genertae graphics.  looking to add a double x-axis on same plot. One holds doubles and the other x-axis holds Date object.  I am using the following commands but they dont seem to work.
First x-axis:
axis.Date(1,at=seq(min(x$Date),na.rm=TRUE,max(x$Date),na.rm=TRUE,by="2 years"),format ="%Y-%m-%d",col.axis="white", cex=1)

Second x-axis:
axis(1,at=seq(min(f), max(f), by = 0.1), col.axis="white", cex=1)

The parameters for the R native plot:
x11()
 par(mfrow=c(1,1),oma = c(0, 0, 2, 0) )

Result is only Dates on x-axis.
Answer: Up front: dual axes can easily be mis-used by mis-representing the data and/or ranges. It's easy for eyes to misconstrue correlation or relationships based on imperfect axis decisions. For scatter plots (such as below), I'm not a fan and tend to avoid them ... but I do use them under very controlled circumstances, as they can provide visual correlation of relative trends.
When I must do it, I'm a fan of using color as a way to more strongly tie points (or lines) with particular axes, though of course this does not work as well with color-impaired readers.
Given that preface ...
I believe the easiest way to handle multiple axes in base-R is to use par(new=TRUE) between plots. Here's an example:
par(mar = c(4,4,4,4) + 0.1)

plot(disp ~ mpg, data = mtcars, las = 1)

par(new = TRUE)

dat <- data.frame(dat = Sys.Date() + 0:5, y = 1:6)
plot(y ~ dat, data = dat, ann = FALSE, yaxt = "n", xaxt = "n", pch = 16, col = "red")
axis.Date(3, dat$dat[1], col = "red", line = 1)
axis(4, col = "red", line = 1, las = 1)

Other differentiating techniques include shapes or line-types (if lines) specific to each side, and adding those as clear markers on the secondary axes.
The use of par(new=TRUE) simply allows the next plot command to not reset/clear the canvas before starting over. This means that the subsequent plotting functions have no knowledge of what is existing. From ?par:
     'new' logical, defaulting to 'FALSE'.  If set to 'TRUE', the next
          high-level plotting command (actually 'plot.new') should _not
          clean_ the frame before drawing _as if it were on a *_new_*
          device_.  It is an error (ignored with a warning) to try to
          use 'new = TRUE' on a device that does not currently contain
          a high-level plot.

It doesn't work well with all plotting mechanisms (certainly nothing grid or ggplot2), and anything that might be sensitive to margins or oma or other parameters should be tested carefully with various ranges of data.
I intentionally used line=1 to "bump out" the top/right axes, another way to set them apart. Frankly, I often do that for the bottom/left (primary) axes as well, it can be aesthetically preferred ... but it's an option and not required for this technique to at least start the process.


Dados de formulário não estão sendo cadastrados

Question: Tenho um formulário escrito em php com conexão a um banco administrado pelo phpMyAdmin.
O QUE DEVERIA ACONTECER:
Os dados inseridos no formulário deveriam ser cadastrados aparecendo um alert de "salvo com sucesso" e voltando para a página anterior.
O QUE ESTÁ ACONTECENDO:
Ao tentar cadastrar, até redireciona pra página responsável por cadastrar e mostrar o alert, mas a página está em branco, não aparece nenhum alert, não volta pra página anterior e nem cadastra as informações no banco.
FORMULÁRIO:

Cadastro de Formações

                    <form id="cadastro" name="cadastro" method="post" action="banco/updateF.php" style="
                        text-align: left;
                        margin-top:50px;">

                                Nome:
                                <input  type="text" required class="form-control" id="NOME" name="NOME" placeholder="Nome da formação">

                                Carga Horária:
                                <input  type="text" required class="form-control" id="CARGA" name="CARGA" placeholder="Carga horária da formação">

                                Objetivo:
                                <input  type="text" required class="form-control" id="OBJETIVO" name="OBJETIVO" placeholder="Objetivo da formação">

                                Conteúdo da programático:
                                <textarea class="form-control" id="CONTEUDO" rows="3" name="CONTEUDO" placeholder="Conteúdo programático da formação"></textarea>

                                <button type="submit" class="btn btn-primary btn-lg btn-block">Salvar</button>

                                Hey!  Antes de realizar o cadastro, certifique-se de que não se esqueceu de nada! :)

                     </form>

A CONEXÃO:
<?php
    mysql_connect("localhost","root","") or die ("erro na conexao com o banco de dados!");
    mysql_select_db("db_formacao");
?>

O UPDATE:

<?php
require ("conecta.php");
//coletando dados do formulario

    $nome           =   $_POST["NOME"];
    $carga          =   $_POST["CARGA"];
    $objetivo       =   $_POST["OBJETIVO"];
    $conteudo       =   $_POST["CONTEUDO"];

// Inserir dados no banco
    $itens = $_POST['NOME'];

    if (!empty($itens)){
        $itens = implode(',', $_POST['NOME']);
    }
$up = "UPDATE turmas SET NOME = '$nome', CARGA = '$carga', OBJETIVO = '$objetivo', CONTEUDO = '$conteudo'";
echo $up;

$up= mysql_query($up) or die(mysql_error());

?>
<?php
    if (mysql_affected_rows() > 0) {
        echo '';
    } else {
        echo '';
    }
?>

Quando tento exibir o código fonte dessa página em branco pelo navegador só aparecem os comentários da página update.
Não sou muito experiente, mas pelo que eu estudei, não parece nada errado.
Se puderem me indicar os erros, agradeceria bastante. :)
Comment: Mariana, por gentileza peço que não fique adicionando AJUDA no titulo, só o fato de ter perguntado no site já entendemos que precisa de ajuda com seu problema.
Comment: Qual a versão do php?
Comment: Isso é algo que eu esqueci de comentar. Minha versão do php é antiga e como tem muitos sistemas rodando nessa versão, eu não posso atualizar.
Comment: Ta, eu ia tirar depois de uns minutos.
Comment: Mas não pode fazer isso simplesmente com o objetivo de "upar" a pergunta. Caso as respostas não tenham resolvido o problema, comente abaixo delas. Ou edite a pergunta fornecendo mais detalhes. Pode também ler [ask] para saber como melhorar a pergunta.
Comment: Sim, mas já to fornecendo todos os detalhes, já comentei abaixo das respostas, to estudando, tentando resolver mas não encontro o problema e já fazem alguns dias. Sei que ninguém tem a obrigação de me responder, foi só uma tentativa, não precisa dar bronca.
Answer: Mariana, se você está enviando javascript para o navegador do cliente é necessário enviar o cabeçalho correto, no caso antes do seu echo faça isso :
header('Content-Type: application/javascript');
if (mysql_affected_rows() > 0) {
    echo '';
} else {
    echo '';
}

No caso acima estou enviando ao navegador e avisando que o código de retorno do php é um javascript, para que ele interprete a rotina.
Atualização
  <?php
       require ("conecta.php");
       //coletando dados do formulario
       $id             =   $_POST["ID"];
       $nome           =   $_POST["NOME"];
       $objetivo       =   $_POST["OBJETIVO"];
       $conteudo       =   $_POST["CONTEUDO"];
       $carga          =   $_POST["CARGA"];

       // Inserir dados no banco
       $itens = $_POST['NOME'];

       if (!empty($itens)){
           $itens = implode(',', $_POST['NOME']);
       }
       $up = "UPDATE formacoes SET NOME = '".$nome."', OBJETIVO = '".$objetivo."',
       CONTEUDO = '".$conteudo."', CARGA = '".$carga."'  WHERE id =".$id;
       $up= mysql_query($up) or die(mysql_error());

       echo "Número de linhas afetadas:".mysql_affected_rows()."
";
       if (mysql_affected_rows() > 0) {
            $resposta = 'Update concluído com sucesso!';
       } else{
           $resposta = 'Cadastro não sofreu alterações!';
       }
       mysql_close($conexao);
       die($resposta);
   ?>

Roda com esse script e me diz o que deu?
Comment: Então, até fiz, mas continua a mesma coisa. O engraçado é que esse mesmo update funciona em outro sistema.
Comment: Faça um teste assim que aparecer a página em banco com o botão direito mande exibir o código de fonte e verifique se tem o conteúdo do seu echo.
Comment: Então, não está mostrando o conteúdo, o que me leva a acreditar que talvez o problema seja no formulário. :/
Comment: Essa página php banco/updateF.php existe? Você está postando para ela, é esse mesmo o nome ? Se o form está online mande o endereço para que eu possa verificar.
Comment: Então, se trata de um sistema interno então não tá online. Mas essa página updateF.php existe sim, a página chega a ser redirecionada pra ela. Vou colocar uma imagem do que está acontecendo.
Comment: Então, rodei com esse script e deu a mesma coisa, nada novo aconteceu. :/
Comment: É, nada ainda. @RafaelSalomão
Answer: Posso estar errado, mas pelo que vi no formulário de preenchimento dos dados, não tem a entrada para o ID, e no código PHP tanto na recuperação dos dados quanto na query de update você usa um id que não existe. Deu pra entender o que eu quis dizer?
Olha o código de novo e veja no formulário que não tem um campo para inserir o id, e no seu código php está assim:
   $id             =   $_POST["ID"]; //essa linha aqui não está recuperando nada
   $nome           =   $_POST["NOME"];
   $objetivo       =   $_POST["OBJETIVO"];
   $conteudo       =   $_POST["CONTEUDO"];
   $carga          =   $_POST["CARGA"];

Logo em seguida temos:
    $up = "UPDATE formacoes SET NOME = '$nome', OBJETIVO = '$objetivo', CONTEUDO = '$conteudo', CARGA = '$carga'  WHERE id = '$id'";
//nessa linha você está usando um id inexistente

Talvez seja por isso que o update não esteja sendo realizado. Confere aí e dá um feedback!
Comment: Muito bem notado CloudAC +1. Cadê o campo id para ser postado Mariana deveria ser um
Comment: Nossa, isso faz muito sentido! Eu tinha colocado o ID porque existe um campo na tabela que é um ID auto increment então fiquei na dúvida se deveria colocar ou não.
Comment: Sim passei o olho e não notei, corrigi isso e vê se funciona e aproveita pega o código que montei abaixo e melhora o seu que está muito bagunçado a escrita.
Comment: Certo, fiz as alterações recomendadas. Deixa eu fazer uma pergunta: A minha formação tem um ID. Quando eu for cadastrar uma turma, vou precisar do ID da formação pra dizer que a turma pertence a aquela formação, certo? Outras formações vão ser cadastradas, então, eu não precisaria do Where pra dizer em qual formação os dados devem ser atualizados?
Comment: Mari melhor montar outra pergunta senão tira a coesão desse post. E ai já sabe os moderadores vem em cima! =P
Comment: Ah, certo, vou montar e coloco o link aqui, ok? :)
Answer: Nada estava errado com o formulário, o erro era no arquivo update.
Reformulei e resolveu assim:

<?php

    $nome = $_POST['NOME'];
    $carga = $_POST['CARGA'];
    $objetivo = $_POST['OBJETIVO'];
    $conteudo = $_POST['CONTEUDO'];

    $strcon = mysqli_connect('localhost','root','', 'db_formacao') or die('Erro ao conectar ao banco de dados');
    $sql = "INSERT INTO formacoes VALUES ('$id', '$nome', '$carga', '$objetivo', '$conteudo')";
    mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro");
    mysqli_close($strcon);

    echo "Formação cadastrada com sucesso!";
?>

Agradeço a todos que me ajudaram.


I don't feel like I'm keeping up with the right tempo

Question: I'm practicing a solo, and this is my first solo. I have started with a pretty hard one for my first solo. There are a lot of pull offs in this solo, and I'm able to play them ok. The song tempo is 186bpm and it's all 8th notes. I'm watching the metronome as I'm playing, and I start with first beep and finish on the second beep of the second measure exactly as it should be. The problem is, I'm getting a feeling that I'm not playing the pull offs in the middle properly on the beats. I dont know, maybe faster, maybe slower. How can I know that I'm playing exactly with the right tempo?
Comment: When you say "the song tempo is 186 bpm" you need to think of that as a suggestion rather than an order. You will find all sorts of different tempos in different performances of the same piece, and tempo isn't what makes them work or not work.
Answer: If you're practising this at 186 bpm it begs the question why. If you can't play it at that tempo, you can't play it. Yet. Most of us who play, try something difficult and maybe play it at half speed, or even less. There is no shame in that at all. It gives the time to think a little compared to what you're doing, which obviously isn't helping anything, except repeating mistakes. And we all know that repetition is a form of learning. So, well done, you're actually learning to play with the mistakes indelibly included. Making re-learning it ten times more difficult!
Hammers and pull-offs can all be done at a slow speed. There's nothing quick about them - try playing a note for 5 seconds, then pulling off to a lower one. In fact, you don't even have to play the first note to achieve the pull-off! So, slowly slowly catchee monkey. Put in our terms, use the metronome, but put it at maybe 90bpm for a while, so you can catch what your fingers are doing wrong.
Gradually speed up, till next week, you're close to the required tempo. Buy then, your fingers will have been trained, and you will hardly need to do the bit that players don't need - think about the actual notes you play in that solo. You can, instead, think about putting some feel into them instead.


Is there any graphical explanation of Multivariate Gaussian?

Question: I am trying to catch up with my statistics. I want to understand what are multivariate Gaussian or multivariate normal distribution. I understand what a univariate Gaussian is any variable $X$ such that $X\sim N(\mu,\sigma^2),\mu\in\mathbb R, \sigma^2>0$ (except for complex numbers, isn't something squared always greater than $0$ ?), that is to say, if $x_i\in X\sim N(0,\sigma^2)$ There is lots of chance that it pertains to something that looks like this :

And as far as
if $x_i\in X\sim N(\mu,\sigma^2)$ with $\mu =\begin{bmatrix}0\\0\end{bmatrix}$ and $\sigma =\begin{bmatrix}1 & 3/5\\3/5 & 2\end{bmatrix}$ (I don't understand the  covariance matrix, especially the bottom right corner) It would have be part of something like this :

But then I don't understand its definition given on ... which I found back on Wikipedia :

A random vector $X = (X_1, …, X_k)'$ is said to have the multivariate normal distribution if it satisfies the following equivalent conditions.

Every linear combination of its components $Y = a_1X_1 + … + a_kX_k$ is normally distributed
i.e. $a^TX=\sum_{i=1}^na_iX_i$ is Gaussian $\forall a\in\mathbb R^n$ (what $a$ has to do there ?)

Would it mean, if we had three random variables, that combining two of them would be a Gaussian, it would look like the picture above. Yet, it isn't a Gaussian, it's a bi dimensional Gaussian !
Comment: "except for complex numbers, isn't something squared always greater than 0 ?" Not if it's zero. What that condition is telling you is that $\sigma^2$ is not allowed to be zero.
Answer: No, the property means that if every projection from $k$ dimensions to $1$ (i.e. any linear combination) yields a normally distributed variable, then the $k$D variable is a multivariate Gaussian. [A single projection is insufficient. On your second plot, you see two different projections giving $1$D Gaussians. If I am right, $k$ independent projections are sufficient.]
If you want to picture a multivariate Gaussian, think of the locus of equiprobable points. In $1$D, you get two isolated points. In $2$, an ellipse. In $k$D, the generalization of an ellipse, i.e. an hyperellipsoid.
Comment: @MichaelHardy: that's right.
Comment: Thank you for your answer ! I understand everything but the bracket point !
Comment: @Marine1: this is a little technicality, don't worry.
Answer: If you have three random variables $X_1,X_2,X_3$ then the statement that the triple $(X_1,X_2,X_3)$ has a multivariate Gaussian distribution means that regardless of which three numbers $a_1,a_2,a_3$ you choose, the linear combination $a_1X_1 + a_2X_2 + a_3X_3$ has a univariate Gaussian distribution. For example, $40X_1 + 5X_2 - 13X_3$ has a univariate Gaussian distribution, and similarly for any other triple of numbers besides $(40,5,-13).$
Comment: I understand ! So why should we bother with multivariate distribution if for any combination of the variables which are part of a multivariate distribution we have a univariate distribution ?
Comment: @Marine1 : For one thing, how would you find confidence ellipsoids? And how would you talk about the conditional distribution of $X_1,X_2$ given $X_3, X_4\text{?}$ And there's the multivariate counterpart of the chi-square distribution, the (matrix-valued) Wishart distribution, used for a number of things in statistics.
Answer: Multivariate as product of independent univariate gaussians
Correlated m=ultivariate gaussian in X space can be projected into de-correlated Y using the eigenvector matrix $U^T$ based on Eigen decomposition: Covariance of X $ = \Sigma = U\Lambda U^T$.
In Y space, the probability distribution is the product of independent univariate gaussian distributions.
$$p(y) \propto \prod\limits_{i=1}^D exp \Big( - \frac {1}{2} \sum_{i=1}^D \frac{y_i^2}{\lambda_i} \Big)$$
Devivation

I found it is helpful to understand the Mahalanobis Distance first.


Highcharts : draw a chart with data from XMLHttpRequest ()

Question: I begin in javascript...
I would like to draw a chart with data from XMLHttpRequest () as to YAXIS.
I receive the data from the server like this:
function cgi_return_data_conso_elec()
{
   var xhr = new XMLHttpRequest();

   xhr.open("GET", "/cgi-bin/return_data_conso_elec?01/04/2015", true);
   xhr.send(null);

   xhr.onreadystatechange = function()
   {
      if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
      {
      var array_reponse = xhr.responseText.split("/");
      var data1 = array_reponse[1];
      alert(data1);
      }
      else
      {
         //document.getElementById("text_test").innerHTML = "wait...";
      }
   }
}

the value of data1 is = 333,2682,2823,1749,624,860,4450,2402,2552,2199,605,794,2433,4060,821,692,477,1005,2904,2438,2066,1652,1672,1544
I draw the graph like this:
   $('#container').highcharts
   ({
        chart:
      {
            type: 'column'
        },
        title:
      {
            text: 'CONSO ELEC'
        },
        subtitle:
      {
            text: 'Source: PATATE.com'
        },
        xAxis:
      {
            categories: ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23'],

         labels:
         {
                rotation: - 90,
            //align: 'right',
            x: -26,
                y: 15
            //distance: 100,
            //padding: 175
            //format: '{value} km'
            }
         //crosshair: true
        },
        yAxis:
      {
            min: 0,
            title:
         {
                text: 'Conso (Wh)'
            }
        },
        plotOptions:
      {
            column:
         {
                pointPadding: 0,
                borderWidth: 0
            }
        },

      series: [{

            name: 'Berlin',
      data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1,42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]

        }]
    });

I want to replace the data of "Berlin" by the variable "data1" but I can not !!
My html page:
<!DOCTYPE html>

   <meta charset="utf-8" />

   <link rel="stylesheet" href="test_style.css" />

   <title>test graph data conso elec</title>

I know that must be used: "series.data.push(parseFloat(item));"
but I can not have put it in my code...
If anyone can help me, I would be really happy ...
thank you in advance
Comment: You need to create chart inside the callback, for example replace `alert(data1);` with creating chart. And there you have access to `data1`, where you need to write parser from your `data1` string to proper format for Highcharts. Also, since you have jQuery on your website, I think you may want to use `$.get()` method instead of using `xhr` directly.
Answer: thank you for your reply.
Here is a solution that works:
function graph_teleinfo()
{

var xhr = new XMLHttpRequest();

    xhr.open("GET", "/cgi-bin/return_data_conso_elec?01/04/2016", true);
    xhr.send(null);

    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
        {

            var array_reponse = xhr.responseText.split("/");//separe les differents champs du str reponse

         var data_tempo;
         var data1 = new Array();
         data_tempo = array_reponse[1].split(",");
         //alert(data2.length);

         var data3 = new Array();
         data3 = array_reponse[2].split(",");
         //alert(data3);

         for (var i = 0; i < data_tempo.length; i++)
         {
            data1[i] = parseFloat(data_tempo[i]);//stock les valeur du str contenu dans "xhr.responseText" dans le tableau et les transforme en float

         }//fin for...

//-----------------------------------------------
//construit le graph

         $('#container').highcharts
         ({

            chart:
            {
               type: 'column'

            },
            title:
            {
               text: '01/04/2015'
            },
            subtitle:
            {
               text: 'Source: raspi-elec'
            },
            xAxis:
            {
               categories: data3,

               labels:
               {
                  rotation: - 90,
                  align: 'right',
                  //x: -30 ,
                  //y: 15

               }

            },
            yAxis:
            {
               min: 0,
               title:
               {
                  text: '(Wh)'
               },

               labels:
               {

               },
            },
            tooltip:
               {

                  useHTML: true,
                  pointFormat: '{point.y} Wh'

               },
            plotOptions:
            {
               column:
               {
                  pointPadding: 0,
                  borderWidth: 0
               }
            },

            series:
            [{

               name: 'Consommation électrique',
               data: data1

            }]
         });

//-----------------------------------------------

       }
      else
      {
         //document.getElementById("text_test").innerHTML = "wait...";
      }
    }

}//fin fonction graph_teleinfo()


Let $A$ is a square matrix of order $2016$ and $I$ is an identity matrix of the same order, where $A^TA=I$.

Question: Prove:
$A^T(A-I)=-(A-I)^T$
$\det A=1$ or $\det A=-1$
If $\det A=-1\Rightarrow \det(A-I)=0$
One example of a symmetric matrix is the identity matrix which satisfies these statements. How to generalize this proof?
Comment: Identifying that $A = I$ is a solution does not help at all here, especially if you want to "generalize" the "proof." A good start is computing $(A - I)^T$ in terms of objects on the left hand side of the equation. For the second part, look at how determinants behave under matrix multiplication.
Answer: From $(A+B)^T=A^T+B^T$ and $\det(A^T)=\det(A)$ you get that $$A^T(A-I)=A^TA-A^T=I-A^T=I^T-A^T=-(A-I)^T$$ and $$1=\det(I)=\det(A^TA)=\det(A)\det(A^T)=\det(A)^2$$ which implies that $\det(A)=\pm 1.$ For the last one it comes from $$-\det(A-I)=\det(A-I)\underset{=-1}{\underbrace{\det(A^T)}}=\det(I-A)=(-1)^{2016}\det(A-I)=\det(A-I).$$


How to add a base field for an entity reference to a specific vocabulary

Question: I have an Entity: EntityX.  It installs correctly and works the way that I want it to; with, of course, one exception.
I want to attach an entity reference to a specific vocabulary.  I have tried:
My vocabulary's machine name is: custom_vocabulary
In EntityX's definition I have the following defined in the baseFieldDefinitions function:
$fields['my_custom_vocabulary'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Vocabulary'))
  ->setDescription(t('What was this tagged with.'))
  ->setSetting('target_type', 'custom_vocabulary')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'author',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

But when I go to install it, I get the following error:
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "custom_vocabulary" entity type does not exist. in /brew/www/html/core/lib/Drupal/Core/Entity/EntityTypeManager.php:133

While looking at the article defined in the installation profile for Drupal, I see that they use it as a field and not a true entity reference.  Is there no way for me to do it this way?  I can't have this all nicely bundled into one single entity.
What I don't know how to do is add a term from a vocabulary to an entity type.
Answer: Vocabularies are bundles of the entity type taxonomy term. If you want to reference a vocabulary then first set taxonomy_term as target type and second restrict the field to a specific vocabulary as target bundle:
$definition = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler_settings', ['target_bundles' => ['custom_vocabulary' => 'custom_vocabulary']]);

See change record https://www.drupal.org/node/2576151


Dealing with few instances in support vector regression

Question: What is the best way of going about dealing with few instances in support vector regression, e.g. only approximately 40? Also - is there an optimal way of dealing with outliers in this case of few instances?
Comment: A feature selection will be carried out based on subject matter expertise, but I am still looking to first run an SVR on all features - approximately 60. I believe the experts will bring the number of features down to approximately 30, and I will then run another SVR.
Comment: it depends on how many features you have.
Answer: First, I'd advise you to separate the outlier detection problem
from the estimation one. Both however will have to take account
of the fact that you are dealing with very few observations in
 a very large space.
For the outlier detection problem, I'de use some high dimensional
outlier detection algorithm on the design space. Specifically,
ROBPCA with $k$ set to $\approx n/5$ (in your case $k=8$).
You'll find a good R implementation of ROPBCA in the function PcaHubert here. You'll
find more details on page 26 of this note.
ROBPCA will give you a rank $k$ approximation of the covariance matrix
and the location vector of the non outlying part of your data. Using these
I would advise you to compute a rank $k$ approximation to the vector of
squared Mahalanobis distances $d_i^2(k)$ to attach to each observation
a weight
$$w_i=I(d_i^2(k)\leq \chi^2_{0.95,k})$$
another possibility is to attach to each observation a weight
$$w_i=\min\left(1,\frac{\chi^2_{k,0.95}}{d_i^2(k)}\right)$$
This is done to prevent observations located far away from the bulk
of the data to exert and out-sized pull and essentially drive the
 final estimates. In a nutshell, it insure that your model adequately
describes the pattern of the majority of your observations.
see also page 14 of this note.
Given these weights, I'd use some form of bayesian shrinkage and a logit to get the final model. This is again necessary because of the extreme sparsity of the space you are considering. Have a look at the Firth method. It's implemented in the package logistf.
Comment: Thank you for the detailed response! Might I ask if you have applied this approach successfully?
Comment: @Anna, you'll find good examples of application of these methods in the original papers (or papers citing them). For [example](http://bioinformatics.oxfordjournals.org/content/20/11/1728.short)


Como faço para que a minha aplicação entenda qual o botão deletar que eu estou clicando e deletar a lista certa?

Question: Tenho uma aplicação que acrescenta uma lista para a pessoa colocar um novo horário toda vez que a pessoa clica em um botão, essa nova lista vem com um botão de deletar do lado, mas quando a pessoa adiciona mais de uma lista, e tenta apagar a última, ela sempre apaga a primeira que foi incluída, parece que não identifica qual botão está sendo clicado.
O script de deletar está da seguinte forma:
function deleteField() {
  const fieldFather = document.querySelector('#schedule-items')
  const fieldSon = document.querySelector('#second-schedule-div')
  fieldFather.removeChild(fieldSon)
}

document.querySelector('.delete-button').addEventListener('click', deleteField)

e na lista que é adicionada, os botões tem um "onClick='deleteField()'"
o código que uso para adicionar as divs é:
OBS.: a div que eu clono, ela está no HTML com display none
document.querySelector('#add-time')
  //quando clicar no botão chama o cloneField
  .addEventListener('click', cloneField)

function cloneField() {
  ?
  const newFieldContainer = document.querySelector('#second-schedule-div').cloneNode(true)

  const fields = newFieldContainer.querySelectorAll('input')

  fields.forEach(field => {
    field.value = ''
  });

  document.querySelector('#schedule-items').appendChild(newFieldContainer)
}

código html:
<fieldset id='schedule-items'>
          <legend>Horários disponíveis
            <button type='button' id='add-time'>+ Novo Horário</button>
          </legend>

              Dia da semana

              <select name="weekday[]">
                <option value="">Selecione uma opção</option>

                {%for weekday in weekdays %}
                <option value="{{loop.index0}}">
                  {{weekday}}
                </option>
                {%endfor%}

              </select>

              Das
              <input type="time" name='time_from[]' required>

              Até
              <input type="time" name='time_to[]' required>

        </fieldset>

html da div clonada:

        Dia da semana

        <select name="weekday[]">
          <option value="">Selecione uma opção</option>

          {%for weekday in weekdays %}
          <option value="{{loop.index0}}">
            {{weekday}}
          </option>
          {%endfor%}

        </select>

        Das
        <input type="time" name='time_from[]' required>

        Até
        <input type="time" name='time_to[]' required>

        <button type='button' class='delete-button' onClick='deleteField()'>delete</button>

foto da aplicação:
Comment: Ah sim, entendi, perdão, sou novo aqui. Vou editar a postagem.
Comment: Você está deletando a imagem pelo id, o que no seu caso é o mesmo para todos os itens (id devem ser únicos) o navegador faz a leitura de cima para baixo, e na primeira ocorrência executa a ação, logo, o primeiro é deletado. Você precisa atribuir dinamicamente os id's únicos. Não coloque print do código, facilita para testar e executar seu código, cole o código e use as tags, sua pergunta está negativada por isso.
Comment: Como faço para gerar os ID's dinamicamente e pra que a aplicação entenda quando eu apertar o botão, que é referente aquele ID?
Comment: Como você gera as Div? Colque o código de como gera o HTML na pergunta.
Comment: Pronto, estão aí os códigos.
Comment: Mudei a abordagem, ta na resposta.
Answer: Acredito que a forma mais fácil sem alterar muito seu código seja buscar pelos elementos pais e remover. Alterei a função delete.
   function deleteField(t) {
      t.parentNode.parentNode.parentNode.removeChild(t.parentNode.parentNode);
   }

No botão, passe ele mesmo como parâmetro
<button type='button' class='delete-button' onClick='deleteField(this)'>delete</button>

Esse na div hidden, todos serão clonados desta forma
Comment: Cara, muito obrigado, funcionou perfeitamente, você é fera!!!


Sample size needed?

Question: I need some help calculating the minimum sample size needed for my upcoming trial. I'm doing higher degree research on eHealth, so I have little knowledge about statistics and sample size calculation. Was doing loads of research online and trying out online calculators but I'm still not too sure.
So basically I've done an initial trial on a small sample of 24 participants, randomly allocated to two groups (13 in control group and 11 in intervention group), the aim is to see whether the use of an IT based intervention can improve health supplement adherence rate when compared to a control group using a pillbox. Below is the result from the initial trial:
Control group- average baseline adherence rate before trial was 86%, and after trial the average adherence rate increased to 95%
Intervention group- average baseline adherence rate before trial was 81%, and after trial the average adherence rate increased to 98%
So what I would like to know is: what is the minimum number of participants I will need for each group (I want a 2:1 ratio, so more people in the intervention group). I need to know the very minimum number as I was having problem recruiting enough participants in the initial trial, and I'm currently starting the recruitment process for the upcoming full trial.
Power=at least 80%, and alpha=0.05
I've tried this online calculator, but unsure what to put in the anticipated incidence sections, or if it is the right calculator to use in my case: https://clincalc.com/stats/samplesize.aspx
Any help will be appreciated.
Answer: Time will severely affect adherence - as you saw you got really high adherence even in the control group, but one would not expect that to last for months (I assume your pilot was just a few weeks). Thus, it really matters how long your trial is. Additionally, calculating adherence over a longer time period will also reduce day-to-day variability (while at the same time potentially increasing variability as people may start to behave differently).
If you perform a long enough trial you may be able to treat the proportion of days adherent as approximately normal* (a lot of hand-waving involved), so you'd primarily need to know what difference between groups you would expect and how much residual variability in the outcome (after adjusting for baseline and the treatment group) you would have. The first you would really need to guess, because your pilot likely won't help you there (your sample size is very small leading to noisy estimates and importantly the difference would likely be different over a longer trial). The second you can get a guess from your pilot (with all the difficulties of extrapolating to a longer trial). You may also wish to see whether the published literature can give you a good idea.
* This is assuming a linear regression (ANCOVA) adjusted for baseline to estimate a treatment difference, which may well be good enough. For the actual analysis you might wish to consider a random effects model for binomial data, but you would have to simulate to get a sample size for that.
If you can get a consultation with the statistics group in your institution that would be very helpful, because this is not a straightforward problem.
Comment: Thanks. So basically what I need to be able to get an estimate sample size is the difference between control and intervention group, but in a larger scale? So if I can find some existing research that has results from a larger study participants then I can use that?
Comment: That would be a plausible approach, particularly if your intervention is similar / should in your judgement should likely have a similar effect. You also need the variability if the outcome, which can also be back calculated from the type of data people tend to publish.
Comment: Sorry but have another question, once I've found the larger data from existing similar literatures, with the data on adherence rates, what kind of calculation should I use to calculate the sample size? Sorry I'm a complete beginner in statistics
Comment: A sample size calculation for a two sample t-test may give you a reasonable answer, but consulting a statistician at your institution in depth would be a good idea.
Comment: Yeah I've sent email to my uni's statistician, but still awaiting response. So I thought I might come online and ask around first. Thanks for your help

Sample size needed?


Integrar fb no app ios swift

Question: Gente boa tarde tudo bom ?
Gostaria de saber se ao integrar o fb sdk no meu projeto ios swift se ao usuario logar  tenho acesso a lista de amigos dele ?
E aproveitando a pergunta, alguem teria algum tutorial sobre a integração ?
Obrigado
Answer: Consegue sim, desde que ao fazer a autenticação com o Facebook você solicite a permissão user_friends para ter acesso a lista de amigos.
A request para pegar a lista de amigos é a seguinte:
let meRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: nil)
meRequest.startWithCompletionHandler({ (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
   if (error != nil) {
       println(result) // Lista de amigos (paginada)
   }
})

Um ótimo lugar para começar com a integração com a o SDK do Facebook, é a própria página deles: Facebook SDK for iOS - Getting Started
Comment: Hmmm ok muito obrigado ... Irei ver

Integrar fb no app ios swift


iPhone sdk - Use a custom camera

Question: I'm developing an app that needs to take two pictures in a row. I'm currently using the iPhone camera but :

I would like to NOT have the cancel
button on the bottom left
I would like to NOT have the preview of my picture (with the blue
button "use").

What should I do ? Should I make my own camera ? I couldn't find an easy tutorial for a custom camera with only a "take picture" button...
Comment: Try this http://stackoverflow.com/a/34433045/3908884
Answer: Create a UIImagePickerController from code, adjust its properties, add an overlay onto it, and with you controller, control whatever you want on that overlay: custom controls, overlaying images, etc...
That gives something like this :
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
self.picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
self.picker.showsCameraControls = NO;
self.picker.navigationBarHidden = YES;
self.picker.toolbarHidden = YES;
self.picker.wantsFullScreenLayout = YES;

// Insert the overlay
self.overlay = [[OverlayViewController alloc] initWithNibName:@"Overlay" bundle:nil];
self.overlay.pickerReference = self.picker;
self.picker.cameraOverlayView = self.overlay.view;
self.picker.delegate = self.overlay;

[self presentModalViewController:self.picker animated:NO];

OverlayViewController is the controller that you must write to control everything you add onto the overlay.
pickerReference is a property you can keep to send orders to the camera. For example, you could call the following from an IBAction coming from a UIButton placed onto the overlay:
[self.pickerReference takePicture];

Answer: The easiest way to do it is to use UIImagePickerController with showsCameraControls set to NO and a custom view set in cameraOverlayView; this view can have whatever buttons you need on it. When touched, the button should call takePicture on the image picker, and when you're done just use dismissModalViewControllerAnimated: to dismiss the picker.

iPhone sdk - Use a custom camera


Subgroups of $SO(4)$ with free transitive action on $S^3$

Question: By considering $S^3$ as the group manifold of $SU(2)$, the ordinary action of $SO(4)$ on the three sphere can be written as the $SU(2)\times SU(2)/\mathbb{Z}_2$ given by the group action of multiplication on the left and right:
$(g,h).x=gxh^{-1}$
From this, there are two obvious subgroups acting freely and transitively on the sphere, by restricting to left and right multiplication.
My question is, are there any others?
Of less importance to me directly, but perhaps more general interest, is the generalisation: How many subgroups of $SO(n)$ act freely and transitively on $S^{n-1}$?
For n=2, there's 1: $SO(2)$ itself.
For n=3, there are none.
For n=4, perhaps 2?
Thanks!
Comment: It is very rare for an action to be free and transitive - in fact, if a Lie group $G$ acts on $M$ freely and transitively, then $M$ and $G$ are diffeomorphic.  Since the only spheres which are Lie groups are $S^0$, $S^1$, and $S^3$, you've essentially exhausted all the examples.  If you relax your question to just *transitive* actions, then you get much more interesting examples...
Comment: Sure, thanks Jason. So it's clear that I'm looking for $SU(2)\subseteq SO(4)$. In that context, the question is whether there are any more than 2 ways to imbed $SU(2)$ inside $SO(4)$, and if not, how to prove it?
Answer: There are precisely two ways, up to conjugacy, of embedding $SU(2)$ into $SO(4)$.  The restriction of the natural action of $SO(4)$ to either of these $SU(2)$s gives a free, transitive action of $SU(2)$ on $S^3$.
To see this, first note that the images of the two $SU(2)$s in $SO(4)$ which you've found are not conjugate in $SO(4)$ (because they are both normal in $SO(4)$, being the images of normal subgroups in $SU(2)^2$).  However, any other subgroup of $SO(4)$ which is isomorphic to $SU(2)$ is necessarily conjugate to one of these two.  Here a sketch of why that's true.
Consider an injective homomorphism $\overline{f}:SU(2)\rightarrow SO(4)$.  By the lifting criteria for covering maps, there is a unique lift $f:SU(2)\rightarrow SU(2)\times SU(2)$ of $\overline{f}$ with the property that $f$ maps the identity to the identity.  One can easily show that $f$ must also be an injective homomorphism.
I claim that there are only two such $f$, up to conjugacy, for which $\pi \circ f:SU(2)\rightarrow SO(4)$ is an injective homomorphism.  Establishing this, because $\pi\circ f = \overline{f}$ (where $\pi:SU(2)^2\rightarrow SO(4)$ is the double covering map), this implies there are at most two such $\overline{f}$ up to conjugacy.
First, it's clear that there are at least two such $f$ given by the inclusions into each $SU(2)$ factor of $SU(2)^2$.  Since these factors are both normal, they are not conjugate to each other.  Now we show that these are the only two.
For this, notice that a map $f:SU(2)\rightarrow SU(2)^2$ is really given as a pair of maps $(f_1,f_2):SU(2)\rightarrow SU(2)^2$, where $f(A) = (f_1(A), f_2(A))$, so this reduces the problem to understanding all maps $f_1:SU(2)\rightarrow SU(2)$.  If both $f_1$ and $f_2$ are trivial, then $f$ is not injective, so we assume wlog that $f_1$ is nontrivial.
We interpret $f_1$ as a $2$-d representation of $SU(2)$.  But the representations of $SU(2)$ have been completely classified - every representation breaks into a direct sum of so-called irreducible representations, and there is a unique irreducible representation of every (complex) dimension.  Because $2=2$ and $2=1+1$ are the only parititions of $2$, $f_1$ is equivalent, as a representation, so either the trivial representation or the standard representation.  Since it's not trivial, $f_1$ is equivalent to the standard representation.
Mal'cev has proven that for maps into $SU(n)$ (and in fact, maps into $U(n), Sp(n), SO(2n+1)$, but not $SO(2n))$, the induced representations are equivalent iff the images are conjugate.  Thus, applying this to $f_1$, we know that $f_1(A) = BAB^{-1}$ for some $B\in SU(2)$.
Working back to $f$, we now know $f$ either has the form $f(A) = (BAB^{-1}, CAC^{-1})$ for some $B, C\in SU(2)$, or $f(A) = (BAB^{-1},I)$ for some $B\in SU(2)$.  In the first case, we note that $f(-I) = (-I, -I) = -(I,I)$, and hence, $f(-I)\in \ker \pi$.  This implies $\overline{f} = \pi \circ f$ has nontrivial kernel, a contradiction.  Hence, $f(A) = (BAB^{-1},I)$ for some $B\in SU(2)$.  This proves there are precisely three nontrivial homomorphisms from $SU(2)\rightarrow SU(2)^2$, but only 2 which give injective homomorphisms $SU(2)\rightarrow SO(4)$.
Comment: Great answer, thanks! The reason I was interested in this was in looking for homogeneous vector fields on homogeneous spaces. I suspect that this reduces to finding free transitive actions, though I've not managed to convince myself. I've just posted another question on that if you're interested.


Facebook : No permission to publish the video

Question: I am trying to upload video using c# facebook graph api, and its working fine for user development account, i am able to post on wall, but when i try to other user i am getting error :
(OAuthException - #100) (#100) No permission to publish the video
This is my sample code
**var fb = new Facebook.FacebookClient(token);
            dynamic parameters = new ExpandoObject();
            parameters.source = new Facebook.FacebookMediaObject { ContentType = "video/mp4", FileName = "video.mp4" }.SetValue(File.ReadAllBytes(@"D:\home\site\wwwroot\\Videos\abc.mp4"));

            parameters.title = "test title";
            parameters.description = "test description";
            dynamic result = fb.Post("/me/videos", parameters);**

where i set the permission
**scope=publish_actions**

Please help me, Thank you in Advance.
Comment: are you trying with a user who is not admin, developer or tester of the app?
Answer: In order to make publish_actions work for other users without a role in the App, you need to go through Login Review. Everything you need to know about that is in the docs: https://developers.facebook.com/docs/facebook-login/review
If you are indeed trying with an App Admin/Developer/Tester and it still does not work, debug the Access Token in the Debugger and make sure publish_actions is authorized correctly: https://developers.facebook.com/tools/debug/
Comment: why not? back then (2015) it was correct. publish_actions is deprecated now though.
Comment: Does not answer the question


How to not show single quote in id attribute

Question: I'm using MVC3 Razor view.
I have following code
@{
var count =0;
<input type="text" id="name'@count'" />

// Some more html elements

}

Now, when i view this html in browser the ID of text element is showing id="name'0'"
How to not show the single quotes in id attribute.
Like this
id="name0"

Please help me with this..
Answer: This should solve your problem:
@{
    var count= 0;

    <input type="text" id="name@{@count}" />
}

Answer: Try some thing like this
<input type="text" id="Name@(@count)" />

Answer: if you are doing it in a javascript file ,while defining you id make use of '+' operator
Ex: id="name"+"@count"
Comment: It is not Javascript, please check the Tags


Converse of Cauchy Integral Formula

Question: The Cauchy Integral Formula for a disk is stated as follows:
Let  $f$: D $\to \mathbb C$ and $ z_0\in D$ If $f$ is analytic, then for every $ r\gt0$ with $\overline{B_r(z_0)} \subset D$ we have:
$$f(z)=\frac{1}{2\pi i}\int_{\partial B_r(z_0)}\frac{f(w)}{w-z}dw$$
Is the converse true? That is, are all functions that satisfy this integral equation, automatically analytic? Or is there some function that satisfies this relation, but is not analytic?
Answer: I believe the answer is yes, as you can move the $\frac{\partial}{\partial \overline{z}}$ operator through the integral sign, and since $\frac{\partial}{\partial \overline{z}}(\frac{f(w)}{w-z})=0$, we have $\frac{\partial}{\partial \overline{z}}f(z)=0$, i.e $f$ is holomorphic.
Another argument is to expand $\frac{f(w)}{w-z}$ as a power series (I forget how it goes exactly, but it is in every complex variable book) and this shows that $f(z)$ is analytic. And this is precisely the argument that shows analytic and holomorphic are the same thing.
Answer: Yes. The cleanest proof (that is, the proof where actually justifying the picky details is easiest) is probably using Morera's Theorem.

Converse of Cauchy Integral Formula


Small bore trombone in philharmonic orchestra - Berlioz symphonie fantastique

Question: I was listening to this recording of Berlioz symphony by the French orchestra "Orchestre philharmonique de Radio France".
After having a laugh about the clarinetist suffering from the trumpets (see 41:51), I noticed at 42:53 that all trombone players are playing on trombone without F attachment, meaning (usually) a smaller bore than most F-attachment trombone. I rarely see philharmonic orchestra with these instruments, except for older pieces of course where you could get sackbut-type instruments.
Given that Berlioz is a relatively recent composer (the trombone was well establish at this time) why would the player use these instruments ? They are usually less-round instruments, not perfectly suited for classical setting (at least that is my understanding). I'm pretty sure it is voluntary, but it's not something I can find in other recordings :

A recording by Frankfurt Radio symphony, playing with F-attachment
A recording by the French national orchestra, playing with attachment
A recording by Radio France & Simon Bolivar Youth orchestra of Venezuela (more clearly), all playing with attachment, except one that seems to be an alto trombone at one point

But I also found another recording by Radio France, different conductor, where they still use trombone without F-attachment.
Anyone care to enlighten me?
Comment: Hey, at least they weren't using valve trombones :-) .
Answer: French composers at that time were writing for smaller, tenor trombones.

Remember, too, that Franck was not writing for a bass trombone, but, as most French composers of the time, for three tenors, which makes his foray into the high range more understandable. Even Berlioz wrote rarely for bass trombone (the only example I have found is in his "Funeral and Triomphe Symphonie"). The Symphonie Fantastique was NOT composed for bass trombone, and the effect of the pedal b flats is quite different on today's .563 bore bass trombone bazooka than on the small, 6.5 inch bell, .515 bore pea-shooter that would have been used (I had two trombones owned by Rochut that he brought to the US when he joined the BSO in 1925 - I gave one to BSO principal trombonist Toby Oft in 2009 on the occasion of his getting tenure in his position with the orchestra - they are tiny, tiny, tiny. When he left for France again in 1929, he took with him a nice big Bach and left his Lefevre trombones behind.). For a taste of the sound Berlioz probably heard (let's not get too far into the "historical instrument" thing, though), listen to Norrington's recording of Fantastique with the London Classical Players. The pedals on the small tenor are frightening! ([SOURCE][1])

Toby Oft's (Boston Symphony Orchestra Principal Trombone) webpage is specific about using a smaller trombone for this piece.

Bach 36G (straight)   Berlioz: Phantastique, Ravel: Bolero & Le Enfant, Jazz or Latin Pops repertoire

[1]: http://www.yeodoug.com/resources/faq/faq_text/scores.html#:~:text=The%20Symphonie%20Fantastique%20was%20NOT,small%2C%206.5%20inch%20bell%2C%20.&text=When%20he%20left%20for%20France,his%20Lefevre%20trombones%20behind.)
Comment: Amazing references :) For those interested, here is the recording mentioned, with the frightening pedal notes on small bore trombone (https://youtu.be/MTPA5Da_4gQ?t=120)
You also made me discover the 1930 recording of Bolero's Ravel, with such an unusual trombone interpretation (https://youtu.be/M5FBiQX2p2s?t=509) Thanks!
Comment: small follow up question, in your experience who would make the call to chose the straight tenor : the musicians or the director. My guess would be the director with the musicians giving their opinion.
Comment: @ThomasLesgourgues Regarding the decision on which trombone to use, I genuinely don't know. It would make an interesting question on its own (but check to see if it's been asked before. I have a vague memory of seeing a similar question). Glad the answer was helpful to you.
Answer: Perhaps the clarinettist in your first clip provides a clue.   Berlioz made great use of the brass.  But was the required sound as heavy as would be produced by today's wide-bore instruments?  The clarinettist would have been blown out of the room!
Those instruments are reasonably authentic for Berlioz's time.  More interesting, perhaps, is the lack of a bass trombone.  Berlioz "declares the lack of bass trombones in Paris a misfortune."  Perhaps this also is authentic?
https://music.allpurposeguru.com/2019/05/berlioz-on-the-trombone/
The Amsterdam Concertgebouw retained the old G bass trombone longer than some.  I have a recording of Tchaikovsky 5 where the low E 6 before H in the last movement has a wonderful rasping fartiness that could only have come from such a 'peashooter'.


drush config-status on translation / language config files?

Question: Similar with but not the same as How to use drush config:set for translations?, is there a way to scan for a site's language config changes via drush or so?
I have a lot of sites on the same server (multi-site), and I would rather check on this via a drush command than having to log in each of the sites to look at the output of /admin/config/development/configuration.
For normal config changes I could run drush cst | config-status but this doesn't appear to work for language config and puts the site at risk of accidentally wiped out language config when not captured.
Example:

$ drush cst -- returns nothing

$ drush cget language.fr:block.block.claro_breadcrumbs
settings:
  label: 'Breadcrumbs FR'

Comment: AFAIK, everything shown on `/admin/config/development/configuration` IS shown in `drush cst`.  If you are talking about the translations that can be exported to `.po` files, those won't be shown by Drush, but those aren't affected by configuration import/export either.
Comment: Thanks, I have updated the question with an example
Answer: The config-status command doesn't show the config's relevant collection, which is how I got confused, but @Patrick Kenny is right, the output does list the language config files.
One solution would be to create a custom drush command similar to Drush\Drupal\Commands\config\ConfigCommands, and alternatively config-import does highlight the collection. So one can run drush cim | config-import without proceeding after the confirmation prompt, so you don't lose the config:
$ drush cst -- does not show collection
------------------------------- ------------
 Name                            State
------------------------------- ------------
 block.block.claro_breadcrumbs   Only in DB
------------------------------- ------------

$ drush cim -- does show collection
+-------------+-------------------------------+-----------+
| Collection  | Config                        | Operation |
+-------------+-------------------------------+-----------+
| language.fr | block.block.claro_breadcrumbs | Delete    |
+-------------+-------------------------------+-----------+

Import the listed configuration changes? (yes/no) [yes]:

Comment: `drush config:import --no` seems to do the trick


Empty field collection in hook_node_presave with entity_metadata_wrapper

Question: I have a node with a field type field_collection which has 2 items:
<code>$node->field_field_collection['und'] = array(
  0 => array('value' => 1),
  1 => array('value' => 2),
);
</code>
on the save node drupal fire hook_node_presave:
<code>/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  $ewrapper = entity_metadata_wrapper('node', $node);
  $wrapper_counter = 0;
  $node_counter = 0;
  foreach ($ewrapper->field_field_collection->getIterator() as $delta => $fc_wrapper) {
    $wrapper_counter++;
  }
  foreach ($node->field_field_collection['und'] as $key => $value) {
    $node_counter++;
  }
}
</code>
after runing code
<code>$wrapper_counter = 0;
$node_counter = 2;
</code>
what am I doing wrong?
I want to walk the field collection using entity_metadata_wrapper.
Drupal: 7.34
Entity API: 7.x-1.5
Field collection: 7.x-1.0-beta8
Comment: `EntityListWrapper` is iterrable, why the need for `->getIterator()`?
Comment: how to use it ?
Comment: I don't understand the question. If your question has changed, please click the "edit" link and update it that way
Comment: how do I bypass the "field collection" using your answer?
"EntityListWrapper is iterrable, why the need for ->getIterator()?"
Comment: It wasn't an answer, it was a comment asking you to clarify your choice to use `getIterator()`
Comment: to calculate the amount of field collection item
I hook_node_presave walk this way
(using "foreach ($ewrapper->field_field_collection->getIterator() as $delta => $fc_wrapper)")
the field collection and in the loop calculates the sum.

at some point, after you upgrade modules field_collection or entity this approach stopped working..
perhaps it is something else, I want to know..

it should be noted that in other "places" (not hook_node_presave) this method works perfectly
in this case, it turns out that in the object $node the data in field collection is,
and when using wrapper access lost..
Comment: @Clive was just saying that you can use "foreach ($ewrapper->field_field_collection as $delta => $fc_wrapper)" instead.  You don't need ->getIterator().
Answer: By this way as per this post:
<code>/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  if ($node -> type == 'my_type') {
    $field_field_collection = field_get_items('node', $node, 'field_field_collection');
    foreach ($field_field_collection as $key => $value) {
      $fc_wrapper = entity_metadata_wrapper('field_collection_item', $value['entity']);
      $fc_name = $fc_wrapper -> field_field_collection_name -> value();
      dsm($fc_name);
    }
  }
}
</code>
See: Understanding Field Collection Values and Entity metadata wrappers pages.


O que é monkey patch?

Question: O que é monkey patch em programação e qual a utilidade e o risco de utilizar tal técnica?
Esse conceito varia de tecnologia pra tecnologia, de linguagem pra linguagem ou do que?
E um outro questionamento: por que esse nome tão esquisito?
Comment: Link para leitura: http://blog.locaweb.com.br/artigos/desenvolvimento-artigos/monkey-patch-sim-nao-quando/
Comment: Adorei a etimologia da palavra segundo a Wikipedia: https://en.m.wikipedia.org/wiki/Monkey_patch
Answer: O que é monkey patching?
O termo, que tem um nome estranho, se refere à quando você modifica ou estende o comportamento de uma aplicação em seu tempo de execução. O termo de forma popular é chamado de monkey patching, mas tecnicamente dynamic runtime patching.
O termo já era conhecido, mas o Google Trends mostra que se popularizou com o Ruby, linguagem que permite o monkey patching de forma ridiculamente fácil. Veja:
puts "vnbrs".upcase

class String
  def upcase
    "Você foi trollado pelo monkey patching!"
  end
end

puts "vnbrs".upcase

O output:
VNBRS
Você foi trollado pelo monkey patching!

Perceba que o comportamento da classe String foi alterado em tempo de execução, visto que consegui sobrepor um método da classe.
Por que é perigoso?

Sim... pode ser bem perigoso.
O Ruby, assim como o Python, tem a premissa de que o programador sabe o que está fazendo, então coisas como essa ficam mais acessíveis. Em linguagens como Java e C#, o processo fica um pouco mais restrito. Há quem diga que é uma proteção contra a maior ameaça de uma aplicação: o desenvolvedor.
Mas sim, monkey patching pode ser perigoso como nesse caso da String. Há alguns usos, como já citaram em outras respostas, para utilizar como workaround de algum bug ou comportamento estranho nas aplicações, mas que pode, se mal-executado, complicações maiores.
O Wikipedia traz algumas informações legais sobre os altos e baixos do monkey patching. Se ele for mal documentado, pode causar problemas:

Pode causar divergências de autualização quando o objeto que foi "monkeypatcheado" assume coisas sobre o objeto original que não necessariamente são verdade após as atualizações. Isso pode quebrar o monkey patching, e por consequência, a aplicação.
Se duas partes da aplicação tentam fazer monkey patch no mesmo objeto, o último que executar será o ganhador da corrida. Isso pode causar confusão.
Pode causar divergências entre o código original e o comportamento de fato, se o programador que está lendo não sabe do patch.

Mas... monkey patching pode ser útil também.
Platão disse:

Não há nada bom nem mau a não ser estas duas coisas: a sabedoria que é um bem e a ignorância que é um mal.

Quase tudo tem uma parte boa.
E por mais que tenha quem não goste, o monkey patching pode ser bastante útil para quem escreve testes automatizados. Um pequeno exemplo em Ruby de um teste:
# ./user_service.rb
module UserService
  extend self

  BASE_URI = "https://api.brasil.gov.br/"

  def fetch(username)
    response = HTTP.get("#{BASE_URI}/pessoas/#{username}")
    JSON.parse response
  end
end

# ./user_service_spec.rb
class HTTP
  def self.get(url)
    '{"username":"vnbrs","name":"Vinicius Brasil"}'
  end
end

describe UserService do
  subject { UserService.fetch("vnbrs") }

  it "returns the user" do
    expect(subject.name).to eq "Vinicius Brasil"
  end
end

Fazendo monkey patching na classe de HTTP, é possível criar um mock para os testes.
Adoção
O C# tem algo como "monkey patching" através dos Extension Methods, o que não permite modificar, porém adicionar comportamento. É seguro e amigável para o desenvolvedor. Não é bem monkey patching pois não te deixa mudar comportamento, mas sim estender, e a nível de compilação.
Em outras linguagens que não tenham um suporte tão claro para extensão ou modificação em tempo de execução, existe a metaprogramação e a reflexão, que podem dar algum tipo de flexibilidade nesse sentido.
Python, por exemplo, assim como Ruby, dá uma grande flexibilidade para monkey patching, vez que as classes são mutáveis e os métodos são meros atributos. Veja o exemplo em Python:
class Pessoa:
    def falar_oi():
        return "Oi!"

Pessoa.falar_oi()
# => "Oi"

Pessoa.falar_oi = lambda: "Não quero!"

Pessoa.falar_oi()
# => "Não quero!"

Por que é chamado assim?
A etimologia do termo é meio obscura. Poucas fontes falam sobre, mas é comum ouvir que monkey patch vem de guerrilla patch, referindo-se à modificar o comportamento às escondidas, de forma sorrateira. Virou monkey pois guerrilla tem a pronúncia quase idêntica à gorilla.

We talked about sneaking in and altering Python code at runtime; the
  term Guerrilla Patching was used because sometimes dynamic patches
  could interfere and conflict. Conflict -> Guerrilla warfare, as the
  conflict was dynamic and depended on the terrain. [fonte]
Answer: É uma gambiarra que permite modificar uma aplicação quando ela está rodando ou fora do contexto normal dela. Ela é necessária para consertar problemas ou modificar um comportamento que a aplicação não permite.
É possível modificar os fontes quando se tem para resolver um bug.
Quando o software atualizar você vai perder esse patch.
Em sistemas como o Protheus por exemplo se faz muito isso, sem mexer nele fora do normal não consegue usar. Cada modificação que eles te mandam tem um problema novo e você que tem que consertar.
Comment: Oi Jefferson, é o dia todo todo dia fazendo isso, é triste.
Comment: Não sabia que esses _patches_ no Protheus costumavam dar tanto problema

O que é monkey patch?


Ocultar segundo elemento de um conjunto de classes

Question: Considere o seguinte código:

       Nome da Categoria

          Por Autor

      Quero ocultar esse conteúdo aqui/a>

          Por Autor

Estou tentando ocultar o conteúdo da segunda classe category-link do article:
Tentei duas formas diferentes, mas não deu certo, vejam:
article div:nth-of-type(2) .category-link a {
   display: none;
}

article div:nth-of-type(2) span .category-link a {
   display: none;
}

Onde eu estou errando?
Answer: Use nth-child(2) direto na classe .entry-meta como abaixo. E tem um  no seu código que vc escreveu errado...
Mas o seu problema é que vc escreveu span .category-link e deveria ser span.category-link  com a tag.classe, sem o espaço.

.entry-meta:nth-child(2) {
  background-color: red;
}
.entry-meta:nth-child(2) .category-link {
  display: none;
}

    Nome da Categoria

      Por Autor

    Quero ocultar esse conteúdo aqui

      Por Autor

Comment: Show! Muito obrigado.
Comment: @Luis sem problemas meu caro, tmj!


Deletar um registro do firebase auth

Question: Preciso deletar um registro do Firebase Auth, estou usando o seguinte código:
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

        }
    });

Porem está dando um erro:

java.lang.NullPointerException: Attempt to invoke virtual method
  'com.google.android.gms.tasks.Task
  com.google.firebase.auth.FirebaseUser.delete()' on a null object
  reference

Alguém sabe o que estou fazendo de errado ou como eu deleto um registro do Firebase Auth?
Comment: `user`certamente é nulo. Você não tem um usuário logado com essa instância do FirebaseAuth. Se você quiser deletar um usuário específico e não o próprio usuário conectado (que nem um adminstrador/superuser) use o Firebase Console.
Comment: Eu quero deletar o usuario q está corrente, por exemplo... após ele sair de uma pagina de validação de login, sem ter validado utilizando um código que é enviado por sms(tudo pronto até aqui), o usuário dele é deletado do banco, pois ele não terminou seu cadastro.
Comment: Entendi. Mas seu FirebaseAuth não tem nenhum usuário, talvez ele nem mesmo tenha sido criado em primeiro lugar.
Answer: Muito provável que o user esteja retornando null.
A causa dele estar retornando null pode estar ligado a Autenticação. Você está autenticando o usuário?
Faça uma validação na sua Activity conforme exemplo abaixo:
@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}

Adicione o task.isSuccessful() no seu método user.delete() para validar:
user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "User account deleted.");
            }
        }
});

Fontes:
Get Started with Firebase Authentication on Android
Gerenciar usuários no Firebase
Comment: Esse metodo "updateUI" não existe! estou usando o Firebase Auth 'com.google.firebase:firebase-auth:11.8.0'
Comment: Que estranho, é pra existir, veja se não falta algum _import_.

Deletar um registro do firebase auth


Django reverse query by the last created object

Question: I have two models:
class SomeActivity(models.Model):
    name = models.ChartField(max_length=100)

class SomeStatus(models.Model):
    name = models.CharField(max_length=100)
    status = models.IntegerField(choises=STATUS_CHOISES)
    some_activity = models.ForeignKey(SomeActivity, related_name='statuses')

The last created status for the activity is the current one. To get it I use this code:
try:
    last_status = some_activity.statuses.latest('id')
except:
    last_status = None

But the problem is when I want to make a query that returns all Activities that have a last_status matching status__in=[1, 2].
Comment: What's the list [1,2]?
Comment: status from the SomeStatus object. I  edit the question to be more clear.
Answer: This solution is a little twisted, but I think it will work:
from django.db.models import Max

max_status_ids = SomeActivity.objects.filter(statuses__isnull=False).annotate(
              last_status_id=Max('statuses__id')
              ).values_list('last_status_id', flat=True)
status_satisfied_ids = SomeStatus.objects.filter(id__in=list(max_status_ids),
              status__in=[1, 2]).values_list('id', flat=True)
activities = SomeActivity.objects.filter(statuses__id__in=list(
              status_satisfied_ids))

I hope there is a better solution.

update
Try
max_status_ids = SomeActivity.objects.annotate(last_status_id=Max('statuses')
                                    ).values('last_status_id')
activities = SomeActivity.objects.filter(statuses__in=max_status_ids,
                                         statuses__status__in=(1,2))

Django automatically generates sub-query when qs, qs.values() or qs.values_list() is used after __in lookup. Thus there is no need to wrap the querysets w/ list() (which also introduces unnecessary evaluation and thus unnecessary intermediate SQLs) or to write flat=True inside qs.values_list()
statuses__id__in lookup inside activities already introduces a table join, thus it's bette to move status__in from status_satisfied_ids into activities to take advantage of the join. Or else, status_satisfied_ids would introduce extra select.

Or you could use Window functions of PostgreSQL to filter by ranked position directly.
Comment: @okm I read the doc of 1.4, https://docs.djangoproject.com/en/1.4/ref/models/querysets/#in the end of this section, django recommend split the queries using mysql, I do not know it will be better in pg.
Comment: Just test in Postgres w/ two tables having 100k rows. 'in' clause is slowest: whole => 3200ms, limit 10 => 800ms, offset 50000 limit 10 => 2950ms; self-join: whole => 650ms, limit 10 => 0.3ms, offset 50000 limit 10 => 620ms; window function: whole => 510ms, limit 10 => 310ms, offset 50000 limit 10 => 440ms. We can see none of the above methods performance quite well in real time for large tables, we should add cache or de-normalized field if the operation is frequent.
Comment: I don't know what level of performance the MySQL would achieve, they say it's bad. Normally Postgres works fine on this kind of job -- for not-that-large tables. For large tables, `in` subquery is still slower than [self-join](http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/) or window function. Second, large `in` clause doesn't perform well, neither [in MySQL](http://www.xaprb.com/blog/2006/06/28/why-large-in-clauses-are-problematic/) or Postgres.


Probability of Sequentially Drawing Balls 1, 2, and 3 from an Urn Containing n Balls

Question: I'm new to probability theory. I'm trying to do some exercices as the one suggested below but I've come across a solution that I didn't quite understand. Can you, guys, help me figure this out?

An urn contains $n$ balls numbered from 1 to $n$, where $n \geq 3$. Without replacement, we draw one ball at a time from this urn. All balls are indistinguishable by touch.
What is the probability that balls 1, 2, and 3 are drawn consecutively and in that order?

I went like this:
First, I would like to point out that in this random experiment, the assumption of equiprobability is clearly satisfied because the balls are identical and indistinguishable by touch.
When we draw n balls one by one from an urn containing a total of n balls, the number of possible outcomes corresponds exactly to the number of combinations of n elements.
In other words: $\text{card}(\Omega) = n!$, where $\Omega$ is the set of all possible outcomes.
We have n-2 possible outcomes for the first ball to be ball number 1 since it cannot occupy the positions "$n-1$" and "$n$".
We have one possible outcome for the second ball to be ball number 2, following ball number 1.
We have one possible outcome for the third ball to be ball number 3, following ball number 2.
Therefore, the number of possible outcomes corresponding to obtaining balls 1, 2, and 3 in this consecutive order is $(n-2) \times 1 \times 1$.
Thus, the probability is equal to $\cfrac{n-2}{n!}$.
However, the suggested solution is that the probability is equal to $\cfrac{(n-2)(n-3)!}{n!}$ but there is no explanation why.
Comment: You want to count the arrangements of $\{1,\cdots, n\}$ where $1,2,3$ appear consecutively. If an arrangement is of this form, then as soon as you know where $3$ is, you know precisely where $1,2$ are, and there's no freedom in their placement. Of course, $3$ itself can appear anywhere (upto being preceded by $1,2)$. So, the total number of such arrangments is just the number of arrangements of $\{3,\cdots, n\},$ i.e., $(n-2)!$.
Answer: Let me just give an example.
Suppose $n=5$.
Then there are $5!=120$ possible orders and there are $3\times2!=6$ favorable orders:

12345
12354
41235
51234
45123
54123

Factor $3$ corresponds with the number of ways we can place string 123 and factor $2!$ with the number of ways we can order 4 and 5.


Fscanf incrementing file position pointer wierdly

Question: This is the part of the code that's working as not as intended (well at least as I was expecting too).
 fscanf(**readFile,"%d", buffer.head);

**readFile is a pointer-to-pointer pointing to the file I've opened. In the file there are numbers written one below another like this:
1

2

3

4

5

6

7

8

9

10

What is weird is that when I print out position of the file pointer with :
 printf("Position %ld", ftell(**readFile));

I'm getting odd numbers : 1 3 5... which means every time I run  fscanf(**readFile,"%d", buffer.head); in a loop, file pointer will not be pointing to next number (e.g. 2), rather it will point to 3rd number(3). I can't figure out what am I doing wrong.
Comment: Maybe show some more of the relevant code?
Comment: So readFile is a (File **)?
Comment: Isn't it odd to declare `FILE` pointer like that ?
Comment: It's a pointer declared as local variable in main passed to a function that creates a thread running this part of the code.
Answer: File positions are in bytes. You don't specify the exact format of your text file, but assuming single-byte line termination (on e.g. Unix or Linux) and blank lines between each line like you showed, three bytes per number seems to make sense for the first 9:
Basically the format of your file seems to be:
1\n\n2\n\n3\n\n...

If you're on Windows, and the blank lines are a mistake, the structure would instead be:
1\r\n2\r\n3\r\n...

And it's still three bytes per number for the first 9.
Comment: @SirDrinksCoffeeALot As I tried to explain above, that's because the position is in *bytes*, and there is whitespace between the numbers.
Comment: @SirDrinksCoffeeALot What? No? There'¨s no "nul terminator" with an integer... Are you not handing `fscanf()` a proper `int *` argument? It's hard to know what `buffer.head` is, but it should be a properly initialized `int *` of course.
Comment: Sorry, my bad, i edited numbers how they are stored in .txt file.
Comment: Problem was that i was overwriting memory of the buffer because fscanf is storing nul terminator, now i need to find how to store integer without nul terminator
Comment: Well, somehow `fscanf` is storing newline character into the next place in the buffer which leads to overflow after 5 inputs.


DataGridView carrega os dados mas não exibe eles

Question: Tenho um DataGridView, ele carrega os dados, mas não exibe eles.
private void AtualizarGrid()
{
    //Procura no banco os registro digitado na caixa de pesquisa.
    AlunoDAL alunoDAL = new AlunoDAL();

    //Exibi no Grid os nomes pesquisados no banco de dados.
    var bindingList = alunoDAL.CarregarAlunos();
    AlunosColecao alunosColecao = new AlunosColecao();
    var source = new BindingSource(bindingList, null);

    dataGridViewAluno.DataSource = null;
    dataGridViewAluno.DataSource = source;

    //Atualiza o Grid.
    dataGridViewAluno.Update();
    dataGridViewAluno.Refresh();
}

Comment: O nome das colunas estao iguais as colunas do datagridview?
Por curiosidade debugando voce ve os itens dentro do source?
Comment: Sim estão iguais, sim debugando aparece os nomes, codigo etc
Answer: Solução:
public List<Aluno> CarregarAlunos(int ordernarPor = 0, string parametro = "")
    {
        // 0 id
        // 1 nome
        // 2 apelido

        List<Aluno> alunos = new List<Aluno>();

        string sql = "SELECT * FROM alunos ";

        switch (ordernarPor)
        {
            case -1:
            case 0 :
                {
                    if (parametro != "")
                    {
                        sql += " WHERE IdAluno like @parametro ";
                    }
                    sql += " ORDER BY IdAluno ";
                    break;
                }
            case 1:
                {
                    if (parametro != "")
                    {
                        sql += " WHERE Nome like @parametro ";
                    }
                    sql += " ORDER BY Nome ";
                    break;
                }
            case 2:
                {
                    if (parametro != "")
                    {
                        sql += " WHERE Apelido like @parametro ";
                    }
                    sql += " ORDER BY Apelido ";
                    break;
                }
        }

        MySqlConnection conn = CriarConexao();
        MySqlCommand cmd = new MySqlCommand(sql, conn);

        if (parametro != "")
        {

            cmd.Parameters.AddWithValue("@parametro", "%" + parametro + "%");
        }

        try
        {
            conn.Open();
            MySqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                Aluno aluno = new Aluno();
                aluno.IdAlunoP      = int.Parse( dr["IdAluno"].ToString());
                aluno.NomeP         = dr["Nome"].ToString();
                aluno.ApelidoP      = dr["Apelido"].ToString();
                aluno.SexoP         = dr["Sexo"].ToString();
                aluno.NascimentoP   = DateTime.Parse( dr["Nascimento"].ToString());
                aluno.CPFP          = dr["CPF"].ToString();
                aluno.RGP           = dr["RG"].ToString(); ;
                aluno.CidadeP       = dr["Cidade"].ToString();
                aluno.LogradouroP   = dr["Logradouro"].ToString();
                aluno.NumeroP       = dr["Numero"].ToString();
                aluno.BairroP       = dr["Bairro"].ToString();
                aluno.UFP           = dr["UF"].ToString();
                aluno.CEPP          = dr["CEP"].ToString();
                aluno.AdmissaoP     = DateTime.Parse(dr["Admissao"].ToString());
                aluno.TelefoneP     = dr["Telefone"].ToString();
                aluno.CelularP      = dr["Celular"].ToString();
                aluno.SituacaoP     = int.Parse(dr["Situacao"].ToString());

                alunos.Add(aluno);

            }
            conn.Close();
        }
        catch (MySqlException ex)
        {
            throw new Exception("Erro ao Carregar Grid:" + ex.Message);
        }
        finally
        {
            if (conn.State == ConnectionState.Open) conn.Close();
        }
        return alunos;
    }


fromCharCode equivalent in Power Query

Question: I have a list of values which I would like to convert in Power Query using an equivalent of JavaScript's String.fromCharCode.
Any help appreciated!
Answer: Powerquery:
<code>let Source = {189, 43, 190, 61},
convert = Text.Combine(List.Transform (Source, each Character.FromNumber(_)))
in convert
</code>

https://learn.microsoft.com/en-us/powerquery-m/character-fromnumber

fromCharCode equivalent in Power Query


Unable to load mailparse even with a zz prefix

Question: I've read numerous articles stating that mailparse needs to load after mbstring, however, even when prefixing the mailparse with zz, it still has the same issue and I really am at my wits end in trying to figure out why.
Though I still see it in the list of modules.
[root@intranet:~]# php -m
PHP Warning:  PHP Startup: Unable to load dynamic library     '/usr/lib64/php/modules/zz-mailparse.so' - /usr/lib64/php/modules/zz-    mailparse.so: undefined symbol: mbfl_convert_filter_flush in Unknown on line 0
[PHP Modules]
bz2
calendar
Core
ctype
curl
date
dom
ereg
exif
fileinfo
filter
ftp
gd
gettext
gmp
hash
iconv
imap
intl
json
libxml
mailparse
mbstring
mcrypt
mhash
mysql
mysqli
openssl
pcntl
pcre
PDO
pdo_mysql
pdo_sqlite
Phar
readline
Reflection
session
shmop
SimpleXML
sockets
SPL
sqlite3
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
Zend OPcache
zip
zlib

[Zend Modules]
Zend OPcache

in /etc/php.ini
extension=zz-mailparse.so
Not sure if this is the issue even though I have SSELinux as permissive.
[root@intranet:/usr/lib64/php/modules]# ls -lhZ
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       bz2.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       calendar.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       ctype.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       curl.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       dom.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       exif.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       fileinfo.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       ftp.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       gd.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       gettext.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       gmp.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       iconv.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       imap.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       intl.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       json.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       mbstring.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       mcrypt.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       mysqli.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       mysql.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       opcache.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       pdo_mysql.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       pdo.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       pdo_sqlite.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       phar.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       shmop.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       simplexml.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       sockets.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       sqlite3.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       tokenizer.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       wddx.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       xmlreader.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       xml.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       xmlwriter.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       xsl.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0       zip.so
-rwxr-xr-x. root root unconfined_u:object_r:lib_t:s0   zz-mailparse.so

I am on a RHEL7 server with PHP 5.6.28 and MariaDB 5.5.52
Comment: @magnus - I actually did and it was last year I did it, I and i just purged a lot of stuff and added `remi-php71` repo on the RHEL server and installed php71 and it's version of mbstring and mailparse and I was good to go.  I tried looking at my server history and found nothing but i did find those installs in my yum history.  Where are you stuck right now?  What are your problems?
Comment: Don't use zz. No one likes zz. So called zombie zappers are obviously sleeping.
Comment: I suggest opening a case with Red Hat.
Comment: Worth a shot we already pay for support.
Comment: Did you ever get this sorted? I'm banging my head against the wall with it.
Comment: @JonWeinraub thanks for the reply. I actually solved the problem myself. Using the `nm` tool to extract dynamic link library names for the modules in the PHP modules directory helped. It was the order of dependencies. Lucky for me, because we're stuck with PHP 5.4 in this situation.
Answer: Maybe you include the module twice. Something similar to:
$ /etc/php/7.1/cli/conf.d # ls -lh | grep parse
lrwxrwxrwx 1 root root 41 Feb  7 12:37 20-mailparse.ini -> /etc/php/7.1/mods-available/mailparse.ini
lrwxrwxrwx 1 root root 41 Feb  7 13:03 21-mailparse.ini -> /etc/php/7.1/mods-available/mailparse.ini

Answer: I had the same problem here.
The problem is caused by two facts:

The mailparse.so PHP dynamic link library requires the mbstring.so PHP dynamic link library.
PHP dynamic link libraries ("extensions") are loaded from both /etc/php.ini (and /etc/php-cli.ini) and the files in the /etc/php.d directory in alphabetical order.

There are several solutions:

Ensure that mbstring.so is loaded prior to mailparse.so in php-cli.ini:

extension=mbstring.so
extension=mailparse.so

If you have either extension in a file in /etc/php.d, rename the .ini files themselves so that they are ordered.

mbstring.so

    extension=mbstring.so

zz-mailparse.so

    extension=mailparse.so

Load the mbstring.so module twice. Note that this produces lots of PHP warnings in the logs which I dislike.

mailparse.so

    extension=mbstring.so
    extension=mailparse.so

mbstring.so

    extension=mbstring.so


Using the DB API to test against a trimmed value?

Question: I want to use the DB API (Drupal 7) to do a query like:
select my_field from table where trim(my_field) <> ''

where my_field is a text field.  My goal is to not get any values in the result that are made up of one or more spaces. (This is a greatly simplified example query, but you get the idea.) Is there any way to get that call to trim() in there? The only thing I could imagine trying was:
$query->condition('trim(my_field)', '', '<>');

which doesn't work at all.  Any thoughts?  Thanks!
Answer: You can use SelectQuery::where() for more complex requirements:
$query->where('trim(my_field) <> :val', ['val' => '']);