When is $2^2+...+n^2=p^k$.

Question: Find all $n>1$ such that $$\sum_{i=2}^ni^2=p^k$$
where $p$ is a prime and $k\ge 1$.
I tried to use the formula for the sum of the first $n$ perfect squares, $$\frac{n(n+1)(2n+1)-6}{6}=p^k$$
$$(n-1)(2n^2+5n+6)=6p^k$$
Furthermore $d=\gcd(n-1,2n^2+5n+6)=13$ or $1$.
Let's see when is equal $1$, we get these subcases $$\cases{n-1=1 \\ 2n^2+5n+6=6p^k}, \cases{n-1=2\\ 2n^2+5n+6=3p^k}, \cases{n-1=3\\ 2n^2+5n+6=2p^k} $$
$${\cases{n-1=6\\ 2n^2+5n+6=p^k}}$$
There are some restrictions on $p$ in the last $3$ subcases, but they're obvious. from these cases we get these solutions $$(p,q)\in\{(2,2),(13,1),(29,1),(139,1)\} $$
But the problem lies in the case when $d=13$, I can't get a handle on the subcases.
Comment: I think it would be more profitable to expand and refactor the numerator of the original term with $-6$ in it, since being equal to $p^k$, you can start to look at their gcd which puts a strong restriction if they can't share prime factors.
Comment: See the edit please
Comment: Indeed, $n(n+1)(2n+1)-6$ has a factorization. Can you find it? Look for a root. Then, you won't need to push the $6$ to the other side.
Comment: https://artofproblemsolving.com/community/c6h1639347p10323485 Might be helpful
Answer: If $d=1$, then you've done the computation correctly.
If $d = 13$, then note that $p=13$ is forced, so dividing by $13^2$ on both sides,
$$
\frac{(n-1)}{13}\frac{(2n^2+5n+6)}{13}  = 6 \times 13^{k-2}
$$
Since the quantities on the left are co-prime, we get that one of  $\frac{n-1}{13}$ or $\frac{2n^2+5n+6}{13}$ is a divisor of $6$, and the other is a multiple of $13^{k-2}$. However, for $n \geq 5$, $$2n^2+5n+6 \geq 2\times 5^2+5 \times 5 +6 \geq 81 > 78 = 13 \times 6$$
Therefore, $\frac{2n^2+5n+6}{13}$ can be a divisor of $6$ only if $n<5$. In this case, however, $\frac{n-1}{13}$ isn't even an integer (we want $n \geq 2$ so $n=1$ is ruled out).
It follows that $\frac{n-1}{13}$ must be a divisor of $6$ i.e. that $n-1 = 13,26,39,78$ i.e. that $n= 14,27,40,79$.

We will diverge from the approach in the AoPS post here, to show a different method. Indeed, one can substitute the values above and check that no more solutions are found , but we can do something that minimizes numerical computation.
We've already seen that $\frac{2n^2+5n+6}{13}>6$ for $n>5$. So if this expression is to be a multiple of a power of $13$ times a divisor of $6$ ,that power of $13$ must be at least $13$. Therefore, $2n^2+5n+6$ must be a multiple of $169$.
The idea now is to use the fact that we only need to test numbers belonging to the arithmetic progression $13k+1$. So we compute the following polynomial modulo $169$:
$$
2(1+13k)^2 + 5(1+13k)+6 \pmod{169} = 2(26k+1)+65k+5+6 = 13(9k+1)
$$
Therefore, we need $9k+1$ to be a multiple of $13$ : this doesn't occur for $k=1,2,3,6$. So no more solutions exist.

When is $2^2+...+n^2=p^k$.


Question on GAM p-value in summary output

Question: mod_gam1 <- gam(Overall ~ s(Income, bs="cr"), data=d)
summary(mod_gam1)
##
## Family: gaussian
## Link function: identity
##
## Formula:
## Overall ~ s(Income, bs = "cr")

## Approximate significance of smooth terms:
## edf Ref.df F p-value
## s(Income) 6.9 7.74 16.4 2e-14 ***

It significant p-value<0.05 mean that smooth component use for income was correct or that independent variable income had significant effect on overall?
I'm new to GAM. I read several comment, paper and lecture not on it but i'm still confuse.
Answer: It means that given the smoothing function that was applied, there is a significant association between $income$ and $Overall$. There is no way to judge from the output whether the specific spline you chose via bs="cr" is "correct". This rather depends on which type of model works best for your goal and application.
You can compare the performance of different models (GAMs and non-GAMs) and then base your inference about the influence of income on the best one, but the reported p-value and coefficients will always refer to the effect of income on the outcome given the specified model.
You can check the spline that was fit via plot(model_gam1) and employ some critical reasoning whether this makes sence. If the only "problem" with $income$ is that it is right-skewed, which is quite usual, a simple log-transformation might be sufficient, which avoids some interpretability issues of GAMs.


Finding the p value for binary data

Question: I have made an experiment with binary outcomes, and I struggle with calculating a p value to decide if it is significantly different than the control group.
There were two sets of identical cells: one treated with a specific molecule (Group 1), the other left untreated (Group 2). The results: out of 10 checked cells in Group 1, 7 died, whereas in Group 2 only 2 out of 10. Am I right, that I cannot use the t-Test for this type of data to decide if the difference is significant? What would be the appropriate method to calculate the p value (and where can I find some good resources that explain how to do it)?
I also have the possibility to check more than 10 cells, but it is quite time consuming. Is there a straightforward way to calculate an approximate N needed for significance?
Comment: Regarding sample size calculation, you'd need to specify the effect size you're looking for - finding a difference of 20% vs. 50% will require far fewer samples to achieve statistical significance compared to a situation where you're trying to find a statistically significant difference between 49% and 50%.
Answer: For such small samples the common test to use is Fisher's exact test.  For larger samples you can use a Chi-Squared test or a 2-sample test of proportions.  There are tools available for estimating sample size/power for these types of tests, either in statistical packages or you can Google for web based tools.

Finding the p value for binary data


Creating / Deleting User in Ember with Array Controller

Question: I am new to Ember and am trying to do a simple create / delete user. I am able to create a client, but can not delete them?
Client Controller:
export default Ember.ArrayController.extend({
  actions: {
    createClient: function(newName) {
        // Create the new Todo model
        var client = this.store.createRecord('client', {
            name: newName,
            avgMarkup: 2,
            quotes: 1
        });

        // Clear the "New client" text field
        this.set('newName', '');

        // Save the new model
        client.save();
    }
  }
});

I've then tried adding this:
    destroyRecord: function() {

        this.get('model').destroyRecord();

    }

And I have no luck. My view is this:

Clients Name:

    {{input type="text" id="new-client" placeholder="Please enter client name"
    value=newName action="createClient"}}
  {{#each}}

      <input type="checkbox" class="toggle">
      {{name}}
      <button {{action "destroyRecord" }} class="destroy"></button>

  {{/each}}

Is this doable with an Array Controller?
Thanks
Comment: You need an `itemController` for this to work. Otherwise, which item are you deleting?
Comment: Thanks Kalman. I do not currently have an itemController. What would this house? (I only have the clientController). The item I am hoping to delete is the user. So when a user is created (which I am able to do), an 'x' appears next to their name and clicking that would delete them. However, I keep getting errors.
Answer: To remove the respective user just pass it to your destroyRecord action:
In your template pass thiswhich correspond to the current user being iterated:
<button {{action "destroyRecord" this}} class="destroy">Destroy</button>

And then when someone click in destroy button, model will be the current user:
destroyRecord: function(model) {
    model.destroyRecord();
}

Comment: Thanks Marcio for the info! I just tried that and am now getting 'undefined is not a function'? I looked and it appears destroyRecord() should be valid?
Comment: Never mind, it was a syntax error. This worked! Thanks so much.


Baby Rudin Theorem 2.30 Counter Example?

Question: Theorem 2.30: Suppose $Y\subset X$. A subset $E$ of $Y$ is open relative to $Y$ if and
only if $E = Y\cap G$ for some open subset $G$ of $X$.
So, suppose we are considering subsets of the real line $X=R$.  Let $Y = [1,2]$ and $G = (0,3)$.  Then $E = Y\cap G = [1,2]$ which is not open.  So, it seems like $Y$ has to be open.  Is this Correct?
Perhaps, it really has to do with the definition of $E$ as being open relative to $Y$: to each $p\in E$ there is associated an $r > 0$ such that $q\in E$ whenever $d(p, q) < r$ and $q\in Y$.  Hence, in the counter example above, we do not consider any $q\not\in[1,2]$.  This does not seem to be a very stringent definition of openness.
Thanks in advance for anyone that can help explain this!
-Jason
Comment: A set is neither intrinsically closed nor open. A set is only open or closed relative to some topology. When we talk about a set being open or closed relative to some subset of a metric space, we are changing our topology from the metric topology on the whole space to the subspace topology.
Answer: Well... here is the way I see it now.  Let's say that $E$ is open with respect to $Y$ if for each $p\in E$ there exists a neighborhood $N_{r_p}(p)\subset X$ such that $N_{rp}(p)\cap Y\subset E$ then it seems obvious that my example is not counter.
Let $p$ be any point in $[1,2] = Y\cap G$, and $N_{r_p}(p)$ be any neighborhood containing $p$; then $N_{r_p}(p)\cap Y = N_{r_p}(p)\cap [1,2]\subset E = [1,2]$ so that $E$ is open with respect to $Y$.
Answer: $(X, \tau) $ be any topological space and $Y\subset X$.
Then $\tau_Y=\{G\cap Y : U\in \tau \}$ is a topology on $Y$( in fact smallest topology on $Y$ for which the inclusion map $\iota:Y\to X$ is continuous).
$(Y, \tau_Y) $ is called topological subspace of $(X, \tau) $.
$E\subset Y$ is open in $Y$ i.e $E\in \tau_Y$ iff $E=Y\cap G$ for some $G\in \tau$

For $X=\Bbb{R}$ , $Y=[1, 2]$ and $G=(0, 3) $ , $E=Y\cap G=[1, 2]$.
Then $[1, 2]$ is open in $[1, 2]$ i.e $[1, 2]\in \tau_Y$ ( be careful it doesn't say that $[1, 2]$ is open in $(X, \tau) $)
$E$ here seems trivial as underlying set in it's topology is always open.
Let's try to show $E= [1, \frac{3}{2}) $ is open in $([1,2], \tau_{[1,2]}) $
Comment: Hi Lost in Space, thanks so much for your reply.  Your nomenclature is a little new for me:  "$(Y,\tau_Y)$ seems clear, but I am little unsure about $U$.  However, it seems that the point is that (here I am substituting my own nomenclature) $(G\cap Y, \tau_Y)$ is a metric space in its own right.  Nevertheless, I believe my confusion originated from the definition of "open w/ respect to".  Would it be equivalent to state that $E$ is open with respect to $Y$ if for each $p\in E$ there exists a neighborhood $N_{r_p}(p)$ such that $N_{r_p}(p)\cap Y\subset E$?
Comment: True. As open balls form a base. $E\subset Y$ open in $Y$ implies $\forall p\in E, \exists N_{r_p}$ such that $N_{r_p}\cap Y\subset E$


CSS puro para fazer progresso em círculo

Question: Estou tentando fazer um círculo de progresso, mas não estou conseguindo.
Eu quero exatamente dessa forma.

Quero um círculo preto.
Uma borda em cinza menor que esse círculo, tipo uns 5px a menos.
Um círculo que é o progresso.

Achei algumas dicas na internet mas não estou conseguindo colocar em prática.
Não consigo fazer o círculo entender a porcentagem correta.
Até agora, fiz isso abaixo:

.percent {
  position: absolute;
  background-color: #000;
  width: 80px;
  height: 80px;
  left: 0;
  right: 0;
  top: 50px;
  margin: auto;
  color: #fff;
  font-size: 24px;
  display: table;
  text-align: center;
  border-radius: 50%;
}

.slice {
  width: 64px;
  height: 64px;
  border: 4px solid #fff;
  border-radius: 50%;
  top: 0;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  position: absolute;
}

.bar {
  border: 4px solid #f00;
  border-radius: 50%;
  width: 64px;
  height: 64px;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  position: absolute;
  clip: rect(0, 30px, 30px, 0);
  transform: rotate(0deg);
}

Comment: Tomei um negativo aqui sem motivos. Até quando?
Answer: Diego vamos por partes.
Primeiro o estilo clip:rect(); foi descontinuado. Agora o que se usa é o Clip-Path
Além disso o Rect quer dizer retângulo, antão nunca daria certo trabalhar com ele em forma de círculo. Para isso existe o clip-path:circle();
Referência do clip:rect(); (deprecated): https://developer.mozilla.org/en-US/docs/Web/CSS/clip
Referência do clip-path:circle(); https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path

Agora vamos ao que interessa, o código!
Usei como base o design e código que você postou, e fiz a animação usando @keyframes está 100% CSS não tem script. A técnica que eu usei não usa o clip:rect(); mas o resultado pode te interessar...
É um modelo bem simples mesmo, mas é para fins didáticos e você ver funcionando com o seu próprio código. Se quiser depois te passo uns links com modelo mais sofisticados só com CSS também.

.percent {
    position: absolute;
    background-color: #000;
    width: 80px;
    height: 80px;
    left: 0;
    right: 0;
    top: 50px;
    margin: auto;
    border-radius: 50%;
    }
    .slice {
    width: 64px;
    height: 64px;
    border: 4px solid #fff;
    border-radius: 50%;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    position: absolute;
    }
    .bar1 {
    border: 4px solid #f00;
    border-radius: 50%;
    width: 64px;
    height: 64px;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    position: absolute;
    border-top: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 4px solid transparent;
    border-left: 4px solid transparent;
    -webkit-animation: loader1 4s linear infinite;
            animation: loader1 4s linear infinite;
    }
    .bar2 {
    border: 4px solid #f00;
    border-radius: 50%;
    width: 64px;
    height: 64px;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    position: absolute;
    border-top: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 4px solid transparent;
    border-left: 4px solid transparent;
    -webkit-animation: loader2 4s linear infinite;
            animation: loader2 4s linear infinite;
    }

    @-webkit-keyframes loader1 {
        0% {
            border-top: 4px solid transparent;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
        }
        25% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
        }
        50% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
        }
        75% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid red;
            border-left: 4px solid transparent;
        }
        100% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid red;
            border-left: 4px solid red;
        }
    }

    @keyframes loader1 {
        0% {
            border-top: 4px solid transparent;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
        }
        25% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
        }
        50% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
        }
        75% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid red;
            border-left: 4px solid transparent;
        }
        100% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid red;
            border-left: 4px solid red;
        }
    }

    @-webkit-keyframes loader2 {
        0% {
            border-top: 4px solid transparent;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
            -webkit-transform: rotate(0deg);
                    transform: rotate(0deg);
        }
        25% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
            -webkit-transform: rotate(90deg);
                    transform: rotate(90deg);
        }
        50% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid red;
            -webkit-transform: rotate(180deg);
                    transform: rotate(180deg);
        }
        75% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid red;
            border-left: 4px solid red;
            -webkit-transform: rotate(270deg);
                    transform: rotate(270deg);
        }
        100% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid red;
            border-left: 4px solid red;
            -webkit-transform: rotate(360deg);
                    transform: rotate(360deg);
        }
    }

    @keyframes loader2 {
        0% {
            border-top: 4px solid transparent;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
            -webkit-transform: rotate(0deg);
                    transform: rotate(0deg);
        }
        25% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid transparent;
            -webkit-transform: rotate(90deg);
                    transform: rotate(90deg);
        }
        50% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid transparent;
            border-left: 4px solid red;
            -webkit-transform: rotate(180deg);
                    transform: rotate(180deg);
        }
        75% {
            border-top: 4px solid red;
            border-right: 4px solid transparent;
            border-bottom: 4px solid red;
            border-left: 4px solid red;
            -webkit-transform: rotate(270deg);
                    transform: rotate(270deg);
        }
        100% {
            border-top: 4px solid red;
            border-right: 4px solid red;
            border-bottom: 4px solid red;
            border-left: 4px solid red;
            -webkit-transform: rotate(360deg);
                    transform: rotate(360deg);
        }
    }


Postfix processes mails to addresses in own domain automatically

Question: I have a server which has the name server1.mydomain.com
This server is used mainly as web server and as mail server for several domains.
But it is NOT the mail server for mydomain.com. The mail server for mydomain.com is mail.mydomain.com.
Sending mails to various external email addresses is working fine. All the mails are delivered correctly. All the client domains hosted on this systems can both send and receive mails correctly.
But unfortunately, I have an issue when sending mails to firstname.lastname@example.com. It seems as if Postfix does not check who the responsible mail server for mydomain.com might be. Instead it expects itself to be the correct mail server. As none of the users of mydomain.com are known to my server (it isn't the mail server of the domain after all), all the mails sent to ...@mydomain.com keep getting an error message saying: "Recipient address rejected: User unknown in virtual mailbox table" which is clear to me...
How can I pursuade postfix to deliver mails (addressed to anyone from mydomain.com) to mail server of mydomain.com instead of processing them itself? All the other mails should be processed as is...
Best regards,
Tom
Answer: Add the mailserver as relayhost in your main.cf:
relayhost=mail.example.com

All Mails will be routed through this server, this will also be an advantage regarding SPF and DKIM checks.
Also, remove your domain from mydestination if it is in there. Only localhost and the hostname should be in there.
Comment: I do not want to send all mails through a relay host. They should be sent by my server directly to the recipient's smtp server.
Comment: In that case the answer by Esa is better for you. However, IMHO it is better to have a single outgoing mailserver, it makes managing the mail infrastructure much simpler in the long run.
Comment: Basically, I agree. But in my scenario, the mail server is sending mails for many different domains and sending them all to a relay host would mean additional configuration work for the relay host as well... As it is quite difficult to re-configure the relay host in my scenario, I would prefer a solution without relay host.
Answer: If there, remove the domain from mydestination or virtual_alias_domains.
You don't necessarily need to set up relayhost as Gerald suggests, because the server will by default use DNS to get the MX records for correct MTAs. Setting relayhost=mail.example.com requires that mail.example.com permits relay from your server1.example.com. (Whichever is the outgoing MTA, you should also have it specified as a permitted sender in your SPF record.)
Comment: I don't have `virtual_alias_domains` defined in my setup. Changing `mydestination` did not work so far. I just restarted the service and expected the server to behave differently, but still the same error message is shown.


Qual a diferença entre um compilador e executável do Windows e do Linux

Question: Quando se compila um programa simples para Linux, o compilador gera um executável que só funciona no Linux, mas quando se compila o Mesmo código com um compilador para Windows ele gera um executável que só funciona para Windows. Oque eu quero saber é qual diferença do processo de compilação nos 2 sistemas operacionais ?
Se o código é o mesmo, porque o resultado final é diferente ? Em qual parte da compilação que começa as diferenças ? é na parte da linkagem ? e porque existem essas diferenças ?
Comment: Entendi, mas bem que alguém poderia responder em português para ajudar a popular a versão brasileira do StackOverflow
Comment: https://stackoverflow.com/questions/32117572/why-does-a-linux-compiled-program-not-work-on-windows
Answer: Esta resposta é simplista, mas tenta dar uma ideia. Imagine que os programas são uma lista de solicitações para fazer algo.
Assim como num restaurante onde voce faz o pedido informando que quer bem passado, com ou sem cebolas, ..., isto é só o pedido (seu programa). Quem vai realmente preparar o prato (o kernel do sistema operacional) está na cozinha tenta preparar de acordo com o seu pedido (o programa).
Você só comerá o que quer se falar a mesma do cozinheiro.
O cozinheiro do linux fala ELF e o do windows fala PE. Então normalmente um não entende os pedidos feitos para o outro.
Mas tem alguns que são bilíngues e conseguem entender outros formatos. Um projeto muito legal é o wine que roda executáveis do windows no linux (por vezes com performance melhor que no próprio windows).
Então é só uma questão de entender o idioma para se comunicar com o sistema operacional.
Aqui tem um link para alguns tipos de formato de executável (em espanhol, mas acho que dá para ter uma idéia que tem um monte)


ANOVA vs. T-test for two groups

Question: I'm conducting an exercise intervention with office workers. The intervention will include Yoga classes and one to one coaching. I will be looking at the effects of the intervention on two dependent variables: 1. walking  2. the amount of time workers spend standing.
I have a control group and a treatment group. Walking data will be measured using pedometers, and standing time will be measured using a self-report questionnaire.
Am I right in thinking that a two-way unrelated ANOVA is needed to test for difference between the groups?
Comment: alternatively, you could inverse the relation and model the independent group variable as a function of the dependent variables. This is especially interesting with the multivariate type of dependent data if it has some structure, e.g. clusters. Plotting the dependent variables in a scatter plot with different colors for the groups, in order to see what kind of distribution you are dealing with, would at least not hurt.
Answer: Usually, we use ANOVA if there are more than two groups. But you also can use ANOVA with two groups, as you describe. In that case ANOVA will result in the same conclusion as an Student's t test, where $t^{2} = F$. See this R code:
<code># Makes example reproducible
set.seed(1)
# define sample size
n <- 100
# generate a group
group <- sample(0:1, n, replace= TRUE)
# generate a dependent variable that varies between groups
y <- rnorm(n) + group
# run a t test (variance must be assumed as being equel, otherwise the results do differ to those from ANOVA)
t.test(y ~ group, var.equal= TRUE)
# run ANOVA
summary(aov(y ~ group))
# F= 32.97
# See if t^2= F
t.test(y ~ group, var.equal= TRUE)$statistic**2
# t^2= 32.97
</code>
This is only true for the Student's t test where equal variances are assumed, while the results of a Welch t test differ to those of ANOVA. Further, since you have multiple dependent variables, maybe you want to have a look at a MANOVA, although I do not know whether this makes sense in your situation. Regardless what analysis you use you should check the assumptions.
If you do not have R you can simply put the code here.
Answer: It would be sensible to measure the amount of time your participants spend walking and standing before you carry out the treatment. You might even want to consider allocating them to control and treatment groups on this basis, so you can avoid accidentally using control and treatment groups that were different before you even started the treatment. If you don't measure beforehand, and especially if your study size isn't very large, it will be difficult for you to rule out the chance that any difference between your groups was just an accident of the more active people being assigned at random to to the treatment group, for example. You want control and treatment groups that are the same as each other before you start the treatment, in every way as far as possible.
Then you might want to look into using a repeated-measures ANOVA, so you can use the data from before and after treatment in one analysis.
Also, you will need to check whether your response data meet the assumptions required for the ANOVA, because if they do not then any conclusions may well be invalid. It is possible that your data will not meet the assumptions - for example, the distribution of values for time spent standing could be quite skewed. Consider transformation or an alternative statistical test if your residuals plots show up a problem.

ANOVA vs. T-test for two groups


Durandal Child router not finding views

Question: Just before I go into the issue here is an overview of my project structure
-- Common
    --services
    --views
    --viewmodels
 -- Product1
    --services
    --views
        -- mywork
            -- overview.html
            -- sections
                -- audit.html
                -- completed.html
                -- attention.html
                -- index.html
    --viewmodels
        -- mywork
            -- overview.js
            -- sections
                -- audit.js
                -- completed.js
                -- attention.js
                -- index.js

Now I've set up a section in Product1 called mywork that contains a child-router. The core route in shell.js is set using a splat.
{ route: 'myWork*details', moduleId: 'product1/viewmodels/myWork/overview', title: 'My Work' }

Then the child route is created as
var childRouter = router.createChildRouter()
            .makeRelative({ moduleId: 'product1/viewmodels/mywork/sections', fromParent: true })
            .map([
                { route: [''], moduleId: 'index', title: 'Overview', icon: 'fa-cogs', nav: false },
                { route: 'audits', moduleId: 'audits', title: 'Audits', icon: 'fa-list', nav: true },
                { route: 'completed', moduleId: 'completed', title: 'Tracked Records', icon: 'fa-list', nav: true },
                { route: 'attention', moduleId: 'attention', title: 'Requires Attention', icon: 'fa-list', nav: true }
            ]).buildNavigationModel();

The main issue is that when accessing any of the pages through a navigation bar I'm given the error...
View Not Found. Searched for "product1/views/mywork/sections/audits" via path "text!product1/views/mywork/sections/audits.html".

Yet the view for the overview page works fine defined by the route ['']. Any ideas as to why my other views are not found even though the viewmodels are and what is text! before the path in the error?
Answer: Note made, Child routes require at least a

 tag in the html files which I assume is due to some type of id assignment otherwise the view will not be found by a child router.

Durandal Child router not finding views


Question about method of finding homomorphisms from $\mathbb Z_4$ to $\mathbb Z_2 \times \mathbb Z_2$

Question: Question about methods of finding homomorphisms from $\mathbb Z_4$ to $\mathbb Z_2 \times \mathbb Z_2$
I've seen both methods, but one seems to fail here. What went wrong?

$\mathbb Z_4=\langle 1\rangle$, so homomorphism is defined by the value we give to $f(1)$. So we can give $4$ values, hence there are $4$ homomorphisms.
We know $\ker f\trianglelefteq \mathbb Z_4$, so $|\ker f|$ is either $1,2,4$.

With this method, I can only find $2$ homomorphisms, trivial and another in which $|\ker f|=2$. What went wrong?
Thanks,
Sammy
Answer: There are two types of homomorphism - the trivial homomorphism, and one in which the element of order $4$ gets mapped to an element of order $2$.
This second type can be realised in three distinct ways, because there are three different elements of order $2$ which you can pick - identifying the kernel gives the isomorphism type of the image, but it doesn't tell you anything about the actual images of the elements. All three of these homomorphisms have the same kernel.
Comment: So the second method can cause me "forgetting" some homomorphisms?
Comment: @SammyBinZayyin - it tells you that the images with that kernel are groups of order $2$ - then you have to go and see which groups of order $2$ are available. If you were mapping to a group of order $3$ or $5$ you'd have no homomorphisms of this type. As it is, since there are no elements of order $4$ in the image you've already excluded that possibility. Identifying the kernel and the isomorphism class of the potential image is a potential step on the route to a solution, in that it can help you to know where to look, but it doesn't solve the problem of identifying the concrete homomorphisms.


Como disparar uma função acionando uma rota http get

Question: tenho um servidor http e criei um servidor websocket pra rodar junto (igual os videos da rocket).
mas to com dificuldade pra isolar os comandos ... está tudo na página do server.js.
eu queria isolar os comandos que o server envia pro client. Eu tenho um controller que envia dados pro DB (POST request) ... e queria que toda vez que isso acontecesse o servidor enviasse algo pro client websocket....
já tentei de tudo e n to conseguindo usar os comandos websockets sem ser no server.js....
tenho o arquivo server.js:
<code> const { socketController } = require('./controllers/actuator/ActuatorController');

ws.on('request', (request) => {
  const client = request.accept(null, request.origin);

  socketController(client);

  console.log(`${new Date()} IP: ${client.remoteAddress} CONNECTED`);

  client.on('close', () => {
    console.log(`${new Date()} IP: ${client.remoteAddress} DISCONNECTED`);
  });

  // reciving client message in console.log
  client.on('message', (message) => {
    if (message.type === 'utf8') {
      console.log(message.utf8Data);
    }
  });
});
</code>
e o arquivo controller.js
<code>socketController(client) {
    client.send('mensagem para o cliente');
  }
</code>
eu queria criar uma outra função que ao chamar a rota fosse executado o client.send
a imagem sintetiza o que eu gostaria de fazer. obrigado
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Você pode tentar exportar o "ws" do seu server.js, daí você terá acesso a ele em toda a aplicação, depois no seu controller você importa ele.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Incorrect wxMaxima sha256sum() output

Question: I'm trying to calculate a hash using sha256sum function from stringproc package.
The output is obviously wrong for me (Windows 7, maxima-5.38.1).
E.g. hash from the docs example:
<code>(%i1) string: sha256sum("foo bar baz");
(%o1) dbd318c1c462aee872f41109a4dfd3048871a03dedd0fe0e757ced57dad6f2d7
</code>
For me it outputs 562fae81675643664087303002ecc95c547cf8a6c8173f3bc046da4244bcaef4
Other hash functions from the same package (SHA1, MD5) seem to work fine.
I've also tried running from xMaxima as well as the sha1.lisp file from version 5.37.2 with the very same result.
Somehow I suspect this to be related with maxima to run under Windows.
Did anybody see such issues?
Thanks a lot.
Comment: I see the same result as you, I'm running Maxima 5.39.0 on Linux. If this web site http://www.movable-type.co.uk/scripts/sha256.html is correct, the documented output is correct. I don't know why it seems to have become incorrect.
Comment: @RobertDodier, thanks for confirming. I've double-checked the output from the example with a couple of online hash calculators. They prove the hash from above. I think I'll file a bug and will look for devs to respond.
Thanks again.
Answer: This was a bug in Maxima. As described by one of developers:

The correct result was only computed when Maxima was compiled with gcl

Since then it was fixed. I've tested and can confirm that sha256sum() now gives correct hashes.
One can download the fixed sha1.lisp file here.

Incorrect wxMaxima sha256sum() output


How to calculate error of percentage ratio?

Question: I have the following problem:
I am counting a subset of cells from a tissue in Drosophila (fruit fly) at different days after "birth". At Day0 I obtain a population of flies, and dissect some of these flies at each time-point (I.e. I have a population of 30 flies at Day0. I dissect 3 of them right away, 3 more after 1 day, another 3 after 3 days, and so on up to 15 days after birth). To obtain these results I need to dissect (thus killing) the fly, so I cannot assay the differences in a single individual fly changing overtime, but I can assay the differences in the whole population.
What I obtain is a n number of around 50 for each timepoint. I could just plot the average for each timepoint on a chart and show the variation overtime this way. I would use standard error of the mean to build up the error bars.
My problem is that I need to show these data not as raw data, but as a ratio over the first Day, in order to better show the decrease in the cell number overtime. To do this, I am showing my data as a percentage ratio over day0 [(Day1Mean/Day0Mean)*100].
To make it more clear:
Day0 mean: 5
Day1 mean: 4
Day3 mean: 3.5
Day6 mean: 3.5
Day9 mean: 3
Day12 mean: 2.5
Day15 mean: 2
Instead of making a dispersion chart with those data (that are the average of the number of cells I counted) I would like to show them this way:
Day0: (Day0/Day0)*100 = 100%
Day1: (Day1/Day0)*100 = 80%
Day3: (Day3/Day0)*100 = 70%
Day6: (Day6/Day0)*100 = 70%
Day9: (Day9/Day0)*100 = 60%
Day12: (Day12/Day0)*100 = 50%
Day15: (Day15/Day0)*100 = 40%
Now my problem is this: If I am using the "raw" data, I can just plot them in and use the standard error calculated on the mean. I cannot use the standard error with the second kind of setup since my number is completely different. If it was possible I would have liked to "convert" the standard error to the new visualization. I thought it could be possible with some kind of mathematical transformation, in a similar way as reported in this document: http://www.census.gov/acs/www/Downloads/data_documentation/Accuracy/PercChg.pdf
Many thanks for Your help
Comment: "Var" is a standard abbreviation for the [variance](http://en.wikipedia.org/wiki/Variance).  In the notation of the second link, "E" stands for the arithmetic mean and "Cov" stands for the [covariance](http://stats.stackexchange.com/questions/29713). You don't say you have covariances, **which is the crux of the matter**: if your data are correlated from one time to the other, this should affect the SEs of the ratios as shown in the formulas.  And yes, percentage changes are just ratios multiplied by 100.
Comment: I finally managed to get in contact with a statistician from our department. It looks like it is possible to use the formula reported in http://www.census.gov/acs/www/Downloads/data_documentation/Accuracy/PercChg.pdf if it is only for chart representation needs, while it is needed another kind of statistics to analyze the data (which I was going to use anyway, in my case I will calculate the linear regression for different timeline and compare their slope to see if there are sig. differences).
Comment: This question appears to be a simpler case of http://stats.stackexchange.com/questions/26916/calculating-the-variance-using-delta-method.  Also, this reply by @jbowman appears to answer the question directly: http://stats.stackexchange.com/a/19580
Answer: This reply illustrates a key issue and provides some (simple) guidance.
Consider an experiment in which the growth of biological subjects is tracked daily.  Here, 24 subjects were measured on days 1 through 10:

Each set of 10 linked points represents a subject.
A collection of boxplots depicts the variation among subject sizes day by day: the box heights are directly proportional to this variation.

Using only this information, we would (naively) conclude there is a lot of uncertainty in the daily growth rates, expressed as ratios.  But there's actually very little because the size of a subject is strongly correlated with its size the previous day and all subjects are growing at the same (albeit varying) rates day to day:

The extremely short heights of these boxes testify to an extraordinarily consistent growth rate among subjects each day--even though those rates varied from day to day (as shown by the variable vertical positions of the boxes).
(These are artificial data created to illustrate the point that temporal correlation matters.)
The delta method formula accounts for this correlation with a covariance term.  The possible solutions, listed in descending order of accuracy and effectiveness, are

Compute subject-specific ratios from the experimental data and analyze those separately.
Compute covariances from the (raw) experimental data and use those in a delta-method calculation.
Do not report standard errors of the ratios.
Comment: Dear whuber, thanks for your answer. In the example you posted it is possible to track a single subject through time. In my case this is not possible: in order to acquire a number I need to dissect the fly (killing it), so at the next timeline I have to dissect another fly from the same population and acquire new data. This sort of remind me of the difference between a One sample T-test and a paired T-test. I will now edit my original post adding more info on the experiment, maybe that can help
Answer: The delta method is a way to approximate the variance of a function of random variable(s).
So in your case you want the variance of (X/Y) given in a formula involving the things you know such as the variance of X and the variance of Y.  It is just a Taylor series expansion of a function expressed in terms of random variables where expected values are taken and the higher order terms in the Taylor series are dropped.  However what is important regarding the formula which you did not mention was whether or not the variables X for say Day1 and Y for Day0 are correlated.  Common formulae based on the delta method assume independence.
Comment: @whuber Good.  Then the OP, Fomb can use it given that the formula is explained and Fomb knows what covariances and/or correlations are.  This OP is a PhD student in biology who may not be well-versed in statistics. Your explanatory comment may help.
Comment: The formula given by @jbowman, linked in a comment to the question, does not assume independence.


hack for jQuery to serialize values of  and  elements that are NOT inside a form

Question: I've been looking through a lot of posts on stackoverflow and elsewhere for this answer, but am still struggling to find something that will work with the boundaries of my application.
I am building off of an existing plugin (http://johnny.github.com/jquery-sortable/) to create a drag-and-drop html editor for elementary students. This plugin uses jQuery to serialize output into a format that resembles HTML source code, which consequently automatically updates a web page preview window. Contenteditable spans work well for allowing users to input values without accidentally editing the html tags themselves.
However, I cannot get the values of the input or select elements to be included in the serialized output. After looking at the jQuery API for serialize, it seems to indicate that <input> elements must be inside a form and also have a name attribute. This is not something that will work with the nature of my project, so I am seeking a hack/workaround.
If anyone is aware of a hack to make sure that input and select element values are included in serialized output, I would greatly appreciate it!
Edit: Here is a link to the most live demo-able state I could get it to: http://tinker.io/5bdab/5.
After trying a few places to put my code (jsbin, tinkerbin, jsfiddle), it seems they all have issues displaying an iframe? So you can't see the awesome fact that dragging and dropping elements in the middle column ultimately results in a live html page preview being changed next to it... However, you can still see that the results in the generated source code below get changed by being serialized (the part that I need assistance in figuring out how to serialize input and select elements so that their values will show up in the textarea).
However, the entire file is just in the HTML section (for convenience for instances like this, not for standard practice), since I link to external js files and have an internal style defined - if you were so inclined, you could just save the html file to your computer and check it out. I am not aware of a better option for displaying a live demo with supported iframes :/
Comment: Show the code you're using, the HTML and the jQuery. Ideally *also* show us [a live demo to reproduce your problem](http://jsfiddle.net/).
Comment: If your elements don't have `name`s, what will be used as the keys?
Comment: Have you considered wrapping the whole thing in a form, serializing, and then removing the wrapper just to have the serialized object?
Answer: Try wrapping all of your contents inside a div

    <input type="text" value="text text" name="text">

    <select name="single">
      <option>Single</option>
      <option>Single2</option>
    </select>
    <textarea name="textarea">textarea text</textarea>

and then serialize all of the elements inside this div
$("#wrapper").find("select,textarea, input").serialize();

Demo
Comment: Thanks, I did find this demo (or rather, a more rudimentary version of it) in my searches for an answer, but I don't think I can apply it to my project.
Comment: Dumb question: this worked (so thank you !!) but why is it that that without the "find()" part, the serialize didn't find the controls..?
Comment: Works with id too. $("#wrapper").find("#textId, #textId2").serialize();


Qual a maneira de criar tabela dinâmica em HTML e JS?

Question: Olá,
Estou com dificuldade em montar uma tela com HTML, CSS, JS, AngularJS.
Preciso montar uma tela onde o usuário escolhe a quantidade de parcelas, curso; e de acordo com isso deve montar : uma tabela onde na primeira linha deve conter os meses (que serão respectivos a quantidade de parcelas escolhidas); na segunda linha deve conter a quantidade de semanas de cada mês; na terceira linha os módulos do curso que será dividida proporcionalmente entre a quantidade de meses; na quarta as disciplinas desde dos respectivos módulos (cada módulo tem as disciplinas especificas); e na última linha as lições de cada uma das disciplinas. Lembrando que isso deve estar alinhado e será montado de acordo com o que o usuário vai escolher.
Não tenho ideia de como montar essa tela dinamicamente.
Alguém poderia me ajudar ????
Comment: Já fez algum código?
Answer: Amigo,
A sua pergunta não é especifica. Você tem problemas com a lógica ou com a linguagem/tecnologia (Angular, javascript, ...)? Também carece de informações. Como os dados serão recebidos no controller do angular? É um JSON? O que seria quantas semanas do mês? (a partir de mês contar, como você vai contar as semanas - se o primeiro dia do mês for um sábado, já conta como uma semana, etc, etc)
Supondo que a dificuldade seja na logica, tentei reproduzir o cenário proposto:

var project = angular.module("meuProjeto", [

        ]);

        angular.module("meuProjeto").controller('MeuController', function () {

            var self = this;

            this.parcelas = null;
            this.curso = null;
            this.cursos = [
                {
                    id: "1",
                    nome: "Curso 1",
                    modulos: [
                        {
                            id: "1",
                            nome: "Modulo 1",
                            disciplinas: [
                                {
                                    id: "1",
                                    nome: "Disciplina 1",
                                    licoes: [
                                        {
                                            id: "1",
                                            nome: "Lição 1"
                                        },
                                        {
                                            id: "2",
                                            nome: "Lição 2"
                                        }
                                    ]
                                },
                                {
                                    id: "2",
                                    nome: "Disciplina 2",
                                    licoes: [
                                        {
                                            id: "3",
                                            nome: "Lição 3"
                                        },
                                        {
                                            id: "4",
                                            nome: "Lição 4"
                                        },
                                        ,
                                        {
                                            id: "5",
                                            nome: "Lição 5"
                                        }
                                    ]
                                },
                                {
                                    id: "3",
                                    nome: "Disciplina 3",
                                    licoes: [
                                        {
                                            id: "6",
                                            nome: "Lição 6"
                                        }
                                    ]
                                },
                            ]
                        },
                        {
                            id: "2",
                            nome: "Modulo 2",
                            disciplinas: [
                                {
                                    id: "4",
                                    nome: "Disciplina 4",
                                    licoes: [
                                        {
                                            id: "6",
                                            nome: "Lição 6"
                                        }
                                    ]
                                },
                                {
                                    id: "5",
                                    nome: "Disciplina 5",
                                    licoes: [
                                        {
                                            id: "6",
                                            nome: "Lição 6"
                                        }
                                    ]
                                },
                                {
                                    id: "6",
                                    nome: "Disciplina 6",
                                    licoes: [ ]
                                }
                            ]
                        },
                        {
                            id: "3",
                            nome: "Modulo 3",
                            disciplinas: [
                                {
                                    id: "7",
                                    nome: "Disciplina 7",
                                    licoes: []
                                },
                                {
                                    id: "8",
                                    nome: "Disciplina 8",
                                    licoes: []
                                },
                                {
                                    id: "9",
                                    nome: "Disciplina 9",
                                    licoes: []
                                }
                            ]
                        },
                        {
                            id: "4",
                            nome: "Modulo 4",
                            disciplinas: [
                                {
                                    id: "10",
                                    nome: "Disciplina 10",
                                    licoes: []
                                },
                                {
                                    id: "11",
                                    nome: "Disciplina 11",
                                    licoes: []
                                },
                                {
                                    id: "12",
                                    nome: "Disciplina 12",
                                    licoes: []
                                }
                            ]
                        }
                    ]
                },
                {
                    id: "2",
                    nome: "Curso 2",
                    modulos: [
                        {
                            id: "1",
                            nome: "Modulo 1",
                            disciplinas: [
                                {
                                    id: "1",
                                    nome: "Disciplina 1",
                                    licoes: []
                                },
                                {
                                    id: "2",
                                    nome: "Disciplina 2",
                                    licoes: []
                                },
                                {
                                    id: "3",
                                    nome: "Disciplina 3",
                                    licoes: []
                                }
                            ]
                        },
                        {
                            id: "2",
                            nome: "Modulo 2",
                            disciplinas: [
                                {
                                    id: "4",
                                    nome: "Disciplina 4",
                                    licoes: []
                                },
                                {
                                    id: "5",
                                    nome: "Disciplina 5",
                                    licoes: []
                                },
                                {
                                    id: "6",
                                    nome: "Disciplina 6",
                                    licoes: []
                                }
                            ]
                        },
                        {
                            id: "3",
                            nome: "Modulo 3",
                            disciplinas: [
                                {
                                    id: "7",
                                    nome: "Disciplina 7",
                                    licoes: []
                                },
                                {
                                    id: "8",
                                    nome: "Disciplina 8",
                                    licoes: [
                                        {
                                            id: "3",
                                            nome: "Lição 3"
                                        },
                                        {
                                            id: "4",
                                            nome: "Lição 4"
                                        },
                                        ,
                                        {
                                            id: "5",
                                            nome: "Lição 5"
                                        }
                                    ]
                                },
                                {
                                    id: "9",
                                    nome: "Disciplina 9",
                                    licoes: []
                                }
                            ]
                        },
                        {
                            id: "4",
                            nome: "Modulo 4",
                            disciplinas: [
                                {
                                    id: "10",
                                    nome: "Disciplina 10",
                                    licoes: []
                                },
                                {
                                    id: "11",
                                    nome: "Disciplina 11",
                                    licoes: []
                                },
                                {
                                    id: "12",
                                    nome: "Disciplina 12",
                                    licoes: []
                                }
                            ]
                        },
                        {
                            id: "5",
                            nome: "Modulo 5",
                            disciplinas: [
                                {
                                    id: "13",
                                    nome: "Disciplina 10",
                                    licoes: []
                                },
                                {
                                    id: "14",
                                    nome: "Disciplina 11",
                                    licoes: []
                                },
                                {
                                    id: "15",
                                    nome: "Disciplina 12",
                                    licoes: []
                                }
                            ]
                        },
                        {
                            id: "6",
                            nome: "Modulo 6",
                            disciplinas: [
                                {
                                    id: "16",
                                    nome: "Disciplina 10",
                                    licoes: []
                                },
                                {
                                    id: "17",
                                    nome: "Disciplina 11",
                                    licoes: []
                                },
                                {
                                    id: "18",
                                    nome: "Disciplina 12",
                                    licoes: []
                                }
                            ]
                        }
                    ]
                },
            ];
            this.arrayMeses = null;

            this.cursoSelecionado = null;

            this.Exibir = function ()
            {
                angular.forEach(self.cursos, function (value, key) {

                    if(value.id == self.curso)
                    {
                        self.cursoSelecionado = value;
                    }

                });

                self.arrayMeses = self.GetArrayMeses();
                self.GetModulo();
            }

            this.GetArrayMeses = function()
            {
                var retorno = [];
                var i = 1;
                while(i <= self.parcelas)
                {
                    retorno.push(i);
                    i++;
                }
                return retorno;
            }

            this.GetModulo = function ()
            {
                //quantos modulos há e quantos meses
                var totalModulos = self.cursoSelecionado.modulos.length;
                var modulosPorMes = parseInt(totalModulos / self.parcelas);
                var resto = parseInt(totalModulos % self.parcelas);

                self.cursoSelecionado.meses = {};

                var ultimoIdProcessado = 0;

                angular.forEach(self.arrayMeses, function (value) {

                    self.cursoSelecionado.meses[value] = [];

                    var processadoMes = 0;

                    angular.forEach(self.cursoSelecionado.modulos, function (modulo, i) {

                        var modulosAdicionais = 0;

                        if (resto - (i - 1) > 0) {
                            modulosAdicionais = 1;
                        }

                        if(processadoMes < (modulosPorMes+modulosAdicionais))
                        {
                            if (ultimoIdProcessado < modulo.id)
                            {
                                self.cursoSelecionado.meses[value].push(modulo);
                                processadoMes++;
                                ultimoIdProcessado = modulo.id;
                            }
                        }
                    });

                });

            };

        });

        <input type="text" ng-model="M.parcelas" placeholder="Parcelas" />
        <select id="repeatSelect" ng-model="M.curso">
            <option ng-repeat="option in M.cursos" value="{{option.id}}">{{option.nome}}</option>
        </select>
        <input type="button" value="Exibir" ng-click="M.Exibir()"/>

                Meses
                Mês {{i}}

                Semanas
                4

                Módulos

{{j.nome}}

                Disciplinas

{{z.nome}}

                Lições

{{y.nome}}

Comment: Ericson, desculpe a falta de informação.
O JSON respectivo a essa tabela está nesse link

 https://1drv.ms/u/s!AkQLtKPK4v9kgcQMAhNdjoEvq_U1zw

Sobre a questão da semana, o usuário entra com a data e as semanas são contadas a partir do domingo e finalizadas no sábado, mesmo que a data inicie e finalize no sábado. Cada módulo tem suas próprias disciplinas.
Comment: O JSON é muito similar ao meu exemplo. Acho que é só ajustar as variáveis. Precisa de ajuda com mais alguma coisa?


What are some easy methods of making score typesetting software sound better?

Question: The timbre and dynamics of sound samples used in scoring softwares (like Sibelius, notion and musescore) are not always very convincing. The build-in playback is very good at making nice music sound terrible. Also, the dynamics over the orchestra is at times out of balance.
There are, of course, many ways of improving the sound quality. I could find thousands of sound samples online. However, many samples are expensive, huge (tens of GBs, takes ages to download), and difficult to use (you need to adjust a lot of settings). On the top of that, after spending the money and time, I cannot guarantee that I will get a better sound.
So here is my question: what's the most efficient way of getting the sound of a score's playback better, if I do not wish to spend too much time on it?
I am willing to use a different softwares, so please suggest the best software for doing this.
Comment: How easy do you find putting invisible tempo markings on pieces, changing individual note velocities, adding invisible dynamics, adding single-staff dynamics, putting on accidentals in passages with cross-staff beaming, or putting invisible articulation markings on *simile* passages? Those are some of the most common ways I've made my music sound passable on Musescore.
Answer: You can sometimes improve realism by 'over-notating' - adding phrasings, dynamics and articulations that would be done naturally by a live player.
For more control over balance, you can Export the score as individual audio tracks and manipulate them in a sequencer program.   And adding just one track 'live' through a microphone can make an enormous difference.  You must play SOME instrument?  Even if it's a bit of extra percussion.
For a quick fix, try the free demo of NotePerformer.  It's maybe rather over-praised!  But still a useful addition to your resources, at a very reasonable price.
Comment: For orchestral pieces, would you recommend sampling your own playing to play with it? Or would the MIDI be preferable in that case?
Answer: I am not affiliated with the company and not about to earn any commission. I am just a satisfied customer:
NotePerformer is a specific piece of software which is designed exactly for your use-case: it makes all the orchestral arrangements playback sound noticeably better, without any human intervention. It does that by detecting phrases and generating additional dynamics / articulations on the fly, based on deep analysis of your midi orchestrations.
It's not meant as a tool to make the final recording, but it's just about perfect for adding authenticity to playback of pieces that are written for a real orchestra.
Comment: So, I need 1) Finale/Sibelius 2)NotePerformer 3) A good sample library. NotePerformer itself doesn't seem to have a library. Is that right?
Comment: you don't need additional libraries - it's a self-contained solution (I don't think it can work with any other sample library). Just try the demo.
Comment: NotePerformer doesn't need an external library, and it even cannot use any external libraries. Wallander's sound generation is based on a different technology that doesn't use "recordings triggered by notes" in the same way as conventional samplers. It's more like adding together small component samples controlled by a behavioral model.
Answer: Depends on the scoring software. Finale (and Sibelius) can use the Garritan libraries which sound better than the free stuff and are on sale now and then. One can play with the Human Playback setting to help. Also setting up the correct reverbs (it has both a convolution reverb and an ambience reverb; I like the convolution version.) Human Playback does read things like expression or volume or tempo or pedal marks.


coredns certificate authority error when starting up k8s over Singularity-CRI

Question: I am only making my first steps into k8s land so please bare with me...
I am trying to bring up a small k8s cluster with Singularity as the containers runtime. I am following this procedure.
The problem is that the coredns pods fail to start, because of the following:
Jan 27 07:18:15 cent8ws sycri[1302]: #011Error: rpc error: code = Internal desc = could not set up pod network interface: error getting ClusterInformation: Get "https://[10.96.0.1]:443/apis/crd.projectcalico.org/v1/clusterinformations/default": x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "kubernetes")

I googled up this problem and found that it was raised many times, but none of the suggested soloutions worked for me. I'm not sure if it is related to the fact that I am using Singularity or not...
Please see some details about my system and the status of the ks cluster below.
Any help will be much appreciated.
Many thanks,
Oren

root@cent8ws ~]# cat /etc/redhat-release
CentOS Linux release 8.3.2011

[root@cent8ws ~]# rpm -qa | grep -e kub -e sing
webrtc-audio-processing-0.3-9.el8.x86_64
kubelet-1.20.2-0.x86_64
kubectl-1.20.2-0.x86_64
kubernetes-cni-0.8.7-0.x86_64
singularity-3.7.0-1.el8.x86_64
kubeadm-1.20.2-0.x86_64

kubeadm init --pod-network-cidr=10.0.1.0/24 --cri-socket unix:///var/run/singularity.sock --ignore-preflight-errors=All --upload-certs --node-name=$HOSTNAME

Jan 27 07:18:15 cent8ws sycri[1302]: #011Error: rpc error: code = Internal desc = could not set up pod network interface: error getting ClusterInformation: Get "https://[10.96.0.1]:443/apis/crd.projectcalico.org/v1/clusterinformations/default": x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "kubernetes")

[root@cent8ws ~]# kubectl get pods --namespace=kube-system
NAME                                          READY   STATUS              RESTARTS   AGE
coredns-74ff55c5b-dldl2                       0/1     ContainerCreating   0          5m50s
coredns-74ff55c5b-tbhkw                       0/1     ContainerCreating   0          5m50s
etcd-cent8ws.localdomain                      1/1     Running             0          5m52s
kube-apiserver-cent8ws.localdomain            1/1     Running             0          5m51s
kube-controller-manager-cent8ws.localdomain   1/1     Running             0          5m51s
kube-proxy-wb62q                              1/1     Running             0          5m50s
kube-scheduler-cent8ws.localdomain            1/1     Running             0          5m52s

root@cent8ws ~]# kubectl describe pods coredns-74ff55c5b-tbhkw --namespace=kube-system
Name:                 coredns-74ff55c5b-tbhkw
Namespace:            kube-system
Priority:             2000000000
Priority Class Name:  system-cluster-critical
Node:                 cent8ws.localdomain/192.168.122.1
Start Time:           Wed, 27 Jan 2021 07:17:47 +0200
Labels:               k8s-app=kube-dns
                      pod-template-hash=74ff55c5b
Annotations:          <none>
Status:               Pending
IP:
IPs:                  <none>
Controlled By:        ReplicaSet/coredns-74ff55c5b
Containers:
  coredns:
    Container ID:
    Image:         k8s.gcr.io/coredns:1.7.0
    Image ID:
    Ports:         53/UDP, 53/TCP, 9153/TCP
    Host Ports:    0/UDP, 0/TCP, 0/TCP
    Args:
      -conf
      /etc/coredns/Corefile
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Limits:
      memory:  170Mi
    Requests:
      cpu:        100m
      memory:     70Mi
    Liveness:     http-get http://:8080/health delay=60s timeout=5s period=10s #success=1 #failure=5
    Readiness:    http-get http://:8181/ready delay=0s timeout=1s period=10s #success=1 #failure=3
    Environment:  <none>
    Mounts:
      /etc/coredns from config-volume (ro)
      /var/run/secrets/kubernetes.io/serviceaccount from coredns-token-29225 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  config-volume:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      coredns
    Optional:  false
  coredns-token-29225:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  coredns-token-29225
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  kubernetes.io/os=linux
Tolerations:     CriticalAddonsOnly op=Exists
                 node-role.kubernetes.io/control-plane:NoSchedule
                 node-role.kubernetes.io/master:NoSchedule
                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason                  Age                   From               Message
  ----     ------                  ----                  ----               -------
  Normal   Scheduled               6m46s                 default-scheduler  Successfully assigned kube-system/coredns-74ff55c5b-tbhkw to cent8ws.localdomain
  Warning  FailedCreatePodSandBox  70s (x26 over 6m45s)  kubelet            Failed to create pod sandbox: rpc error: code = Internal desc = could not set up pod network interface: error getting ClusterInformation: Get "https://[10.96.0.1]:443/apis/crd.projectcalico.org/v1/clusterinformations/default": x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "kubernetes")

Comment: As I saw repository of Singularity-CRI has been archived by the owner. It is now read-only. See: https://github.com/sylabs/singularity-cri. They are working on new feature, maybe something is wrong with this cri. Can you try another one, for example CRI-O - https://kubernetes.io/docs/setup/production-environment/container-runtimes/#cri-o ?
Comment: Have you tried https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm/#tls-certificate-errors ?
Comment: Hi, Yes that link is one of the things I looked at. The crtificate looks ok, unless the issuer shouldn't be "kubernetes" or the CN=kubernetes-admin. If this is the case then what the values should be, and how can I change that?
Answer: To fix this issue. I ran below commands in centos machine.
for image pull latest
sudo kubeadm config images pull

removed the ip links:
ip link list | grep cali | awk '{print $2}' | cut -c 1-15 | xargs -I {} ip link delete {}

Try running these step in master and worker nodes.

move or remove the calico file in this location /etc/cni/net.d

restart the kubelete sudo systemctl restart kubelet.service

try to delete the not running pod kubectl delete pods coredns-558bd4d5db-t6d7r -n kube-system and kubelet get pods -A


Detectar clique prolongado, javascript

Question: Supondo estes tipos de clique:

1 CLIQUE
2 CLIQUES SEGUIDOS
CLIQUE PROLONGADO

eu sei como detectar o click normal e o dbclick mas como detectar o clique prolongado? aquele clique que você clica e segura por X tempo por exemplo?
Comment: podes usar o mousedown mas deves ter um timeout para confirmar. Quantos milisegundos é "longo"?
Comment: @Sergio seria legal ser ajustável, mas nesse caso seria algo como no **mínimo** 2 segundos **máximo** 4
Answer: Aqui fica uma sugestão:
Precisas de uma função que corra quando houver um clique longo. Como isso não existe nativo tens de criar uma outra função que seja passada ao oscultador de eventos para medir o tempo. Medir tempo e interromper caso houver um mouseup.
Criei uma função longclick que faz isso mesmo. Cria algumas variáveis que guardam em memória o estado das coisas e retorna uma função que, essas sim, é usada pelo oscultador de eventos.
Desse modo quando houver um mousedown, a variável mousedown vai servir de flag/bandeira pois vira true. Aí dispara um contador e se houver um mouseup a flag muda e anula o contador.
Fiz agora na hora, talvez seja possível otimizações, mas em geral a ideia está lá.
Edit: juntei agora mais lógica na minha função pois caso o mousedown e o mouseup acontecerem em elementos diferentes o clique não deve ser válido. Juntei também lógica para máximo e minimo.
var longclick = function (cb) {
    var min = 2000;
    var max = 4000;
    var time, self, timeout, event;

    function reset() {
        clearTimeout(timeout);
        timeout = null;
    }

    window.addEventListener('mouseup', reset); // caso o mouseup ocorra fora do elemento
    return function (e) {
        if (!self) {
            self = this;
            self.addEventListener('mouseup', function (e) {
                e.stopPropagation(); // para não subir no DOM
                var interval = new Date().getTime() - time;
                if (timeout && interval > min) cb.call(self, event);
                reset();
            });
        }
        event = e;
        time = new Date().getTime();

        if (e.type == 'mousedown') timeout = setTimeout(reset, max);
    };
};

var div = document.querySelector('div');
var handler = longclick(function (e) {
    alert('clicado entre 2 e 4 segundos! ' + e.type);
    this.style.backgroundColor = '#ccf';
});
div.addEventListener('mousedown', handler);

jsFiddle: http://jsfiddle.net/n2382xsk/4/
Comment: Muito boa a idéia, fez bem o que eu pensei que era criar uma função "padrão". Muito bom, Obrigada, qualquer dúvida retorno. Vou adaptar antes de marcar como correta..
Comment: Sergio, não sei se é valido por nesta pergunta mas como é associado irei perguntar-te. Eu gostaria de dar a sensação visual ao usuário para que ele saiba que está clicando e segurando.. No seu exemplo mesmo teria como usando o efeito `scale` do CSS demonstrar isso?
Comment: Levando em consideração o tempo que ele está a segurar a div, quanto mais tempo mais pequeno é o o número do `scale` (com um limite lógico) e quando ele liberar o clique a scale dá uma "pulsação" (um pequeno zoom, como o elastico dá quando repuxamos) e volta ao tamanho original, poderia me dar idéias de como faze-lo?
Comment: @Elaine podias fazer assim na sua versão mais simple: http://jsfiddle.net/n2382xsk/5/ Para ir crescendo podia-se juntar uma lógica com setInterval que vai aumentando o `scale` à medida que o tempo passa.
Comment: Gostei da forma com que aplicastes, porém nao consigo colocar para acompanhar o tempo, acho que ficaria um efeito legal se a cada 0.1s ele abaixasse 0.1 no scale respeitando o mínimo de 0.4 no scale total, para a div também não sumir.. eu teria que por chamando essas funções dentro da setinterval? é isso?
Comment: @Elaine se quiseres coloca uma pergunta nova sobre isso. Eu estou no móvel agora e não consigo ajudar muito, mas tendo um setInterval qu vai aplicando style.transform = 'scale('+ (size++) +')'; deve fazer o que procuras...
Comment: teria como voce reproduzir o efeito scale que voce fez nesse fiddle http://jsfiddle.net/n2382xsk/5/ só que na sua primeira versao? http://jsfiddle.net/n2382xsk/ a que estava sem a contagem máxima
Comment: @Elaine esse meu primeiro fiddle tinha um possivel problema, daí ter melhorado a resposta. Mas o código sem o máx e min com o que pretendes poderia ser assim: http://jsfiddle.net/n2382xsk/7/
Answer: De acordo com a resposta a esta pergunta em inglês "Listen to mouse hold event on website?", você precisa passar um parâmetro para os eventos mousedown e mouseup para que você possa identificar se o tipo do evento é mousedown, indicando assim que o usuário está mantendo pressionado o botão esquerdo do mouse.
O exemplo abaixo, também extraído da resposta à pergunta "Listen to mouse hold event on website?", irá executar um evento quando o usuário manter um clique prolongado em qualquer div:

$('div').on('mousedown mouseup', function mouseState(e) {
    var div = $('div');

    if (div.data('tempo-decorrido') == 0) {
        var horaAtual = new Date();

        // Devido ao JavaScript ser muito rápido, julguei necessário
        // diminuir um milisegundo da hora atual para evitar que o código
        // após esse if sempre retorne zero em newDate() - div.data('momento-ultimo-click').
        horaAtual.setMilliseconds(horaAtual.getMilliseconds() - 1);

        div.data('momento-ultimo-click', horaAtual);
    }

    // Obtém o tempo decorrido em milisegundos.
    var tempoDecorrido = new Date() - div.data('momento-ultimo-click');

    // Verifica se já se passou o tempo mínimo
    if (tempoDecorrido > div.data('tempo-minimo') && e.type == "mousedown") {
        // Código executado ao manter o clique prolongado.
        console.log("Evento clique prolongado executado.");
    }

    // Reseta o momento do último clique para que o tempo mínimo seja considerado novamente antes de atirar o evento.
    if (tempoDecorrido > div.data('tempo-maximo')) {
        div.data('momento-ultimo-click', new Date());
    }
});

O autor da resposta original também disponibilizou um exemplo no site JSFiddle, no qual você pode simular evento de manter um clique prolongado na div.
Comment: Gostei da forma com que trabalhou com os parametros, é sim o que eu desejo, +1
Comment: @Elaine atualizei a resposta considerando o tempo mínimo e máximo. Assim será que fica mais ou menos próximo ao que você precisa?
Comment: @Sergio obrigado por me informar sobre esses problemas. Atualizei a resposta com as devidas correções.
Comment: Achei legal a pergunta mas ele acaba detectando cliques juntos, como expliquei ao @Sergio ele deve ter um tempo mínimo e máximo para ser considerado um clique prolongado

Detectar clique prolongado, javascript


Pitch or frequency?

Question: There seems to be confusion (certainly with me!) about the relationship between pitch and frequency. Trying to clear it up finds contrasting ideas. Obviously, when a note has a higher frequency than another, it is a 'higher' ( further to the right on a piano) note. Would it be correct to say the pitch of a note is, say, C, without specifying whether it's C4 or C5, for instance?
I'm not referencing the 'same note played on different instruments', but perhaps it's as simple as we call the frequency 440Hz as pitch 'A' (not always, I know), but there are other frequencies also called 'A' - like 220Hz, and 880Hz.
The other question is related (and my answer accepted), but that's all, I think.
Comment: @user1803551, I don't think the linked question is asking the same thing as this question. The linked question seems to be based on a misconception of how pitches relate to frequencies. So while it might solicit answers with similar info, I don't think the question itself is the same (this question isn't based on a misconception, for example). I also think this one will be more useful to future readers with this same specific question.
Comment: @user1803551 - surely a question would have a duplicate, rather than any answer to a question?
Comment: Possible duplicate of [Do musical instruments pitched at different frequencies play different notes when compared to each other?](https://music.stackexchange.com/questions/65709/do-musical-instruments-pitched-at-different-frequencies-play-different-notes-whe)
Comment: @jdjazz But my answer there answers the question here, and duplicates are considered by answer, and not by question.
Comment: You'd think so, but no, see [here](https://meta.stackexchange.com/a/10844/274088). Otherwise, I can just copy-paste my answer from there to here.
Answer: Frequency refers to the measurable number of cycles per second (Hz) of a periodic sound wave.
Pitch refers to (subjectively) how low or high that wave sounds to us as a note. The way I see it, pitch is the log-scale way that humans subjectively perceive frequency.
An unfortunate medical condition that highlights the difference between frequency and pitch is Diplacusis - people hearing the same frequency as different pitches in each ear.

Would it be correct to say the pitch of a note is, say, C, without specifying whether it's C4 or C5, for instance?

Out of context, it would be confusing, because C4 and C5 are not the same pitch - one sounds subjectively higher than the other. (It might be OK if it were obvious from context which C you were talking about).
In our musical system, I think it's OK in some contexts to say that C4 and C5 are the same note, as long as we're talking in a context where the idea of octave equivalence is understood.
Comment: See also loudness (perception) versus intensity (measurable and scientific).
Answer:
Would it be correct to say the pitch of a note is, say, C, without specifying whether it's C4 or C5, for instance?

It might be helpful to consider the distinction between a pitch and a pitch class. A pitch is a specific location on a keyboard: A4, for instance, is a pitch.
But a pitch class is a collection of all pitches related by octave equivalence. In other words, every single A on the keyboard (and every other A out there) belong to the pitch-class A.
Such a distinction is really helpful when understanding post-tonal music that operates on the notion of octave equivalency. Stravinsky's arrangement of Happy Birthday, for instance, is best understood from a standpoint of pitch classes.
Answer: To combine it all in one simple answer - No, C4 and C5 are different pitches.  They are the same 'pitch class', which might be loosely described in some circumstances as the same 'note'.  But they are different pitches.
Frequency is the scientific description of pitch.
Comment: That might be half an answer - what about frequency?
Answer: In my way of understanding, pitch in musical terms refers to the frequencies associated with musical notes, where as frequency might be associated with tones that are in between notes and not musical in nature at all. Pitch seems to be musical and frequency seems to be associated with Physics. Another way to look at it is pitches are things we can hear and frequencies can include pitches but can extend well below or above the capability of the human ear to perceive.
Comment: @skinnypeacock -- I do support your notion that frequency belongs to physics, but pitch belongs to _perception_. Any (audible) frequency can give rise to a pitch perception. Consider what we commonly call a "high-pitched sound." This does not need to lie in a particular scale to be meaningful. Or consider pitch-bending wheels on keyboards; it is still a pitch when it is bent.
Comment: @skinnypeacock -- If you have a reference color, and try to match it but miss by a little bit, you might say that the second color is off. When a pitch doesn't quite match a reference pitch, the pitch is off, but it is still a pitch in the same way that the color that is off is still a color. Off-pitch doesn't mean "not a pitch", but something more like "not the reference pitch."
Comment: @DavidBowling- This discussion is getting a little long winded but I've noticed one point that wasn't made clear before. Frequencies are measurable simply by counting the vibrations, no changes, where as pitches are seemingly not so absolute and may be varied slightly leaving a little wiggle room when applied to musical tones.
Comment: @skinnypeacock -- Yes, it is a bit long-winded, sure to be banished to chat at any moment. Your last comment hits on the point I was trying to make from the start: frequency is an objective, measurable quantity, while pitch is a subjective perceptual phenomenon. Pitch is how we interpret sound wave frequencies.
Comment: We might refer to a note as being 'off pitch' if its frequency isn't quantised to the currently-established musical framework.  But it would still have a 'pitch', albeli a wrong one!
Comment: @Laurence Payne - Off pitch indicates to me that it is indeed off and not on an accepted definition of a pitch. No wonder folks are confused by this, I would say the off pitch tone was out of tune and needed adjustment to become on pitch, but that's just me. And how do you call pitches when they are frequencies above or below the hearing capabilities of the ear, are there pitches associated with broadcast frequencies?
Comment: Frequency is a physical property of sound waves (and of other waves), but pitch is a perceptual property (or a psychoacoustic property) of _sound waves_. [See this](https://en.wikipedia.org/wiki/Pitch_(music)). Our sense of pitch allows us to rank pitches on a musical scale, but which scale? The western 12-tone scale? The 17-tone or 22-tone scales associated with Persian music? What about other microtonal scales? I think that we have to grant that pitch is continuous, and we use our sense of pitch to organize pitches in whatever scales are convenient or familiar.
Comment: @DavidBowling - It is my understanding that a pitch is a designated frequency, where as a frequency is not necessarily a designated pitch. Am I wrong? I think that pitch is designated as opposed to continuous.
Comment: How many microtonal scales are there? The 12-tone scale is somewhat arbitrary, so how do we arrive at which pitches are defined? What about different pitch standards (e.g., 440 Hz vs 432 Hz). The way I understand it, we use pitch to organize sounds on a scale, we don't use scales to define what is and what is not a pitch. Frequency is the physical property of sound waves that gives rise to the perceptual phenomenon of pitch. Since frequency is continuous, so is pitch (more or less).
Comment: @DavidBowling- I can't argue with much of what you are saying but your question " how do we arrive at which pitches are defined" doesn't really translate to " how do we arrive at which frequencies are defined" does it? It seems pitches are assigned to specific frequencies rather than the other way around. Pitches have to do with what we can hear, frequencies have to do with a much broader spectrum. I think frequencies come before pitches in how things should be explained.
Comment: You should look at the article I linked to, because I think we are talking past each other a little bit. From the Wikipedia article: "Pitch is an auditory sensation in which a listener assigns musical tones to relative positions on a musical scale based primarily on their perception of the frequency of vibration. Pitch is closely related to frequency, but the two are not equivalent.... Pitch is each person's _subjective perception_ of a sound wave, which cannot be directly measured."
Comment: @ David Bowling - It appears to me that you seem to be supporting my original statement that frequencies are physics, and pitch refers to music,( what we know as musical tones). Pitch seems to be assigned to frequency, in my opinion, where as frequency is not necessarily assigned to pitch, and I don't feel pitch is continuous when applied to what we know as music.
Comment: @David Bowling- interesting point, what we perceive as a high pitched sound is actually quite low on a wide band frequency spectrum, and I suspect pitch bending is accomplished by going off pitch, so does that mean it's still on pitch?

Pitch or frequency?


Time ago with specific time format

Question: How do we convert specific time format ("yyyy-MM-dd-HH-mm-ss") to calculate time ago in Flutter? I have the codes below for my android app, however I am trying out Flutter which uses Dart. Can someone provide a pointer here on how we can achieve this?
Date currentDate = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", locale);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dd = sdf.format(newsDate);
Date gmt = null;
try {
    gmt = sdf.parse(dd);
} catch (ParseException e) {
    e.printStackTrace();
}

long duration = currentDate.getTime() - gmt.getTime();

long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

Comment: As an complete aside, in your Android app consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. Also the point in formatting `newsDate` only to parse it back is slipping me. You are getting an equivalent `Date` only without the fraction of second.
Comment: See [`DateTime.difference`](https://api.dart.dev/stable/2.5.2/dart-core/DateTime/difference.html).
Answer: This is how I've implemented it:
String timeAgoSinceDate({bool numericDates = true}) {
  DateTime date = this.createdTime.toLocal();
  final date2 = DateTime.now().toLocal();
  final difference = date2.difference(date);

  if (difference.inSeconds < 5) {
    return 'Just now';
  } else if (difference.inSeconds <= 60) {
    return '${difference.inSeconds} seconds ago';
  } else if (difference.inMinutes <= 1) {
    return (numericDates) ? '1 minute ago' : 'A minute ago';
  } else if (difference.inMinutes <= 60) {
    return '${difference.inMinutes} minutes ago';
  } else if (difference.inHours <= 1) {
    return (numericDates) ? '1 hour ago' : 'An hour ago';
  } else if (difference.inHours <= 60) {
    return '${difference.inHours} hours ago';
  } else if (difference.inDays <= 1) {
    return (numericDates) ? '1 day ago' : 'Yesterday';
  } else if (difference.inDays <= 6) {
    return '${difference.inDays} days ago';
  } else if ((difference.inDays / 7).ceil() <= 1) {
    return (numericDates) ? '1 week ago' : 'Last week';
  } else if ((difference.inDays / 7).ceil() <= 4) {
    return '${(difference.inDays / 7).ceil()} weeks ago';
  } else if ((difference.inDays / 30).ceil() <= 1) {
    return (numericDates) ? '1 month ago' : 'Last month';
  } else if ((difference.inDays / 30).ceil() <= 30) {
    return '${(difference.inDays / 30).ceil()} months ago';
  } else if ((difference.inDays / 365).ceil() <= 1) {
    return (numericDates) ? '1 year ago' : 'Last year';
  }
  return '${(difference.inDays / 365).floor()} years ago';
}

then for example, you can embed it inside of an object, and call it like this:
Text(viewmodel.post.timeAgoSinceDate())

Time ago with specific time format


Get currently active 'simpletest' user during test

Question: How do you retrieve the current 'simpletest' user during a simpletest.
During a simpletest is the $user GLOBAL from the test environment or the live environment?
Answer: Inside the test method?
No idea what in $GLOBALS['user'] is, but you certainly can't rely on it. You are never "logged in" in that context, you are only logged in when doing requests with drupalGet()/drupalPost().
If you used drupalLogin(), you can look for $this->loggedInUser. If not, then it's not possible, other than maybe doing a GET to /user and then trying to get the username from title.
Inside a page callback, $GLOBALS['user'] is the current user, just like you'd expect.
Comment: Thank you @Berdir. $this->loggedInUser and user_load did the trick and makes for a way cleaner test class.


Transform a vector of int to a vector of str

Question: I'm trying to convert a vector<int> to a vector<string>. Using std::transform I used std::to_string to convert the int to string but I keep getting an error. Here's my code
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>

int main(){
    std::vector<int> v_int;
    std::vector<std::string> v_str;

    for(int i = 0;i<5;++i)
        v_int.push_back(i);

    v_str.resize(v_int.size());
    std::transform(v_int.begin(),v_int.end(),v_str.begin(),std::to_string);
}

but I'm getting this error
 no matching function for call to 'transform'
        std::transform(v_int.begin(),v_int.end(),v_str.begin(),std::to_string);
        ^~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:1951:1: note:
      candidate template ignored: couldn't infer template argument
      '_UnaryOperation'
transform(_InputIterator __first, _InputIterator __last, _OutputIterato...
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:1961:1: note:
      candidate function template not viable: requires 5 arguments, but 4 were
      provided
transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputItera...

Answer: std::to_string is an overloaded function, so you'll need to provide a cast to disambiguate
std::transform(v_int.begin(),v_int.end(),v_str.begin(),
               static_cast<std::string(*)(int)>(std::to_string));

Or use a lambda
std::transform(v_int.begin(),v_int.end(),v_str.begin(),
               [](int i){ return std::to_string(i); });

Comment: @gauravsehgal The type in the cast is the same type as `to_string`'s overload for `int`. Its only effect is that it makes explicit which overload you want. You can view it as manual overload resolution.
Comment: @gauravsehgal I'm casting it to a pointer to function type that takes an `int` argument and returns `std::string`. Since the OP has a `vector`, that's the relevant overload from the list I linked to above.


Multiple Django Projects using IIS but Getting Blank Page on Second Site

Question: I'm running two django projects in IIS with wfastcgi enabled.  The first django project is running without an issue but the second project displays a blank page (code 200) returned.
Second Project Info:
A virtual folder, within it's own application pool in IIS, is created to host the second project.  The second project was created in an python environment folder.  The second project runs from django using python manage.py runserver 0.0.0.0:8080, but displays a blank page when browsing to the virtual folder page.
The root folder was granted with "everyone" full control access to all sub-folders
for the second project, wfastcgi application and handler is pointing to the virtual environment python and wfastcgi file correctly.
Can you have two wfastcgi applications and handlers "Second Python FastCGI"
C:\project_folder\project_env\Scripts\python.exe|C:\project_folder\project_env\lib\site-packages\wfastcgi.py"
I wanted them separate so that two developers don't interfere with each others work, but they need to run within the same server and port.
Answer: I resolved the problem by editing the web.config file and removing the static handler from it.  The static handler was being used instead of the FastCgiModule handler.  The static handler should be moved below the FastCgiModule.


How to solve this differential equation with power 2 and trigonometry?

Question: $\ddot{x} = (\tan x) \dot{x}^2$
Do I have to use power series?
Comment: Are you sure you have written it correctly ?
Answer: HINT: Divide by $\dot x$ and integrate,
$$
\int\frac{\ddot x}{\dot x}\,dt=\int \dot x\tan x\,dt.
$$
I think you can take it from that hint? Tell me otherwise, and I will give a first step.


Como resgatar um valor de inicialização de um plugin?

Question: Vou expor o problema específico, mas eu sempre tive essa dúvida em um contexto geral: inicializei o plugin owl carousel. Tive a necessidade de implementar uma progress bar nele. Porém, eu preciso informar a velocidade de transição = o parâmetro autoplayTimeout pra progress bar durar o tempo correto. Segue o código:
var carousel = $('.owl-carousel');

carousel.owlCarousel({
  loop: true,
  margin: 10,
  nav: true,
  items: 1,
  autoplay: true,
  autoplayTimeout: 7000,
  onInitialized: startProgressBar,
  onTranslate: resetProgressBar,
  onTranslated: startProgressBar,
});

function startProgressBar() {
  $(".slide-progress").css({
    width: "100%",
    transition: "width 7000ms linear"
  });
}

function resetProgressBar() {
  $(".slide-progress").css({
    width: 0,
    transition: "width 0s"
  });
}

Como eu conseguiria acessar o valor autoplayTimeout da variavel de inicialização do plugin e informar no transition: "width <VALOR DE autoplayTimeout> linear" da função startProgressBar()?
Obrigado.
Answer: A sua variável "carousel" está definida em um contexto global, então acredito que ela possa ser usada normalmente dentro da sua função.
function startProgressBar() {
  $(".slide-progress").css({
    width: "100%",
    transition: "width "+carousel.data('owlCarousel').autoplayTimeout+"ms linear"
  });
}

Se esse cara carousel.data('owlCarousel').autoplayTimeout retornar undefined ou disparar algum erro, tente usar carousel.data('owlCarousel').settings.autoplayTimeout. Depende da versão do plugin que você esta usando.
Comment: Muito obrigado Big Boss. Sua resposta me fez avançar. Consegui acessar com a seguinte sintaxe: carousel.data('owl.carousel').settings.autoplayTimeout.
Fui investingando com console.log...
Porém quando coloco isso concatenado a string da propriedade transition  "Uncaught TypeError: Cannot read property 'settings' of undefined" não entendo muito bem os "pormenores" do js, mas acho que esse valor não existe quando eu triggo o onInitialized. Continuo na busca.
Comment: A funcao startProgressBar, deve ser chamada após a inicialização do plugin (carousel), se não ele não vai ter nada para ler. A onde que você esta chamando esta função?
Comment: logo abaixo da inicialização do plugin, se vc ver na pergunta, a função é chamada no evento onInitialized, fornecido pelo próprio plugin
Comment: @user7069 neste caso, talvez funcione substituindo o "carousel.data('owlCarousel')" pelo this (depende do contexto).