How to only draw the graph and the Xaxis gridlines using chart.js

Question: I am trying to draw a graph, but the left and the bottom corners keep getting this blank margin. How do I get rid of that? I managed to erase them, but at the same time it erases the gridLines for the X axis. I want to keep the Xaxis gridlines.
Notice that I also want that border around the graph. Didn't find a way to draw the border using the chart.js.
The white spaces are very evidient, right on the bottom and on the left, spacing the gray border away. You can see it on the image:

I tried disabling the ticks display.
My chart so far:

var myChart = new Chart(modalChart, {
          type: 'bar',

          data: {
              labels: ['Total enviado', 'Total recebido', 'total aberto', 'total convertido'],
              datasets: [{
                  backgroundColor: my_gradient,
                  data: [totalEnviado,totalRecebido, totalAberto,totalConvertido]
              }]
          },
          options: {
              legendCallback: function(chart){
                  var text = [];
                  text.push('
');
                  text.push('
');
                  for (var i=0; i<chart.data.labels.length; i++) {
                      console.log(chart.data.datasets[i]); // see what's inside the obj.
                      text.push('
');
                      text.push('' + chart.data.labels[i] + '');
                      console.log(chart.data.labels[i]);
                      text.push('
');
                  }
                  text.push('
');
                  text.push('
');
                  return text.join("");
              },
             legend: {
                  display:false
              },
              scales: {
                  xAxes:[{
                      display: true,
                      categoryPercentage:1.0,
                      barPercentage:1.0,
                      ticks: {
                          beginAtZero: true,
                          display:false
                      }
                  }],
                  yAxes: [{
                      ticks: {
                          beginAtZero:true,
                          display: false
                      },
                      gridLines:{
                        display:false
                      }
                  }]
              }
          }
      });

Notice that I also want that border around the graph. Didn't find a way to draw the border using the chart.js only. This gray border around the graph and the gray borders separating the bars are very important.
Answer: You need to set the drawTicks option to false for both the x- and y-axis:
gridLines: {
  drawTicks: false
}

Working example:

var modalChart = document.getElementById("chart"),
  totalEnviado = 4,
  totalRecebido = 3,
  totalAberto = 2,
  totalConvertido = 1,
  my_gradient = "orange";
// --
var myChart = new Chart(modalChart, {
  type: 'bar',

  data: {
    labels: ['Total enviado', 'Total recebido', 'total aberto', 'total convertido'],
    datasets: [{
      backgroundColor: my_gradient,
      data: [totalEnviado, totalRecebido, totalAberto, totalConvertido]
    }]
  },
  options: {
    legendCallback: function(chart) {
      var text = [];
      text.push('
');
      text.push('
');
      for (var i = 0; i < chart.data.labels.length; i++) {
        console.log(chart.data.datasets[i]); // see what's inside the obj.
        text.push('
');
        text.push('' + chart.data.labels[i] + '');
        console.log(chart.data.labels[i]);
        text.push('
');
      }
      text.push('
');
      text.push('
');
      return text.join("");
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        display: true,
        categoryPercentage: 1.0,
        barPercentage: 1.0,
        ticks: {
          beginAtZero: true,
          display: false
        },
        gridLines: {
          drawTicks: false
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true,
          display: false
        },
        gridLines: {
          display: false,
          drawTicks: false
        }
      }]
    }
  }
});

  <canvas id="chart"></canvas>

Comment: It's been a long time, I forgot to thank you. This worked like a charm in that time. Thanks a lot!


Multithreaded unit test

Question: I have a helper class that validates an XML based on its schema. There are some static methods/function in combination with instance method/functions and I want to test it for thread safety.
What is the best approach to test this helper with MSTest (VS2008) ?
Comment: In general this is possible, but if we arer going to discuss concrete technique - please share a code you want to test
Answer: Perhaps I misunderstand your question, by why not launch multiple simultanious threads to manupulate your class(es) and trap all threading related exceptions before waiting for all threads to finish and then check for concurrency problems in the results?
Answer: In my opinion the best way to unit test threading issues is to predict problems and let your test specifically cause each situation. Unit tests should always produce the exact same result each time they run against the same code.
You may want to check out Microsoft CHESS (http://research.microsoft.com/en-us/projects/chess/) if you do not have a specific problem to test.
Comment: Single tests agains the public methods/functions all pass. But this component failed in production (Biztalk -> Orchestrations). Some times the message was validation succesfully while the message was invalid and vica versa....
Answer: It is kind of hard of doing this, since you can not be sure about how de OS will schedule the threads execution. You tests will most likely randomly fail.
If you can, change your design so you can reduce locks/other synchronization techniques and design for thread safety (for example, not using shared state).

Multithreaded unit test


How to know what changes YUM UPDATE is going to apply?

Question: How to know what changes YUM UPDATE is going to apply?
I know you can see the list of packages that are going to be updated, but I'd like to know what detailed changes are going to be aplied in package.
Comment: What is the motivation behind asking this question? What problem are you trying to solve?
Comment: Always there are many updates to apply, and I wonder what is the faster way to apply them and kown what is going to change in the server. (LAMP)
Answer: There's no out-of-the-box facility to accomplish this. You would need to write a script to do the following:

Run yum update in download-only mode to get the new RPMs
For each package which is being updated:

Get the list of files and their MD5s installed by the current RPM
Get the list of files and their MD5s contained in the new RPM
Compare the lists and print any differences (added/removed/changed files)
Print the preun and postun scriptlets in the current RPM
Print the pre and post scriptlets in the new RPM
Comment: I believe, you have to have the yum-utils package to run yum in download only mode, isn't it.
Comment: @SohamChakraborty Correct.
Answer: Run the update on a separate, identical system and then compare the two to see what has changed.
Though, this probably isn't going to help you answer your real question. This probably is the answer:
Yum keeps a complete history of everything it does, with a full rollback capability. To roll back a change, first run:
yum history

You'll see a numbered list of transactions. Find the number corresponding to the transaction you want to revert, and then do:
yum history undo ###

Comment: Yum history undo is not guaranteed to make your system exactly as it used to be.  Also, yum history undo needs the original packages.
Answer: You can query a package with rpm to see its changelog.
rpm -qp --changelog http://example.org/path/to/package-1.1.0-2.x86_64.rpm

Or you can read on Red Hat's page on Security Updates and read the errata for your server version.
For Red Hat Enterprise Linux version 6 you would read this errata.


Testing for homogeneity

Question: I am analyzing data (see image below) from an fMRI experiment. The dependent variable is activation values (continous) from a specific brain site. There are two conditions, each with two levels of a manipulation (2x2). There is also a covariate (a behavioral measure for how well they the participants did in a behavioral task).
What I want to do is to test for  an interaction for how much the two levels (low & high) for each condition correlate with the covariate. I was told that testing for the homogeneity of regression slopes in ANCOVA can help me answer this question. What I want to see is if the regression slope differences between low & high, differ for Cond 1 compared to Cond 2 (e.g., slopes are similar (between low & high) for Cond 1, but differ for Cond 2, which should be considered an interaction).
I am definitely not a stats wiz, and I am new to R. I checked many forum posts, but the data set used in each experiment differed from mine, so it was hard to interpret the solutions (most include group, where my data is repeated measures). How can I test for the interaction I mentioned in R? Thanks a lot in advance.
Comment: Tried it in the original post but couldn't find a sane way of doing it, with the proper table formatting. Here is a link to the csv file that has the table: https://alabama.box.com/shared/static/irf2d9rtd3481llde4wlco983684lhn6.csv  . Thanks.
Comment: Per this link, https://stats.stackexchange.com/questions/278460/regarding-ancova-and-regression why not just do a multiple regression?
Comment: Are the factors in your 2x2 design between- or within-subjects?
Comment: Within-subjects.
Comment: OK, cool. One more thing: Could you post the data in a way that would let me easily put it into R? Not as a picture, but as text.
Answer: First, you aren't really "testing for homogeneity"; you are testing for an interaction, it seems.
One option for a solution is a linear mixed model. You need to reshape the data from wide to long format first. And then you can run a model predicting the outcome variable (measurement) by the condition (cond), level (level), and covariate (cov). Code is below. I specified cond and level to be random effects, but you could try to specify the random effects structure differently with different nested model comparisons (I laid out elsewhere here).
You could also do a within-subjects ANCOVA, but I prefer linear mixed models. They are more flexible and can handle when the covariate is related to the other factors (I'm not sure if the other factors were measured or manipulated).
> widedat <- read.csv("/Users/markiiwhite/Downloads/dat.csv") # reading in data
> widedat$id <- as.factor(dat$id) # making id a factor
> head(widedat) # checking out data
  id    c1lo    c1hi   c2lo    c2hi    cov
1  1  2.7027  2.7936 2.7422  2.7645 0.5294
2  2 -0.0808 -0.0771 0.0150 -0.1972 1.0000
3  3  2.2013  2.5407 2.4612  2.3019 0.7647
4  4  1.0307  1.1048 0.9500  1.1764 0.8235
5  5  0.3813  0.4553 0.6664  0.0091 0.9412
6  6  0.7322  0.4040 1.8527  0.2983 0.6471
>
> library(tidyr) # loading package to convert to long format
> longdat <- gather(data=widedat, key="condition", value="measurement",
+                   c(c1lo, c1hi, c2lo, c2hi), factor_key=TRUE) # converts data from wide to long...
> # ...responses in each condition (condition 1 hi, condition 2 hi, condition 1 lo, condition 2 lo)...
> # ...recoded into a value named "measurement," with a key variable called "cond"
> longdat$cond <- factor(ifelse(longdat$condition=="c1lo" | longdat$condition=="c1hi", "one", "two"))
> longdat$level <- factor(ifelse(longdat$condition=="c1lo" | longdat$condition=="c2lo", "low", "high"))
> # condition into two factors: cond and level
> longdat <- longdat[,-3] # getting rid of superfluous condition variable
> head(longdat[order(longdat$id),]) # matches the values of the data above
   id    cov measurement cond level
1   1 0.5294      2.7027  one   low
25  1 0.5294      2.7936  one  high
49  1 0.5294      2.7422  two   low
73  1 0.5294      2.7645  two  high
2   2 1.0000     -0.0808  one   low
26  2 1.0000     -0.0771  one  high
>
> library(lmerTest) # loading package for satterthwaite dfs
> library(lme4) # package for multilevel models
> model <- lmer(measurement ~ cond + level + cond*level + cov + (1 + cond + level|id), longdat)
> # measurement predicted by condition (1 or 2), level (high or low), and the covariate (cov)
> # specified random effects for cond and level, nested within id
> summary(model)
Linear mixed model fit by REML
t-tests use  Satterthwaite approximations to degrees of freedom ['lmerMod']
Formula: measurement ~ cond + level + cond * level + cov + (1 + cond +      level | id)
   Data: longdat

REML criterion at convergence: 226.7

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.9676 -0.3400 -0.0879  0.2729  3.2985

Random effects:
 Groups   Name        Variance Std.Dev. Corr
 id       (Intercept) 1.98441  1.4087
          condtwo     0.07425  0.2725   -0.50
          levellow    0.64150  0.8009   -0.75  0.95
 Residual             0.19626  0.4430
Number of obs: 96, groups:  id, 24

Fixed effects:
                 Estimate Std. Error      df t value Pr(>|t|)
(Intercept)        5.3721     1.3261 23.2600   4.051 0.000486 ***
condtwo           -0.1114     0.1395 46.8600  -0.799 0.428558
levellow          -0.1631     0.2076 34.0900  -0.786 0.437314
cov               -5.2231     1.5316 22.0800  -3.410 0.002499 **
condtwo:levellow   0.2675     0.1809 46.0000   1.479 0.146004
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) condtw levllw cov
condtwo     -0.088
levellow    -0.158  0.580
cov         -0.974  0.000  0.000
cndtw:lvllw  0.034 -0.648 -0.436  0.000

Comment: maybe I am being naive, but why not just do a multiple regression with the Covariate as the dependent variable and all the others as independent variables?You could also add the interaction terms between the independent variables in the regression model. I don't see why this is worse then Mixed Linear Model in this case.
Comment: Both factors are within-subjects, not between.
Comment: Ah, so since it is within-subject and not between, there will be alot of interaction, and thus it is better to use a mixed model, correct?
Comment: The standard regression assumes observations are independent of one another. Since people are within all 4 conditions, the non-independence of those observations (i.e., they are all from the same person), needs to be modeled. One way to do this is a multilevel model.

Testing for homogeneity


Dividir números de um int. C++

Question: Ola!
Estou lendo e estudando sobre C++ no livro " C ++ Como Programar 5ª edição ".
Há uma questão na pg 97. Questão 2.28 cujo eu não consigo realizar, sendo ela:
Escreva um programa que insere um inteiro de cinco dígitos, separa o inteiro em seus dígitos individuais e imprime os dígitos separados
entre si por três espaços cada. [Dica: Utilize operadores de divisão de inteiros e módulo.] Por exemplo, se o usuário digitar 42339, o
programa deve imprimir:
4 2 3 3 9.
Pelo que eu compreendi, devo fazer:
#include <iostream>
using namespace std;

int main () {

int x ;
cin >> x; // Digitar cinco números

// eu não faço ideia como separar estes números?
// alguém pede me ajudar?
return 0;
}

Answer: No seu próprio texto tem:

"Dica: Utilize operadores de divisão de inteiros e módulo".

Essa é mesmo a dica. Suponha que você leia o número inteiro 42339, como você mesmo ilustra.
Se você dividir ele por 10, dá quanto?
42339 / 10 = 4233,9

Repare como a vírgula separa o primeiro dígito à direita (não por acaso, a dezena) do seu número original. Em C++, você pode pegar esses valores fazendo:
#include <iostream>
using namespace std;

int main() {

    int num = 42339;

    int dig = num % 10; // módulo (resto da divisão) por 10
    int sobra = int(num / 10); // divisão inteira por 10

    cout << "num: " << num << " dig: " << dig << " sobra: " << sobra << endl;

    return 0;
}

O resultado é esse (veja funcionando no Ideone):
num: 42339 dig: 9 sobra: 4233

Ou seja, pra fazer um passo do que você precisa, basta aplicar essa regra (use o módulo - isto é, resto da divisão - por 10 para pegar o dígito, e a divisão inteira para manter o que sobra). Então, repita esse procedimento para os demais passos, até que o seu resultado da divisão inteira seja 0 (não há mais nada sobrando e você já processou todos os dígitos).

Dividir números de um int. C++


Não consigo ir para outra página com a função header

Question: Estou tendo problema com o header(), fiz uma programação de alterar os dados do banco de dados e quando clica no botão para poder alterar ele vai para uma página em branco então coloquei o header("Location: AdmAgenda.php"); para que pudesse voltar para a página já com os dados atualizado mas está dando erro:

A página de localhost não está funcionando
Redirecionamento em excesso por localhost Tente limpar os cookies.

O que posso fazer para corrigir?
meu código:
<?php
$idSeg = filter_input(INPUT_GET, "id-segunda");
$seg = filter_input(INPUT_GET, "seg");

$idTerca = filter_input(INPUT_GET, "id-ter");
$tercaa = filter_input(INPUT_GET, "ter");

$idQuarta = filter_input(INPUT_GET, "id-quarta");
$quartaa = filter_input(INPUT_GET, "qua");

$idQuinta = filter_input(INPUT_GET, "id-quinta");
$quintaa = filter_input(INPUT_GET, "qui");

$idSexta = filter_input(INPUT_GET, "id-sexta");
$sextaa = filter_input(INPUT_GET, "sex");

$idSabado = filter_input(INPUT_GET, "id-sabado");
$sabadoo = filter_input(INPUT_GET, "sab");

include("conexao.php");

if($link) {
    $segg = mysqli_query($link, "UPDATE horas_segunda set horas_de_segunda='$seg' where id='$idSeg';");
    $terc = mysqli_query($link, "UPDATE horas_terca set horas_de_terca='$tercaa' where id='$idTerca';");
    $quarr = mysqli_query($link, "UPDATE horas_quarta set horas_de_quarta='$quartaa' where id='$idQuarta';");
    $quinn = mysqli_query($link, "UPDATE horas_quinta set horas_de_quinta='$quintaa' where id='$idQuinta';");
    $sexx = mysqli_query($link, "UPDATE horas_sexta set horas_de_sexta='$sextaa' where id='$idSexta';");
    $sabaa = mysqli_query($link, "UPDATE horas_sabado set horas_de_sabado='$sabadoo' where id='$idSabado';");
    header("Location: AdmAgenda.php");
}
else{
    die("Erro: " .mysqli_error($link));
}
?>

Comment: O redirecionamento é pra mesma página? Loop infinito?
Comment: Coloque um `if` para prevenir que entre na condição que faz as alterações e o redirect.
Comment: isso... teria que voltar para a pagina
Comment: Já conseguiu resolver?
Answer: Não concordo com a forma como você está fazendo as coisas, pois só redirecionar não vai dar a informação de "Atualização realizada com sucesso" para o usuário,  mas se você mudar:
if($link) {

para:
if($link && isset($_GET["seg"])) {

já resolve o problema da forma que vc quer.
Answer: Em que pese não ser a melhor prática, não há problema em redirecionar para a mesma página, desde que você saiba o que está fazendo e consiga escrever sua lógica de uma forma que nunca caia em um redirecionamento infinito (o navegador na verdade cancela o loop quando verifica que há muitos redirecionamentos para a mesma página, lançando algo como ERR_TOO_MANY_REDIRECTS). Assim, não chega a travar a navegação.
No seu problema específico, você está apenas verificando se a variável $link (que pelo contexto, depreende-se que é uma conexão aberta com o mysql) não é null, ou seja: sempre (se tudo estiver certo).
Para evitar isto, ao invés de verificar se há conexão, verifique se a url está enviando os parâmetros para salvar. Sugiro colocar acima do seu if($link) { algo assim:
if ( $idSeg && $seg && $idTerca && $tercaa && $idQuarta && $quartaa &&
     $idQuinta && $quintaa && $idSexta && $sextaa && $idSabado && $sabadoo ) {

    if($link) {
        /* funções de update */
        header("Location: AdmAgenda.php");
    } else{
        die("Erro: " .mysqli_error($link));
    }

}

Isso implicaria em só atualizar o banco e redirecionar se todos estes parâmetros estiverem presentes (não sei se esta é a lógica da sua aplicação, mas é apenas para fins de explicação, você adapta). Uma abordagem mais clean é verificar um a um. Feito isto, quando você redirecionar, os parâmetros não irão ser enviados e, consequentemente, não cairão neste if.
Comment: Então, quando eu fiz a programação cru cada vez que eu alterava o dados e clicava no botão ele iria para uma outra página em branco, ai pensei se fosse para cair em uma página em branco que caia na página adm.php novamente pois assim já atualiza a página automáticamente
Comment: E colega tentei dessa forma continuar indo para pagina em branco o que seria?
Comment: Bom dia @Nathan, o erro de excesso de redirect foi corrigido? o script `AdmAgenda.php` é o que renderiza o formulário, correto? quando ele não cai no 'header` para redirecionar, ele continua o script normalmente, e vai executar tudo que está nele, depois desse `if`.
Comment: Não consegui, nem mesmo com esse codigo amigo, o script que faz alteração do banco e outro, esse `AdmAgenda.php` ele seria o corpo de onde vizualizo e coloco os dados para poder alterar, ao clica no botao de alterar deveria dar um redirect na pagina para poder ver novamente (como se fosse um f5).


How to estimate a standardized mean difference from two samples' quartiles?

Question: I'd appreciate ideas about how to estimate the standardized mean difference (SMD) for two independent samples from each sample's size and middle three quartiles (i.e., median and 25th and 75th percentiles).  This problem's context is a meta-analysis whose focal effect size is a post-intervention SMD between treatment and control groups on a continuous outcome variable: Many studies report both samples' sizes, means, and variances or equivalent results (e.g., from a t test), from which a SMD is readily estimated, but some studies report other results instead (e.g., sizes and quartiles).  Below I state the problem more precisely, give an example, and offer a few remarks.
Suppose we're interested in the following SMD on a continuous dependent variable $Y$ for Groups 1 and 2: $\delta = (\mu_1 - \mu_2) / \sigma$, where $\mu_j = \mathrm{E}(Y_j)$ and $\sigma^2 = \mathrm{Var}(Y_j)$ for $j = 1, 2$ are the groups' means and (common) variance.  For convenience let's assume normality for each group, so $Y_j \sim \mathcal{N}(\mu_j, \sigma^2)$.  Now consider a study that reports for one simple random sample from each group the size, $n_j$, and estimates of the three middle quartiles, $q_{1j}$, $q_{2j}$, and $q_{3j}$.  How can we estimate $\delta$ from these results?
EXAMPLE: The following randomized study is from a meta-analysis of interventions to improve medication adherence.  In short, Group 1's treatment sample experienced a multi-component intervention, Group 2's control sample received no attention beyond enrollment and data collection, and the outcome variable was a pharmacy refill measure on which higher scores represent better adherence.  The samples' sizes and quartiles are as follows:

Group 1: $n_1$ = 80, $q_{11}$ = 58, $q_{21}$ = 85, $q_{31}$ = 174
Group 2: $n_2$ = 46, $q_{12}$ = 31, $q_{22}$ = 79, $q_{32}$ = 158

The intervention seems to have improved adherence, in that all three quartiles are higher for the treatment group.  Both groups also exhibit evidence of positive skewness.  Answers to this question could use these results to demonstrate any proposed method for estimating $\delta$.
REMARKS: Below are several related issues that may be worth considering, in no particular order.
R1. Typically no details are reported about how exactly quartiles were computed.  In principle one could obtain this information -- and perhaps the original subject-level data -- from the study's author(s), but in practice that's often not feasible.
R2. For now I'd be content with a "reasonable" estimator of $\delta$.  I'm less interested in properties of the estimator (e.g., bias, consistency, efficiency) or in finding an optimal estimator (e.g., UMVUE), but those would be interesting to consider eventually.
R3. A potential complication is duplicate quartiles within a sample (e.g., $q_{11} = q_{21}$) or between samples (e.g., $q_{21} = q_{22}$), especially when reported results are rounded severely.  We can ignore this for now, but it arises in practice.  For instance, another study from the same meta-analysis as the above example reported all six quartiles as 3.
R4. One ad hoc method I've considered involves obtaining several estimates of $\delta$ and combining them in a way that accounts for their variances and correlations (e.g., generalized least-squares using estimated precision matrix).  For instance, we could use Group 1's results to estimate $\sigma$ and $\mu_1$ as follows, where $\Phi^{-1}(p)$ is the standard normal inverse CDF (i.e., quantile function) at $p$:
$\hat\sigma = (q_{21} - q_{11}) / [\Phi^{-1}(1/2) - \Phi^{-1}(1/4)]$ .
$\hat\mu_1 = q_{11} - \Phi^{-1}(1/4)\hat\sigma$ .
We could use other pairs of quartiles for these estimates, do the same for Group 2, and estimate $\delta$ using various combinations of estimates from Groups 1 and 2 (e.g., mean difference and pooled variance).  Note that $\delta$ estimates from different combinations of quartiles may differ in sign.
R5. Some meta-analytic techniques require a sampling variance for the estimate of $\delta$, such as precision-weighted methods that use weighted least-squares.  For now I'm willing to obtain this variance by resampling or simulation, but a closed-form expression would be convenient.
R6. I can imagine numerous useful variants on or extensions of this problem.  For example, suppose a study reports for at least one group different or more quartiles (e.g., $q_{0j}$ [minimum] or $q_{4j}$ [maximum]), different or more quantiles (e.g., 10th and 90th percentiles), or other results (e.g., sample mean).  Another idea is to consider monotonic transformation of the quartiles, say $X_j = f(Y_j)$, so that $X_1$ and $X_2$ better satisfy normality and homoscedasticity.
Answer: If you are willing to assume that $Y$ has a symmetric distribution within the two groups, then the medians of the two groups (i.e., $q_{21}$ and $q_{22}$) could be used in place of the means. Furthermore, if you are willing to assume that $Y$ is normally distributed within the two groups, then you could make use of the relationship between the IQR and the SD for the normal distribution, namely, $SD \approx IQR / 1.35$. So, you can compute the two IQRs with $IQR_1 = q_{31} - q_{11}$ and $IQR_2 = q_{32} - q_{12}$, transform them to SDs, pool those two SDs in the usual manner, and then you have all of the pieces to compute the standardized mean difference.
Example: For your example data, this would be $$IQR_1 = 174 - 58 = 116$$ $$IQR_2 = 158 - 31 = 127,$$ so $$SD_1 = 116 / 1.35 = 85.93$$ $$SD_2 = 127 / 1.35 = 94.07.$$ Therefore, $$SD_p = \sqrt{\frac{(80-1)85.93^2 + (46-1)94.07^2}{80+46-2}} = 88.97.$$ And finally: $$d = \frac{85-79}{88.97} = 0.07$$ Now you could use the usual equation to estimate the sampling variance of $d$ (Hedges & Olkin, 1985): $$v = \frac{1}{80} + \frac{1}{46} + \frac{0.07^2}{2(80+46)} = 0.034.$$
Remarks: Under normality, $d$ should be an okay estimator of the true SMD. However, the use of medians in place of means and the estimation of the SDs via the IQRs involves a loss of precision. The usual equation for the sampling variance of $d$ does not reflect that, so it yields values that are probably too small (on average).
Also, the appropriateness of this method hinges on the symmetry/normality assumption. Unfortunately, authors typically choose to report medians and IQRs whenever they suspect that $Y$ has a non-normal/symmetric distribution. So, I would regard this method only as a rough approximation.
References:
Hedges, L. V., & Olkin, I. (1985). Statistical methods for meta-analysis. Orlando: Academic Press.
Comment: Thanks for your well-articulated answer.  Three very brief comments: **1.** Computations like yours but with other quartiles would yield different results, such as $q_{11} - q_{12}$ for the mean difference; I'm curious how to choose among or combine different options (see my Remark R4). **2.** Larry Hedges pointed me to Hedges & Olkin (1985, p. 93) for relevant ideas based on order statistics.  **3.** I share your concerns about the sampling variance and non-normality (see my Remarks R5 and R6).
Comment: Regarding *(1.)*: True, but using the medians will make the loss of precision smallest. Combining different options would be another option.


mock private constructor and its multiple parameters with mockk

Question: I want to mock the private constructor of a class with its multiple parameters (with Kotlin):
public final class Foo {

   public static class Bla {
        public final CustomType1 property1;
        public final CustomType2 property2;

        private Bla(CustomType1 param1, CustomType2 param2) {
            this.property1 = (CustomType1)Objects.requireNonNull(param1);
            this.property2 = (CustomType2)Objects.requireNonNull(param2);
        }
    }
}

Through that I try to mock the properties (property1, property2) which are otherwise nearly impossible to mock.
Comment: "which are otherwise nearly impossible to mock" you should consider redesigning your class to allow for testability.
Comment: Is `Foo.Bla` your own class, or is it part of a dependency?
Answer: Maybe a private constructor is not what you are looking for. With a private constructor you restrict the object creation to only within the class Bla. Take a look here.
If for some reason you are required to have the constructor private, then you could try using reflections as mentioned in this issue, but keep in mind that it will essentially set the private modifier to public at runtime.
Comment: Sorry, but I still don't get how reflection could help him with mocking the private constructor, could you elaborate? Because I'm in a similar [situation](https://stackoverflow.com/questions/78068110/how-to-port-a-python-monkeypatch-in-kotlin)
Comment: In Java you can use the `Method#setAccessible` method to make it public at runtime and invoke it. I don't know how this is done in other languages or if it is possible at all.
Answer: I think there are only 2 ways. The first one is already mentioned @micartey and the second one is to use PowerMockito. It's a strong tool that allow you to mock static and private methods. If we are talking about code. so it should look like this:
@RunWith(PowerMockRunner::class)
class FooTest {

    @Test
    fun testBlaConstructor() {

        val customType1Mock = mock(CustomType1::class.java)
        val customType2Mock = mock(CustomType2::class.java)

        val blaMock = mock(Bla::class.java)
        whenNew(Bla::class.java)
            .withArguments(customType1Mock, customType2Mock)
            .thenReturn(blaMock)

        val blaInstance = Bla(customType1Mock, customType2Mock)
        verify(blaMock).property1 = customType1Mock
        verify(blaMock).property2 = customType2Mock
    }

Dont forget to prepare dependency for PowerMockito
NOTE: Power Mock should be used in legacy applications where you cannot change the code which has been given to you. Often such code does not have unit/integration tests and even small change can result in bugs in application.
Answer: It was possible to mock the parameter property1 while wrapping it with an extending function:
internal fun Foo.Bla.getProperty1(): CustomType1 {
   return property1
}

I've accessed the value of property1 then in the implementation though getProperty1().
With that workaround it could be mocked.


Checking two databases when logging in a user with a custom module

Question: I am trying to create a module that will check for two databases when logging in a user to Drupal. If drupal's native login is a success but the external application does not have that account, then the module will create an account on the external application. If the account is not on drupal but is on the external application then drupal will create a local account. If the user does not exist on either database then the login will fail. Which hook(s) would I need to implement this in a module?
Answer: Never tried, but you can basicaly:

try hook_user() but you may not catch the case where the user doesn't exists in drupal but your other site.
create your own login form & callback and:

check if user exists in drupal with user_external_load()
if user exists on your external site either login or register on drupal using user_external_login_register()

You may find some interesting code in the openid_authentication().


Find largest char that occured double times in sequence

Question: my method findLargestDoubledChar takes in a string, and returns char c when c is the largest char that appears next to it's identical code. For example: findLargestDoubledChar(look) returns o and findLargestDoubledChar(aaxx) returns x. When there is no doubles, it's supposed to return '\u0000' I have spent hours toying with this code and this is what I have. Where am I going wrong?
public static char findLargestDoubledChar(String string){

        char largestDoubleChar = '\u0000';
        String doubleChars = "";

        char[] stringArray = string.toCharArray();

        for(int x = 0; x < stringArray.length - 1; x++) {
            for (int j = x + 1; j < stringArray.length; j++) {
                if(stringArray[x] == stringArray[j]) {
                    System.out.println("Found Double!");
                } else {
                    continue;
                }
            }
        }

        for (int i = 0; i < doubleChars.length(); i++) { //find largest of doubleChars
            if (doubleChars.charAt(i) >= largestDoubleChar) {
                largestDoubleChar = doubleChars.charAt(i);
            } else {
                largestDoubleChar = '\u0000';
                continue;
            }
        }

        return largestDoubleChar;
    }

Answer: Looks like you're iterating over doubleChars in the second loop when it's being set to an empty string. Maybe something like this would work better:
public static char findLargestDoubledChar(String string){

    char largestDoubleChar = '\u0000';
    String doubleChars = "";

    char[] stringArray = string.toCharArray();

    for(int i = 0; i < stringArray.length - 1; i++) {
        if (stringArray[i] == stringArray[i + 1]) {
            System.out.println("Found Double!");
            if (stringArray[i] > largestDoubleChar) largestDoubleChar = stringArray[i];
        }
    }

    return largestDoubleChar;
}

Comment: Oops, you have a left-over `doubleChars`. Still: +1
Answer: You have a few problems.

The inner loop isn't needed for the first loop.
You aren't storing the doubled char when you find it.
Example answer from modifying yours:
'   public static char findLargestDoubledChar(String string){
char largestDoubleChar = '\u0000';
String doubleChars = "";

char[] stringArray = string.toCharArray();

for(int x = 0; x < stringArray.length - 1; x++) {
    if (stringArray[x]==stringArray[x+1]){
        System.out.println("Found Double");
        doubleChars= doubleChars+ stringArray[x];

    }
}

for (int i = 0; i < doubleChars.length(); i++) { //find largest of doubleChars
    if (doubleChars.charAt(i) >= largestDoubleChar) {
        largestDoubleChar = doubleChars.charAt(i);
    } else {
        largestDoubleChar = '\u0000';
        continue;
    }
}

return largestDoubleChar;

}'
Answer: It can be done in a single statement like this, which also supports Unicode characters from the supplemental planes, such as emojis.
public static String findLargestDoubledChar(String input) {
    return Character.toString(Pattern.compile("(.)\\1").matcher(input)
            .results().mapToInt(r -> r.group(1).codePointAt(0)).max().orElse('\0'));
}

Test
System.out.println(findLargestDoubledChar("look"));
System.out.println(findLargestDoubledChar("aaxx"));
System.out.println(findLargestDoubledChar(""));

Output
o
x

Answer: Try this.
static final Pattern DOUBLE_PAT = Pattern.compile("(.)\\1");

public static char findLargestDoubledChar(String string){
    return DOUBLE_PAT.matcher(string).results()
        .map(x -> x.group().charAt(0))
        .max(Comparator.naturalOrder()).orElse('\u0000');
}


existence of generator set of a vector space

Question: I always find this quote in the books of linear algebra:
"Let V be an K-vector space and S a spanning set of V"
My question is simple, why does S exist?
Answer: One can take $S = V$.  Slightly less trivially, one can take $S = V\setminus\{0\}$.
Comment: thank you man for your answer.


Can't call pg_dump for all databases in PSQL

Question: please help me solve the following problem:
Syntax error EXECUTE 'pg_dump...'
SELECT datname FROM pg_database WHERE datname NOT IN ('postgres', 'template0', 'template1');
CREATE OR REPLACE FUNCTION dump_databases() RETURNS void AS $$
DECLARE
save_path text := 'C:/Users/79209/Desktop/';
db_name text;
dbs CURSOR FOR SELECT datname FROM pg_database WHERE datname NOT IN ('postgres', 'template0', 'template1');
timestamp text := to_char(now(), 'YYYY-MM-DD');
BEGIN
OPEN dbs;
LOOP
FETCH dbs INTO db_name;
EXIT WHEN NOT FOUND;
EXECUTE 'pg_dump -U postgres -Fc -d ' || db_name || ' > ' || save_path || db_name || '_' || timestamp || '.dump';
END LOOP;
CLOSE dbs;
END $$ LANGUAGE plpgsql;
SELECT dump_databases();

Tried the following options - nothing worked...
EXECUTE 'C:/Program Files/PostgreSQL/15/bin/pg_dump -U postgres -Fc -d ' || "db_name" || ' > ' || save_path || "db_name" || '_' || timestamp || '.dump';

EXECUTE 'pg_dump -U postgres -Fc -d ' || quote_ident(db_name) || ' > ' || quote_literal(save_path || db_name || '_' || timestamp || '.dump');

EXECUTE format('pg_dump -U postgres -Fc -d ' || quote_ident(db_name) || ' > ' || quote_literal(save_path || db_name || '_' || timestamp || '.dump'));

Comment: [pg_dump](https://www.postgresql.org/docs/current/app-pgdump.html) is a command line program it cannot be run inside a `plpgsql` function. Furthermore `plgsql` is a TRUSTED language and cannot operate outside the database.
Comment: Well you are not going to do it from a `plpgsql` function inside Postgres. You will need to use a Windows shell batch script. I avoid Windows like the plague, so I cannot help you much there. A search on 'Windows Postgres pg_dump script' might get you something.
Comment: @AdrianKlaver is a term paper assignment, the main condition is to write the following algorithm on the Windows command line. Maybe you know where I can see a sample code implementation?
Answer: If you execute the lines separately it works, launching the cmd file does not work, it closes the window when entering the loop.
chcp 65001
PAUSE
cd C:\Program Files\PostgreSQL\15\bin
PAUSE
FOR /F "usebackq" %i IN (`psql -U postgres -tAc "SELECT datname FROM pg_database WHERE datname NOT IN ('postgres', 'template0', 'template1')"`) DO pg_dump -U postgres -Fc %i > "C:\Users\79209\Desktop\%i-%DATE%.dump"
PAUSE

Comment: Thanks for the help, it works:
```
chcp 65001
cd C:\Program Files\PostgreSQL\15\bin
FOR /F "usebackq" %%i IN (`psql -U postgres -tAc "SELECT datname FROM pg_database WHERE datname NOT IN ('postgres', 'template0', 'template1')"`) DO pg_dump -U postgres -Fc %%i > "C:\Users\79209\Desktop\%%i-%DATE%%.dump"
```


How to fit ARMA(4,4) model, but some coefficients set to zero / fixed?

Question: Suppose I have the following ACF and PACF (data:

I want to fit an ARMA-GARCH process. Currently I want to do the first step, specify the mean equation. The first model just uses a constant $\mu$, so no ARMA. In the second model I was thinking about a modified ARMA(1,1) or ARMA(4,4), I don't know what this is called. I want to only use the 4th lag order in the AR and MA part. So this is basically an ARMA(4,4) where the coefficients of the first three lags are set to zero.
$r_t=\delta + \epsilon_t + \alpha_4 r_{t-4}+ b_4 \epsilon_{t-4}$
How can I fit this model in R?
I tried
   arima(logloss, order=c(4,0,4),fixed=c(0,0,0,NA,0,0,0,NA,NA))

First of all: Is this correct?
Second: Does this make sense?
My output is the following:

If I calculate the p-values via
# p-values
(1-pnorm(abs(aa$coef)/sqrt(diag(aa$var.coef))))/2

I get
> (1-pnorm(abs(aa$coef)/sqrt(diag(aa$var.coef))))/2
         ar1          ar2          ar3          ar4          ma1          ma2
2.500000e-01 2.500000e-01 2.500000e-01 4.431378e-08 2.500000e-01 2.500000e-01
         ma3          ma4    intercept
2.500000e-01 2.523225e-06 1.886732e-01
>

So can I say, that the both coefficients of the 4th lag order are highly significant, but the intercept is not significant, correct? So should I also fix it to zero?
If I just fit a model with a mean, so no AR or MA, I get:

So the mean is also not significant. What should I do? Fit a GARCH without a mean equation? So no mean, no AR or MA part?
EDIT: I played around with it and I found, that an ARIMA(5,0,5) with the first 3 lags fixed to zero and the mean fixed to zero seems to be approrpriate. The output is:

The AIC is smaller than in case of the ARIMA(4,0,4) with mean fixed to zero and the residuals look ok. Are my model building steps correct?
Answer: (1) Have you correctly fitted an ARIMA with some coefficients forced to zero? - Yes. But did you heed the Warnmeldung? If you didn't, & want to make sure your model is causal & invertible, check the roots of the AR & MA polynomials (abs(polyroot(your.polynomial)) is convenient in R).
(2) Is your model-building approach sensible? - I don't think it's the most sensible. Setting various coefficients to zero just because they're "not significant" is no more principled in ARIMA than in multiple regression - see the 'model selection' & 'variable selection' tags - & can lead to the same sorts of problems. The estimate for one parameter depends on all the others that are in the model, so by removing a whole bunch at once you can badly degrade the model. Stepwise selection is a little better, but after doing lots of tests you can't really justify the result overall.
Approaches vary, & depend on the goals of modelling, but I would suggest confining your attention to a smallish set of plausible models (is it really likely that an observation's affected by what happened four & five observations ago but by nothing in the intervening time?), picking a model using AIC, & validating it by out-of-sample forecasts.
Answer: I disagree. In ARIMA modelling "parsimony" is important/key so it becomes necessary to knock out highly insignificant AR/MA terms. Also helps to guard against overfitting. If diagnoses of pacf/acf reveals a large spike at 12 and at 1, why would you estimate a full AR(12) with 10 insignificant parameters with all the knock on effects on the SE's and coef estimates? I always knock out highly insignificant terms using the AIC/BIC and residual diagnostics as a guide and haven't really had many problems at all. It does take longer to fit though, but that is worth it in my opinion, to obtain a parsimonious model. (I'd be less concerned (slightly) if I was forecasting.). So, IMHO, it's not bad practice to knock out AR terms etc ....and you can develop a sensible model as long as you go about it sensibly.
Or you could just switch to Structural Time Series Models instead.
Comment: could you state what exactly and tag who you disagree with? Ordering of answers varies with votes so over time and if new answers are provided and answers are rearranged it may no longer be clear to readers.
Comment: Interesting that you find parsimony slightly less important in forecasting. I could (though not necessarily would) say it is precisely in forecasting that we can afford to simplify the model as much as needed to increase forecast precision, in contrast to (1) explanatory modelling where certain variables are kept for their subject-matter significance; or (2) exercises aiming to find the true data generating process that do not care about estimation imprecision (think Shmueli ["To explain or to predict"](https://arxiv.org/pdf/1101.0891.pdf) (2010)).


How to extract meaning of colloquial phrases and expressions in English

Question: I am looking into extracting the meaning of expressions used in everyday speaking. For an instance, it is apparent to a human that the sentence The meal we had at restaurant A tasted like food at my granny's. means that the food was tasty.
How can I extract this meaning using a tool or a technique?
The method I've found so far is to first extract phrases using Stanford CoreNLP POS tagging, and use a Word Sense Induction tool to derive the meaning of the phrase. However, as WSI tools are used to get the meaning of words when they have multiple meanings, I am not sure if it would be the best tool to use.
What would be the best method to extract the meanings? Or is there any tool that can both identify phrases and extract their meanings?
Any help is much appreciated. Thanks in advance.
Comment: Search for sentiment analysis.
Answer: The problem you pose is a difficult one. You should use tools from Sentiment Analysis to get a gist of the sentence emotional message. There are more sophisticated approaches which attempt at extracting what quality is assigned to what object in the sentence (this you can get from POS-tagged sentences + some hand-crafted Information Extraction rules).
However, you may want to also explore paraphrasing the more formal language to the common one and look for those phrases. For that you would need to a good (exhaustive) dictionary of common expressions to start with (there are sometimes slang dictionaries available - but I am not aware of any for English right now). You could then map the colloquial ones to some more formal ones which are likely to be caught by some embedding space (frequently used in Sentiment Analysis).
Comment: @Fleur - did it help you? If so, could you please accept the answer?


How can I get ~B + AC by simplifying (~A~B)+(AC)+(A~B~C)

Question: The original expression is:

(~A~B~C)+(~A~BC)+(A~B~C)+(A~BC)+(ABC)

I could reduce it to (~A~B)+(AC)+(A~B~C) using the Uniting Law, but I need extra help to finally simplify the expression to ~B+AC
From (~A~B)+(AC)+(A~B~C) I could factor out ~B but then, there's not anything I can simplify.
Thank you.
Answer: <code>(~A~B~C)+(~A~BC)+(A~B~C)+(A~BC)+(ABC) =
(~A~B)+(A~B)+(ABC) =
~B+ABC =
~B+AC
</code>
or, from your reduction
<code>(~A~B)+(AC)+(A~B~C) =
A(C+~B~C) + ~A~B =
A(C+~B) + ~A~B =
A~B + AC + ~A~B =
~B+AC
</code>
Comment: What a prompt response, I really appreciate it!
Comment: btw, how can you just remove B in ~B+ABC. The same thing with ~C in A(C+~B~C) + ~A~B on the bottom reduction
Comment: Because A+~AB = A+B. Notice that if A is 1, then the result is 1; if A is 0, then the result is determined by the value of B.


Cleaning a Tenor Recorder lever

Question: I have a plastic Tenor Recorder which I understand can be washed with soapy water.
I am concerned if the lever can also be immersed or do I have to clean it another way.
Answer: Although most of the plastic recorder can be cleaned with water and mild detergent, since the keys have pads, you want to keep the keys dry. From Yamaha's website:

Resin recorders can be washed in one piece using a neutral kitchen detergent. For instruments equipped with keys, take care to avoid allowing the keys to become wet.

My Yamaha tenor recorder is built in 3 parts; I can wash the head and middle joints easily, but I need to be careful with the foot joint, since that's the section with the keys.

Cleaning a Tenor Recorder lever


Reshape pandas dataframe with 3 columns

Question: I have the following code:
sentiments = ['He is good', 'He is bad', 'She love her', 'She is fine with it', 'I like going outside', 'Its okay']
positive = [1,0,1,0,1,0]
negative = [0,1,0,0,0,0]
neutral = [0,0,0,1,0,1]
neutral
df = pd.DataFrame({'Sentiments':sentiments, 'Positives':positive, 'Negatives': negative, 'Neutrals':neutral})
df.head()

which creates this:

I want to have instead only 2 columns, 1 with sentiment and other with category and that should be that particular sentiment i.e. the result should be:

Sentiment
Category

abc
positive

xmy
negative

poi
neutral
Answer: Try .melt():
x = df.melt("Sentiments", var_name="Category")
x = x[x.value != 0].drop(columns="value")
x["Category"] = x["Category"].str.replace(r"s$", "", regex=True)
print(x)

Prints:
              Sentiments  Category
0             He is good  Positive
2           She love her  Positive
4   I like going outside  Positive
7              He is bad  Negative
15   She is fine with it   Neutral
17              Its okay   Neutral

Answer: Assuming there is only going to be one column with the value 1 (i.e. dummies), try:
>>> df.set_index("Sentiments").idxmax(axis=1).rename("Category").reset_index()
             Sentiments   Category
0            He is good  Positives
1             He is bad  Negatives
2          She love her  Positives
3   She is fine with it   Neutrals
4  I like going outside  Positives
5              Its okay   Neutrals

Answer: Another way:
df = df.set_index('Sentiments').dot(df.columns[1:]).reset_index(name = 'Category')

Reshape pandas dataframe with 3 columns


Statistical Significance Dependent Populations

Question: I am hoping to understand best way to test statistical significance between 2 dependent population groups.
For example, consider a usability test. When 100 subjects were tested, 50 of them clicked (=50% click rate). However, 50 of the subjects were male, 40 of whom clicked for an 80% click rate for males.
The question is that 80% statistically significant? In other words, do men click more than the population as a whole? I think I need to use a paired $t$-test, however unsure as what I would use as the mean, since these are all population proportions.
Comment: Do you mean 50 of the 100 subjects? And significantly different from what? Do you want to know if the part is different from the whole?...the remaining part?
Comment: "*The question is that 80% statistically significant?*" against what null? It seems like you want a two sample test, but you must clarify.
Comment: The statement I want to make is that males click rate is 700% better then those who are not male. (40/50)-(((50-40)(100-50)))/(40/50)). However if the males subject population was only 1, and that 1 person clicked, i would have a much larger value, but it wouldn't be significant because 1 of 1 is not large enough to be deemed statistically significant.
Comment: Do you mean that `40/50-(50-40)*(100-50)/(40/50)=-624.2`? The male click rate is `40/50=80%`, and the female click rate is `(50-40)/(100-50)=20%`? If 1 of 1 male clicked, you mean that you will have a larger male click rate (from 80% to 100%), but what becomes insignificant? `male click rate = 0` or `male click rate = female click rate`, or others? Please edit your question to clarify.
Answer: You seem to have gone on a convoluted route to asking for how to assess independent count data. You've got 100 independent items.  There are 40 males that clicked, 10 males that didn't click, 10 non-males that clicked, and 40 non-males that didn't click. You can easily construct what is called a contingency table (below) from those data and do a $\chi^2$ (chi-square) test for independence.
<code>         male non-male
click    40   10
no click 10   40
</code>
Searching for the chi-square test on the internet will show you the formulas, logic, and even online calculators that can solve the problem.
Comment: Sorry I don't have a lot of stats knowledge but from my general understanding, the populations are dependent since the male population is a subset of the total population of subjects. If the populations were independent could I use a binomial approx and check for the result being within 3 std deviations? Sorry I am totally out of my element here, but I am trying to determine statistical significance for a bunch of different usability tests where I want to know if the subset of users proportion is statistically significant to the larger population of subjects.
Comment: Yes, the males are a subset of the total population but given that kind of a rule for dependence any values are dependent. Imagine I rolled a die 20 times and got 4 6's. The number 4 is dependent on the fact that I rolled 20 times. But none of those rolls is dependent on any other roll. They're independent rolls. And yes, you could use a binomial approximation and reporting a CI would be a good idea. However, that runs into some judgments on what's conservative and not. I believe it's a better way to report results but not a better test than $\chi^2$.


First promise inside Promise.all() doesn't execute properly

Question: the wait function is used as a sleep function, fn function takes an array (items), it logs each item and sleeps for a second before logging the next item.

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

const fn = async(items) => {
  for (item of items) {
    await wait(1000)
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()

The problem is the result provided by exeAll function which prints:
B1
A2
B2
B2

But I think it should print something like:
A1
B1
A2
B2

A1 doesn't show at all when the above code is executed. Can anybody explain why ?
Comment: If you `await` the calls to `fn()` in the `Promise.all()` call, it works exactly as you expect.
Comment: and B2 is always logged twice at the end.
Comment: There's no need for `exeAll` to be async.
Comment: I don't want to `await` them, awaiting them makes them execute in order. which would print:
A1 A2 B1 B2
Comment: I have removed the `async` keyword from exeAll function and nothing changed, the problem is always there. `A1` is not printed and `B2` is printed twice.
Comment: @Pointy using `await` inside promise.all kinda kills the point of using it, makes your code sequential
Answer: for (item of items) { will create an implicit global variable item, i.e. multiple calls to fn will interfere with each other, overwriting item. Properly declare the variable and it works as expected:

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

const fn = async(items) => {
  for (let item of items) {
  //   ^^^^
    await wait(1000)
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()

We can add more logging to fn to see what happens when in your case:

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

let counter = 0;
const fn = async(items) => {
  const c = counter++;
  console.log(`enter fn call #${c}`);
  for (item of items) {
    console.log(`fn call #${c} sets item <-`, item);
    await wait(1000)
     console.log(`fn call #${c} reads item ->`, item);
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()

Strict mode ("use strict";) would have caught that mistake because assigning to an undeclared variable throws an error.
Comment: Strict mode (`"use strict";`) would have caught that because assigning to undeclared variables throws an error ;)
Comment: Exactly. "strict mode" is the first thing that came to my mind when I first saw your answer.


Equivalente a função sql LEFT() no JPA

Question: Qual a função equivalente a LEFT() no JPA?
Preciso pegar somente os 6 primeiros caracteres de um campo.
O select equivalente em sql seria:
select  left(campo,6), count(*) qtd
from tabela
group by left(campo,6)

Answer: Não existe função LEFT() no jpa!
A documentação restringe a captura de porções de string somente à [função] SUBSTRING().
ex:
select substring(v.campo, 1, 6), count(*)
from V v
group by substring(v.campo, 1, 6)

Equivalente a função sql LEFT() no JPA


Render custom block using block.html.twig template

Question: I'm attempting to render a custom content block programmatically (created through the Custom Block Library UI) and I would like the block to render using block.html.twig as it would if I were to place it in a theme region. I have the block placed in a disabled region and I can get the block body field to render programmatically, but it is not wrapped in the usual block template and does not include the block title. I'm using the code to render a "content block" from the accepted answer here: How can I programmatically display a block?
$bid = ??? // Get the block id through config, SQL or some other means
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->
getViewBuilder('block_content')->view($block);
return $render;

As I understand it, I need to render the instance of the custom block that I have placed inside the disabled region, so I would expect that I have to use the machine name of that instance. I've done a lot of searching and come up with nothing. It's strange that nobody else seems to want to render the block with the title in the block.html.twig template.
Comment: What template would the block right now be rendered with?
Comment: It renders using field--text-with-summary.html.twig.
Answer: BlockContent is the only entity in Drupal not having a template of its own. So you have to wrap it in a template yourself:
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
if ($block) {
  $content = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
  $build = [
    '#theme' => 'block',
    '#attributes' => [],
    '#configuration' => ['label' => 'My Block', 'label_display' => 'visible'],
    '#base_plugin_id' => 'block_content',
    '#plugin_id' => 'block_content:' . $block->uuid(),
    '#derivative_plugin_id' => $block->uuid(),
    '#id' => $block->id(),
    'content' => $content,
  ];
  return $build;
}

Comment: Thank you. This does render the block in the block.html.twig template. It doesn't however use the block title/label configured in the instance of the block I placed in the disabled region. I'm certain there must be a way to do this because it seems like a simple task. Somehow Drupal core is doing the same thing when it renders a custom block inside of a region.
Comment: Since you've asked a code only question I've responded with the code you need to fulfill the task "render a custom block using block html twig template". When Drupal renders a block you've placed in the block layout it does the same, Twig Tweak probably as well. This is the basic usage of twig templates, they are invoked by building a render array with #theme. And when you want a block template you have to use `'#theme' => 'block'`, directly in your own code or via other code you've found in contrib. You can fill #configuration with the settings of a configured block if you want.
Comment: Thank you for the response! That's fair, I didn't mention the desire to render the configured title in the question title so as not to make too lengthy.
Comment: Yes, and your assumption "As I understand it, I need to render the instance of the custom block that I have placed inside the disabled region", is not the case, you don't need to do this only to store the label to retrieve it later to put it in the block template. A configured block is mainly used to place a block in a theme and region.
Answer: Ok, I was hoping for an answer that didn't involve installing a module because this seems like a simple task, but after some point you just have to give in. The Twig Tweak module can do what I'm asking very easily. After installing, in a template where you want to render the block, add this:
{{ drupal_entity('block', 'BLOCK_CONFIG_MACHINE_NAME') }}
where BLOCK_CONFIG_MACHINE_NAME is the machine name of the block you have configured at /admin/structure/block/
This will render the block using block.html.twig and will render the title you have configured.
Documentation: https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak
Comment: Twig Tweak probably isn't the worst. Can even imagine it in core some day.
Comment: I ended up running into this issue again and found my own thread here. I also found that there is actually an open core issue about this on Drupal.org:

https://www.drupal.org/project/drupal/issues/2704331
Comment: I would consider making twig_tweak a standard tool in you site configuration. My opinion is that twig_tweak is one of the most useful contrib modules available for Drupal 8.
Comment: I agree with you both that Twig Tweak is great. However I'm doubtful it will ever become part of core. Drupal 9 is deprecating functions that are wrappers around object oriented code. It seems to me that because a contrib module like Twig Tweak introduces wrapper functions which make our lives easier, it will never become part of core. I'm all for object oriented, but we shouldn't need to write 5+ lines of code to render a block with the proper template unless we choose to do it that way. Oh well.


Discrete Math - Relations Proofs.

Question: Let $R$ be a relation on a group $A$, how to prove that if $R$ is symmetric and transitive relation then $R$ is also reflexive relation?
attempt:
$R$ is symmetric relation, so for all $x,y ∈ A$ if $xRy$ then $yRx$.
$R$ is transitive relation, so for all $x,y,z ∈ A$ if $xRy$ and also $yRz$ then $xRz$.
By the definitions we get that:
for all $x,y,z ∈ A$ if $xRy$ and also $yRz$ then $yRx$ , $xRz$ , $zRy$ , $zRx$.
I have no idea how to continue from here to prove that $R$ is also reflexive relation, i.e all $x ∈ A$ are in the relation $R$: $xRx$.
I tried this:
Because $xRy$ and $yRx$, (as we saw above by definitions), I thougt that $xRx$, because $y$ exists in both terms. but its not like that because $xR∘Rx$, i.e $(x,x) ∈ R∘R$.
Can someone help with an idea?
Thanks!!
Answer: Modulo @Alan Wang's objection, $x R y$ and $y R x$ because it is symmetric. Also apply the transitive property on the above. You will get $x R x$.
Answer: Your question is not true in general.
Let $R$ be an empty relation.
Then clearly $R$ is symmetric and transitive but not reflexive.

Discrete Math - Relations Proofs.


Can I use inferential statistics in a non-probabilistic sample?

Question: Can I use inferential statistics (eg, binomial test, One-Sample Chi-Square Test etc) in a non-probabilistic sample (convenience sample)?
The sample size (n) = 45.
Is there any reference to support the use of inferential statistics in a non-probabilistic sample?
Comment: **How** exactly your sample was gathered? Without knowing this, the question is not answerable.
Comment: The sample consisted of all patients from a care centre (eg, clinic).
Answer: According to Hubbard et al., (2019) the answer is YES.
Nonrandom samples, allied with a replication strategy, can yield robust findings. Which is to say that, over time, via replication research, the point estimates and confidence intervals of additional (new) results about the phenomena at hand may be compared with the increasingly sturdy bench marks established by their numerous predecessors to check for consistency. Consistency gained in this manner leads to deserved support for the veracity of the findings.
And striking break throughs in other fields have arisen from the employment of such samples. For example, Freedman (1999) tells of how the use of convenience samples was key to establishing the causal links betweencontaminatedwater andthe spreadof cholera, and cigarette smoking and lung cancer.
References
Freedman, D. (1999), "From Association to Causation: Some Remarks on the History of Statistics," Statistical Science, 14, 243–258.
Hubbard, Raymond; Haig, Brian D.; Parsa, Rahul A.  (2019). The Limited Role of Formal Statistical Inference in Scientific Inference. The American Statistician, 73(sup1), 91–98.         doi:10.1080/00031305.2018.1464947.
Answer: Of course you can.  The resulting probabilities are completely meaningless, but you can certainly plug numbers into formulas.  Pretty much all NHST inference assumes randomly sampled data.
Comment: -1 This is an irony rather than answer.
Comment: I asked about references on ways to support the use of non-probability sampling in samples for convenience. From what I read, this is not a consensus among statisticians.

In studies with a non-probability sample, the results should not be interpreted as representative of the population.

This work points out an option:

Sousa VD, Zauszniewski JA, Musil CM. How to determine whether a convenience sample represents the population. Appl Nurs Res. 2004 May; 17 (2): 130-3. PMID: 15154126.

But I would like more information!


Is it possible to have some kind of dynamic KeyFilter in autofac?

Question: KeyFilter used in Autofac is helpful but really I think it's not dynamic because the key here is preset/setup/defined and attached to constructor parameters at compile time. No way to have something similar working at runtime.
Here is the scenario, at the time resolving for some instance, the key can be determined (which can change dynamically based on the current context). That key then should be taken into account before resolving for the instance. I think Multitenant feature supported by autofac is something very close to that requirement. However I don't think it can be easily used and supports constructor injection (we may have to always create a scope and resolve for instances explicitly and manually, which looks much like a service locator's way).
So applied that imaginary feature in code version picking example, let's see how helpful it can be. Suppose I have 2 implementations for a same interface, each corresponds to one code version (v1 and v2). Now the constructor consuming that interface does not care about which version, but the context will provide the IoC container which version so that it should resolve for the correct implementation corresponding to the that version.
public interface ISender {
    void Send(string msg);
}
//version v1
public class SlowSender : ISender {
    //...
}
//version v2
public class FastSender : ISender {
    //...
}

Now's the consumer class:
public class MyConsumer {
    readonly ISender _sender;
    public MyConsumer(ISender sender){
        _sender = sender;
    }
    //do whatever with what ISender provides
}

So here when resolving for MyConsumer, autofac should know about which version it is to pick for me, such as via some context info provider like this:
public class ContextInfoProvider : IContextInfoProvider //just an example
{
    public string GetCurrentVersion(){
        //can return some value picked from HttpContext.Current.Request
        //or any ambient variable that can be injected at some very early time.
    }
}

That's kind of a service (very fast service) to help autofac know of which should be taken into account (as an input, a parameter) for the instance resolving process.
I know this is possible but may have not been implemented yet by autofac. It's really a pity. Do you have any alternative solution with the current features supported by autofac? Please note that I don't want to use service-locator-like code, sometimes we have to use it that way but almost the time we need a constructor-dependency-injection's way, it's just neat and clean.
Comment: There are no miracles in programming. Autofac cannot know it by itself. You have to provide some piece of code that will be generating/calculating/fetching/<...> key for resolving your service from the autofac container.
Right now you can write something like ISenderFactory which will resolve service from autofac's container based on the key provided from your algorithm.
Comment: If you read my question thoroughly, you should have noticed that I mentioned about a way to help ioc container know about that key, (the `IContextInfoProvider`). Of course this is not very miracle, it's possible but pity that not yet (or never) be implemented. I have some workarounds in mind but really not clean as what I described in my question. Using a factory is also a workaround.
Answer: You could register a lambda. Put the factory logic in that lambda.
builder.Register(ctx =>
  var version = ctx.Resolve<IContextInfoProvider>().GetVersion();
  if(version == 1)
  {
    return new SlowSender();
  }
  return new FastSender();
).As<ISender>();

Comment: thank you, I am trying this approach, still implementing code, I'll be back with some result. In the mean time I may have another question asked in SO.
Comment: BTW do you have any idea to save an environment variable (from http request) in some static variable (defined in my class) ***as soon as possible*** so that it happens before the Autofac resolving process? I've tried preparing the environment variables in `OnActionExecuting` but looks like it's too late. Somehow the controller's dependencies are resolved first (so autofac runs first) before `OnActionExecuting` runs (so the environment variables are unavailable at the time resolving my dependencies).
Comment: HttpRequest doesn't have anything to do with environment variables, and if you do get something from the request you should never store it as static because the request _changes every request_. I'd recommend doing some research on this since using request variables (including during resolution time) is very common and there are examples of it all over. If it still isn't clear, that's a new SO question rather than an add-on to this one.
Comment: I meant the environment variable ***comes from http request***, and those kind of variables ***exist per request lifetime***. So maybe you understand it differently. Actually I've just thought of ***http module*** which is replaced by ***middleware*** in asp.net core. That should work, thank you anyway. I'll come back this question with some result.
Comment: I've successfully implemented the version switching feature based on middleware in ASP.NET Core (with the help of the new feature named `Endpoint Routing` because we need the Route Data before MVC middleware), of course with the help of your answer as well (about using a factory to resolve instances). Thanks


MongoDB : Update only those objects in a collection whose 'Id' exists in a list

Question: I have a MongoDb collection that I need to update.
The collection's JSON object consists of a few elements, 'Id' being one of them.
Now, I need to update only those objects in this collection whose 'Id' matches the ones I have in temporary list, 'TempList'.
I tried doing something like this, (see below and notice the 'filter' parameter) but it throws me an error,
await MyAccounts.UpdateManyAsync(w => TempList.Any(y => y.Id == w.Id),
        Builder.Update
        .Set(w => w.Elem1, blah1)
        .Set(w => w.Elem2, blah2)
        .AddToSet("Elem3", blah3));

Any help is appreciated !
Comment: what is the error ?
Answer: you need to make tempList a list of IDs for the following to work and not a list of objects.
            var filter = Builders<MyAccount>.Filter
                            .Where(a => tempList.Contains(a.Id));

            var update = Builders<MyAccount>.Update
                            .Set(a => a.Elem1, "blah1")
                            .Set(a => a.Elem2, "blah2")
                            .AddToSet("Elem3", "blah3");

            collection.UpdateMany(filter, update);

here's a test program:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Linq;

namespace StackOverflow
{
    public class Account : Entity
    {
        public string Elem1 { get; set; }
        public string Elem2 { get; set; }
    }

    public class Program
    {
        private static void Main(string[] args)
        {
            new DB("test", "localhost");

            (new[]
            {
                new Account{
                 Elem1 = "first-elem1",
                 Elem2 = "first-elem2"
                },
                new Account{
                 Elem1 = "second-elem1",
                 Elem2 = "second-elem2"
                },
                new Account{
                 Elem1 = "third-elem1",
                 Elem2 = "third-elem2"
                }
            }).Save();

            var tempList = DB.Queryable<Account>()
                             .Select(a => a.ID)
                             .Take(2)
                             .ToList();

            DB.Update<Account>()
              .Match(a => tempList.Contains(a.ID))
              .Modify(a => a.Elem1, "blah1")
              .Modify(a => a.Elem2, "blah2")
              .Modify(a => a.AddToSet("Elem3", "blah3"))
              .Execute();
        }
    }
}
Comment: Thanks ! That was what I was looking for.


Cannot import module in Android Studio 0.3.5

Question: I recently updgraded by AS to 0.3.5 and I can't see import module option. When I open
<code>ProjectStructure - Modules - Click the + sign
</code>
I cant see 'Import Module' option. And also I only see "Modules" in Project Settings.
Is there any other way??
Answer: This isn't implemented yet for Android Studio; it's being tracked in https://code.google.com/p/android/issues/detail?id=62122 . You'll need to move the directory containing the module you want to import under your project root, create a build.gradle file to build it, add an entry to your settings.gradle file to point to it, and re-sync your Android Studio project with Gradle.


Trouble adding a backend to statsd

Question: <code>npm install -g statds
npm install -g statsd-ganglia-backend
</code>
This does not deliver the new backend to /usr/local/lib/node_modules/statsd/backends.
What do I need to copy for myself?
Answer: The doc for neglects to mention that you install it inside of statsd. You cd to the statsd directory and to a local, not a global, install.

Trouble adding a backend to statsd


Values in a HashMap are being overriden everytime I put a key value in the HashMap

Question: I have this flink program below:
object WindowedWordCount {
    class MyCoMap extends RichCoMapFunction[String, String, String] {

      private var usersMap: MapState[String, String] = _

      override def open(parameters: Configuration): Unit = {
          usersMap = getRuntimeContext.getState(
          //Error here
          new MapStateDescriptor[String, String]("usersMap", TypeInformation[String], TypeInformation[String)
      )}

      override def map1(value: String): String = {
        //Grab userId and timeStampOfUserId here
        usersMap.put(userId,timeStampOfUserId)
        println(usersMap)
        "Adding user from event stream to global map: " + timeStampOfUserId
      }

      override def map2(value: String): String = {
          //Do something with the second stream
      }
    }
}

The problem I have in the above code is that in the map1 function inside of the MyCoMap class when I add a key-value to my users HashMap defined globally, for some reason every key-value I add, it is overriding the previous value. So my map always contains 1 key-value in it...
For example if it adds users.put("user1", "abc") the map will contain {"user1"="abc"} then puts another key-value users.put("user2", "abc") the map will becomes {"test2"="abc"} instead of {"test1"="abc", "test2"="abc"}.
EDIT:
Yes I would like to join on userId. Stream1 is coming in at 1 message per second while stream2 is coming in at 1 message per 6 seconds. I want to add the userId from stream1 into a MapState (in the map1 function) and then in the map2 function I want to check if the userID from stream2 is present in the MapSate.
I have a lack of knowledge in this field but when you say keyed state I am assuming all the keys that are the same will be processed on the same node correct and that each node gets it's own MapState object? Since my main concern is that when I am joining the userId from stream2 I want to make sure I have all the userId's from stream1 collected and that they are on the same node when lookup in the MapState occurs in map2 function.
Comment: You shouldn't be using mutable data structures. Especially global ones. Especially, unsynchronized. And DEFINITELY not with flink, or spark or other distributed framework like that.
Comment: @Dima I have added an edit to my question. Can you please take a look at it?
Answer: If I got your requirements right, you want to join two streams on a user.
This can be done by keying both streams on the user field:
val stream1: DataStream[(String, String)] = ??? // first field is user
val stream2: DataStream[(String, String)] = ??? // first field is user

val connected: DataStream[X] = stream1
  .connect(stream2) // connect both streams
  .keyBy(_._1, _._1) // key both streams on first field
  .map(new YourCoMapFunction())

The CoMapFunction should use Keyed State, i.e., state that is keyed on the same attribute as you keyBy on (user in your case). So keyed state is essentially a sharded, distributed HashMap. Note that keyed state can only be locally accessed. When working with state you have to make sure that you remove all state that you do not need anymore. Otherwise, your state might grow too large at some point.
Comment: Yes, `keyBy` partitions by key, i.e., all records with the same key are processed by the same operator. Also, you might not need a `MapState`, because the state is already partitioned by key. If you only need one value per user, you should go with `ValueState`. Each user will have its own `ValueState`.
Comment: Thank you so much for the help. Can you please take a look at my edit really quick in my question? I had some doubts.


How to solve the trigonometric equation $\sin x-\cos x-2(2)^{\frac 1 2}\sin x\cos x=0$

Question: the question is:

Find the solutions of the equation: $\sin x-\cos x-2(2)^{\frac 1 2}\sin x\cos x=0$.

Let  $\sin x+\cos x=u \text{ and } \sin x \cos x=v \implies \sin^2x+\cos^2x+2\sin x\cos x=u^2 \implies v=\frac {u^2-1} 2$
similarly solving the above equation it comes out to be:
$$\sqrt2 u^2-u-\sqrt2=0=(u-\sqrt2)(\sqrt2u+1)=0 \implies \sin x+\cos x=\sqrt2 \quad(1)$$
and
$$\sin x+\cos x= \frac{-1} {\sqrt2}\quad (2)$$
so solving the results differently i got the answers:
$$x=2n\pi + \frac{\pi}4, 2n\pi +\frac{7\pi}{12}, 2n\pi-\frac{\pi}{12}$$
but the answers are:
$$x=2n\pi + \frac{\pi}4, 2n\pi -\frac{5\pi}{12}, 2n\pi+\frac{11\pi}{12}$$
I divided the eq(2) by $\sqrt2$
Comment: Aren't the answers same. You just have to put the next 'n' to change from say $-\frac{5\pi}{12}$  and $\frac{7\pi}{12}$
Comment: Almost, but there is $2\pi$, not $\pi$ next to $n$.
Comment: It seems to me that both your answer and the answer from the book(?) are wrong. Harish result below is correct.
Comment: $\sin x-\cos x$ doesn't match $u$.
Answer: Notice, we have $$\sin x-\cos x-2\sqrt2\sin x\cos x=0$$
$$\sin x-\cos x=2\sqrt2\sin x\cos x$$
$$\sin x-\cos x=\sqrt2\sin 2x$$
$$\frac{1}{\sqrt2}\sin x-\frac{1}{\sqrt2}\cos x=\sin 2x$$
$$\sin 2x=\sin x\cos\frac{\pi}{4}-\cos x\sin\frac{\pi}{4}$$
$$\sin 2x=\sin \left(x-\frac{\pi}{4}\right)$$
Writing the general solution , we get
$$2x=2n\pi+\left(x-\frac{\pi}{4}\right)\iff x=\frac{(8n-1)\pi}{4}$$
$$\bbox[5px, border:2px solid #C0A000]{\color{red}{x=\frac{(8n-1)\pi}{4}}}$$
or $$2x=2n\pi+\pi-\left(x-\frac{\pi}{4}\right)\iff x=\frac{(8n+5)\pi}{12}$$
$$\bbox[5px, border:2px solid #C0A000]{\color{red}{x=\frac{(8n+5)\pi}{12}}}$$
Where, $n$ is any integer.
Answer: This could be helpful:
\begin{align}
\sin x-\cos x-2(2)^{\frac 1 2}\sin x\cos x&=-\sqrt2\Big(\sin(x-\frac{\pi}{4})+\sin(2x)\Big)\\
&=-\frac{\sqrt2}{2}\cos(\frac{\pi}{8}-\frac{3}{2}x)\sin(\frac{\pi}{8}+\frac{1}{2}x)
\end{align}
Answer: The equation can be rewritten
$$\sqrt2\sin(x-\frac\pi4)=\sqrt2\sin(2x),$$
hence
$$x-\frac\pi4=2x+2k\pi\text{ or }x-\frac\pi4=\pi-2x+2k\pi,$$
$$x=\frac{24k-3}{12}\pi\text{ or }x=\frac{8k+5}{12}\pi.$$
The second formula covers the first, so that
$$\color{green}{x=\frac{8k+5}{12}\pi}.$$
Answer: my hints: $$\sin \theta=\sin \alpha\iff \theta=2k\pi+\alpha\ \text{or}\ \theta =(2k+1)\pi-\alpha$$


Help with the proof of a recurrence

Question: I have this recurrence to solve $$f(n,m)= f(n,m-1) + nf(n-1,m-1)$$ with $f(n,0)=1$ $\forall n \in \mathbb{N}$ with $n\geq m$ ,
and I found the solution guessing and it is $$\sum_{k=0}^m \frac{n!}{(n-k)!} \frac{m!}{(m-k)!k!}$$ But I can't prove it by induction and I'm sure that it is correct because I used Matlab to verify the result.  I would be glad if someone can help me.
Answer: Computing some small values, we can find them in a table under A088699 in the OEIS, which gives us the definition

$A(n,m)$ is the number of ways to pair the elements of two sets (with respectively $n$ and $m$ elements), where each element of either set may be paired with zero or one elements of the other set.

Given a pairing counted by $A(n,m)$, if we inspect the first element of the $m$-element set, it is either

not paired at all, leaving $A(n,m-1)$ ways to choose pairs for the other elements, or
paired with any of the $n$ elements in the other set; both elements are removed from consideration, leaving $A(n-1,m-1)$ ways to choose pairs for the other elements,

which gives us the recurrence $A(n,m) = A(n,m-1) + n A(n-1,m-1)$. Also, when $m=0$, there is only one way to choose the pairs: not to choose any pairs. So $A(n,0) = 1$. The recurrence and initial conditions match $f(n,m)$, which confirms that OEIS's $A(n,m)$ is equal to your $f(n,m)$.
But from OEIS's combinatorial interpretation, it is easy to prove a formula. If we decide that we are going to choose a total of $k$ pairs, $k$ must satisfy $0 \le k \le m$. We choose a subset of $k$ elements from the $n$-element set that will belong to a pair, in $\binom nk$ ways. We choose a subset of $k$ elements from the $m$-element set that will belong to a pair, in $\binom mk$ ways. Finally, we can pair these up in $k!$ ways. This tells us that $$f(n,m) = \sum_{k=0}^m k! \binom nk \binom mk   = \sum_{k=0}^m \frac{n!}{(n-k)!} \frac{m!}{(m-k)!\, k!}$$ as desired.
Comment: +1: calculating a table with some small values and then going to the OEIS if the pattern isn't clear is an excellent approach.

Help with the proof of a recurrence


How to get translated menu link entity

Question: I have a headless Drupal 9 solution and I'm currently working on i18n of the whole site.
I've managed to do everything except menus. The content translation core module is installed and setup correctly. I have all the menu items translated.
This a snippet of the code:
  $parameters = new MenuTreeParameters();
  $parameters->onlyEnabledLinks();

  // Get drupal menu tree.
  $menu_tree = \Drupal::menuTree();

  // Load the menu tree.
  $main_menu_tree = $menu_tree->load('main', $parameters);

...
$manipulators = [
  ['callable' => 'menu.default_tree_manipulators:checkNodeAccess'],
  ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
];

$tree = $menu_tree->transform($main_menu_tree, $manipulators);

...
  foreach ($tree as $key => $menu_tree_element) {
    $menu_object = $this->generateSingleMenuObject($menu_tree_element, $max_depth);

    array_push($menu_array, $menu_object);
  }

The 'generateSingleMenuObject' function is where I'd expect to somehow get the objects in a certain language. Here's how the function starts
// Get link from menu tree element.
$menu_tree_element_link = $menu_tree_element->link;

// Get url object from link.
$menu_url_object = $menu_tree_element_link->getUrlObject();

// Create dummy object for storing data.
$menu_object = new stdClass();

// Get id and label.
$menu_object->id = $menu_tree_element_link->getDerivativeId();
$menu_object->label = $menu_tree_element_link->getTitle();

// Get href.
$menu_object->href = $menu_url_object->toString();

I've tried some of the standard options that worked on other entities but without luck.
This is basically the same question as this one.
The only thing I need is the translated menu label.
What am I missing? This really sounds like it should be a relatively simple ask.  Thank you!
Answer: It seems like you're building a custom solution to generate menu items for a headless Drupal site, and you're encountering difficulties with retrieving translated menu labels. In Drupal 9, using the right services and methods is crucial to achieving accurate translations. To get the translated menu labels for each language, you can follow these steps:

Use the Translation Manager:
The MenuLinkManagerInterface provides a method to load menu links with translations. Using the MenuLinkManagerInterface::loadLinks() method with the appropriate parameters, you can load translated menu links.

Loop Through Translated Links:
Once you have the translated menu links, you can loop through them and extract the translated label for each link. This ensures that you get the labels in the correct language.

Here's how you can modify your code to achieve this:
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\Core\Menu\MenuTreeParameters;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyMenuService {

  protected $menuLinkManager;

  public function __construct(MenuLinkManagerInterface $menuLinkManager) {
    $this->menuLinkManager = $menuLinkManager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('menu.link_manager')
    );
  }

  public function generateMenu() {
    $parameters = new MenuTreeParameters();
    $parameters->onlyEnabledLinks();

    // Load the menu tree.
    $main_menu_tree = $this->menuLinkManager->loadLinks('main', $parameters);

    // Add your manipulators and transform the tree.
    // ...

    $menu_array = [];

    foreach ($tree as $key => $menu_tree_element) {
      $menu_object = $this->generateSingleMenuObject($menu_tree_element, $max_depth);

      array_push($menu_array, $menu_object);
    }

    // ...
  }

  protected function generateSingleMenuObject($menu_tree_element, $max_depth) {
    // ... your existing code ...

    // Load the translated link.
    $translated_menu_tree_element_link = $this->menuLinkManager->loadLink($menu_tree_element->link->getPluginId(), $menu_tree_element->link->getMenuName(), $menu_tree_element->link->getPluginDefinition());

    // Get the translated title.
    $translated_label = $translated_menu_tree_element_link->getTitle();

    // Set the translated label in the menu object.
    $menu_object->label = $translated_label;

    // ... rest of your code ...
  }
}

By using the MenuLinkManagerInterface methods to load and handle menu links, you ensure that you get the translated menu labels for each language. This approach should work well with your headless Drupal solution. Just make sure you have the necessary dependency injections set up and the right services used in your class.
Comment: Hi Z CHAMP, thanks for you response. You are right, it's a Drupal 9 headless solution but I'm afraid your answer isn't as helpful as I hoped it would be. By looking into it I've found the menu.link_manager service doesn't exist and even if it did the MenuLinkManagerInterface doesn't have the functions you are suggesting (loadLinks() and loadLink)? Could you elaborate a bit further or tell me if I'm getting something totally wrong here? Thanks!
Answer: I managed to solve this issue with the following code:
if ($lang) {
  $entity = \Drupal::service('entity.repository')
    ->loadEntityByUuid('menu_link_content', $menu_tree_element_link->getDerivativeId());

  if ($entity->hasTranslation($lang)) {
    $translation = $entity->getTranslation($lang);
    $link_override = $translation->get('link_override')->first();
    if ($link_override) {
      $menu_object->href = $link_override->getUrl()->toString();
    }
    $menu_object->label = $translation->getTitle();
  }
  else {
    $menu_object->label = $menu_tree_element_link->getTitle();
  }
}
else {
  $menu_object->label = $menu_tree_element_link->getTitle();
}

Basically loading the menu_link_content entity by Uuid from the menu tree element link. Then checking if the entity has a translation and if so populating the fields from the translated entity.

How to get translated menu link entity


An earned run and loss despite the runner being out - how?

Question: Why did Tanaka get the earned run and loss against the A's on 26 May 2017, when the runner he allowed in the eighth got thrown out at the plate and didn't score?
Comment: Not an expert at this, but I'd put a small amount of money on this being because the [Rosales out was scored as a fielder's choice](https://www.mlb.com/gameday/athletics-vs-yankees/2017/05/26/490823#game_state=final,lock_state=final,game_tab=play-by-play,game=490823).
Answer: 9.16(g) is probably the most relevant rule from the Official Baseball Rules that applies here.

(g) When pitchers are changed during an inning, the official scorer
  shall not charge the relief pitcher with any run (earned or unearned)
  scored by a runner who was on base at the time such relief pitcher
  entered the game, nor for runs scored by any runner who reaches base
  on a fielder's choice that puts out a runner left on base by any
  preceding pitcher.

Phillip Kendall's comment about this being a fielder's choice situation is correct.
Batter 2 (Rosales) reaches on a single, so is Tanaka's run on base.
After the pitching change, batter 3 (Davis) reaches on a fielder's choice.  The ruling is basically that without Tanaka's runner (Rosales) on base, Davis would have been out and no runners on.  So Davis continues to be charged as Tanaka's baserunner under 9.16(g).
Batter 4 (Joyce) walks and is credited to Clippard.
Batter 5 (Lowrie) singles.  This drives in Davis.  The earned run is credited to Tanaka.  As this run put Houston in the lead, Tanaka is then on the hook for the loss until the game becomes tied or the Yankees retake the lead (which did not happen).


How do I read this text-only musical notation from Wikipedia

Question: I have practically no music notation experience, so please consider me a dummie when answering.
I am reading this Wikipedia article, about the clave rhythm. They use a text only notation looking like this:
1 & a 2 & a 3 & a 4 & a ||
X . X . X . . X . X . . ||

or
1 e & a 2 e & a 3 e & a 4 e & a ||
X . . X . . X . . . X . X . . . ||

Is this a standardized notation? Does it have a name? Where can I read more about it?
I believe that the first line specifies 'points in time' and the second specifies which of those times should have a beat. But what points in time are specified? What do the 'e', 'a' and '&' mean?
Comment: This is really interesting. I hadn't seen this kind of notation before. I didn't want to read the answer below so I could figure it out bymyyself and I did. I agree with the comment by Dave below. Thats how I figured it out too.
Answer: You are correct in your interpretation of the two lines.
In the 1 & a example, you can see that the numbered beat is being divided up into three equal parts, and that there are four total beats per measure. This means we are in 12/8, and that each symbol corresponds to the value of an eighth note.
In the 1 e & a example, the numbered beat is being divided up into four equal parts, and there are four beats per measure. This means we are in 4/4, and each symbol corresponds to the value of a 16th note.
The Wikipedia page you referenced has this image:

Your first example is equivalent to the second line (son clave in 12/8) and the second example is equivalent to the first line (son clave in 4/4)
Ultimately, this notation is a type of rhythm counting system that can be used to verbally describe different rhythms. It works by assigning a number to each primary beat in a measure, and then subdividing that beat with various syllables like e, &, a -- some variations exist from place to place, but the basics of & being a duple subdivision and e, a being the next level down are fairly standard with western classical and jazz musicians.
Comment: Many english speakers mentally (or literally) say
"one eee and aaa, two eee and aaa ..." when counting 16th notes, hence the symbols.
Answer: I would be leery of stating that 1 & a is breaking a beat into three -- I've been taught that for triplets one should use 1 la li 2 la li and 1 & a would be 8th note 16th note 16th note (in 4/4 time).  It does appear that this example uses that, but that is non-standard.  (Because there often is differences in tuples, it's important to pick one and be consistent -- and then make sure to explain it.  I use la-lis because they aren't used elsewhere :-P)
Comment: That's *nice*. I usually use "bippity-boppity". But it doesn't extend as well.
Comment: Pretty much every musician you ask is going to have a different syllable for triplet subdivisions. I prefer `1 ta ma 2 ta ma`, though I've heard `la li` from a few people before.
Answer: One interesting note on this kind of notation (no pun intended) is that it only works with monospace fonts.  It is similar in this to the guitar tab you see on sites like ultimateguitar.com.  This makes it a pain if you accidentally paste it into, say, Times New Roman font, but the great advantage is that the spacing on the screen is the same as the spacing in time, like in a "piano roll" editor for a drum machine:


Exporting Custom Display Suite View Modes With Configuration

Question: I'm using display suite with custom display settings for several view modes.  I am also using the configuration management module for D7.
When I go to import my config on the staging server, the content types and settings and even the 'ds' field format settings come through, but it does not remember what view modes I've checked to have custom display settings.  If I manually go back in and recheck the view modes, everything displays fine again.
Any idea where to track those changes?
Answer: Found the answer.  It is under the strongarm variables.  The setting you have to click is field_bundle_settings for that particular content type.  You must have the strongarm module enabled for this to work.


Como conseguir uma lista a partir de um JSON

Question: Estou tentando fazer uma lista de moedas a partir de um texto JSON, para isso estou utilizando a API  "exchangeratesapi.io".
Utilizando JavaScript eu consegui certo sucesso:

const url = 'https://api.exchangeratesapi.io/latest?base=USD'

fetch(url)
  .then(result => result.json())
  .then(json => console.log(json.rates))

Porém eu gostaria de criar uma lista com somente os nomes abreviados das moedas, por exemplo:
{
  BGN,
  NZD,
  ILS,
  RUB,
  CAD,
  USD,
  PHP,
  CHF,
  AUD,
  JPY,
  TRY,
  HKD,
  MYR,
  HRK,
  CZK,
  IDR,
  DKK,
  NOK,
  HUF,
  GBP,
  MXN,
  THB,
  ISK,
  ZAR,
  BRL,
  SGD,
  PLN,
  INR,
  KRW,
  RON,
  CNY,
  SEK,
  EUR
}

Ou até mesmo criar um array contendo todas elas a partir disso, por exemplo:
let currency = ["BGN", "NZD", "ILS", "RUB", "CAD", "USD", "PHP", "CHF", "AUD", "JPY", "TRY", "HKD", "MYR", "HRK", "CZK", "IDR", "DKK", "NOK", "HUF", "GBP", "MXN", "THB", "ISK", "ZAR", "BRL", "SGD", "PLN", "INR", "KRW", "RON", "CNY", "SEK", "EUR"];

Quais tecnologias ou métodos devo utilizar para conseguir isso?
Answer: Nesse caso basta criares uma array usando let currencies = Object.keys(json.rates);.
O Object.keys vai extrair todas a chaves de um objeto e criar uma array com as mesmas.
Ou seja:

const url = 'https://api.exchangeratesapi.io/latest?base=USD'

fetch(url)
  .then(result => result.json())
  .then(json => {
    const currencies = Object.keys(json.rates);
    console.log(currencies);
  })


What's an intuitive explanation for why MAP is variant under parameterization?

Question: I understand why MAP is variant under parameterization mathematically, but I don't really understand it intuitively.
To help me out, my professor gave me an example where reparameterizing MAP "compressed the distribution", resulting in an different maximum. This made sense, but it still didn't give me too much intuition about what's going on.
If I understand correctly, MAP essentially combines a prior and some given information (observed values) to generate a probability distribution for the model parameters, and then returns the maximum. What's essentially confusing me is that "what you know beforehand", and the given information hasn't changed in a reparameterization - no new information has been added or removed from the system, so why is the math suggesting a new model?
In other words, if there's no change in information, and the models are the same too, shouldn't the most likely model be the same too? As I see it, reparameterizing simply assigns each model a new "name"; for instance, you go from identifying models by their likelihoods to identifying them by their their log odds. It's like going from one hot encoding to a regular encoding. Nothing has actually changed, so I wouldn't expect the math to work out any differently.
Answer: First, this question is much general what you state and could be restated as "why mode of a distribution is not invariant under parameterisation" i.e. $mode(f) \ne \phi^{-1}(mode(g))$ with $\phi(X)=Y$ and $X \sim f$ and $Y \sim g$ and much generally refers to how interpreting a continuous density function.
First this invariance exists in the discrete case. For the continuous case, you must remember that a point-wise definition of the density function as for the discrete case is not directly possible and that a possible proper manner to think about a density $f$ is to consider it as the derivative of its respective cumulative distribution $F$:
$$
f(x) = \frac{d}{dx} F(x),
$$
or in another way as:
$$
    \Pr[a\le X\le b] = \int_a^b f(x) \, dx.
$$
So $f$ is related to $X$ through a differentiation operator and the fact is that reparametrisation over $X$ does not acts similarly on $f$ because of this operation.
Then what does it means ? Interpret continuous density function point values with caution.


Problem on convergence of sequence of random variables

Question: Given any sequence of random variables $\{ X_n \}$; how do I show that there exists a sequence of real numbers $\{ \alpha_n \}$, such that $\{ \alpha_n X_n \}$ converges in probability to 0 ?
Comment: If any sequence of real numbers is allowed, why not simply pick $\alpha_n=0$ for all $n$?
Comment: The problem is that $ \left( \alpha_{n} X_{n}\right) $ is an element, not a sum.  The only way that any scalar element $ \left( X_n \right) $ can "converge" to zero is if it is multiplied by zero.  Is there a sum in this?  (I'm not sure how to make curly brackets).
Comment: Answered with a hint since this is a typical textbook question. I think the self-study tag is appropriate here.
Answer: As indicated in the comments, you have to state some additional assumptions for this to be interesting. This answer assumes $\alpha_n \neq 0$ for all $n$ and $P(\vert X_n\vert < \infty) = 1$ for all $n$.

Fix $n$ and observe / prove that for every $\epsilon_n >0 $ there exists a constant $M_n = M_n(\epsilon_n)$ such that $P(\vert X_n \vert > M_n) \leq \epsilon_n$. That is,
$$
P(\vert \alpha_n X_n\vert>\vert \alpha_n\vert M_n)\leq \epsilon_n.
$$
Can you pick $\epsilon_n$ and $\alpha_n$ so as to make $P(\vert \alpha_nX_n\vert > \delta) \to 0$ for any given $\delta>0$?