Extension builder overwrite fe_user TCA

Question: If I try to extend fe_user table by creating a new Model Object on extension builder in Typo3 6.1.7, it overwrites TCA by writing those lines in ext_tables.php of my extension:
<code>\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addLLrefForTCAdescr('fe_users', 'EXT:voiwizard/Resources/Private/Language/locallang_csh_fe_users.xlf');
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages('fe_users');
$TCA['fe_users'] = array(
    'ctrl' => array(
        'title' => 'LLL:EXT:voiwizard/Resources/Private/Language/locallang_db.xlf:fe_users',
        'label' => 'prova',
        'tstamp' => 'tstamp',
        'crdate' => 'crdate',
        'cruser_id' => 'cruser_id',
        'dividers2tabs' => TRUE,

        'versioningWS' => 2,
        'versioning_followPages' => TRUE,
        'origUid' => 't3_origuid',
        'languageField' => 'sys_language_uid',
        'transOrigPointerField' => 'l10n_parent',
        'transOrigDiffSourceField' => 'l10n_diffsource',
        'delete' => 'deleted',
        'enablecolumns' => array(
            'disabled' => 'hidden',
            'starttime' => 'starttime',
            'endtime' => 'endtime',
        ),
        'searchFields' => 'prova,',
        'dynamicConfigFile' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) . 'Configuration/TCA/User.php',
        'iconfile' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extRelPath($_EXTKEY) . 'Resources/Public/Icons/fe_users.gif'
    ),
);
</code>
This code overwrites the original fe_users's TCA configuration and the back-end [website user][1] table becomes inaccessible.
Is there any way to prevent this or do I have to delete those lines every time I want to save the changes in the extension builder?
Comment: Please add your edit as answer and accept it by clicking the check sign. This way it's a community wiki that you answered yourself.
Answer: I've found an error in my relationship:
To properly extend fe_users table with a Model Object in Extension Builder, I had to "extend existing model class" \TYPO3\CMS\Extbase\Domain\Model\FrontendUser instead of "map to existing table" fe_users.

In this way, everything works as expected!

Extension builder overwrite fe_user TCA


Nameserver and Domain config in WHM/Cpanel

Question: Just installed a fresh CPANEL/WHM on a VPS.
I only have one IP address.  What is the correct way to setup nameservers in WHM so that I can point the registered domains (i.e. from namecheap or godaddy or similar) to the nameservers at the server?
Alternatively, is it better to use the nameservers at the registrar and point the the domain directly to the new ip address that's registered in CPanel?
Comment: Administration panels are off-topic on Server Fault.
Answer: You need to edit the name server IPs at your domain registrar control panel. Most registrars allow to have two name servers in with the same ip. You can set up private name servers pointing to your server; like
<code>ns1.yourdomain.com >> your_server_ip
ns2.yourdomain.com >> your_server_ip
</code>
By doing this your domain will start resolving to your server. Then you need to have proper entries in your named.conf. This can be done using the cpanel. Do let us know if you have further queries.
Comment: @Augustine - Indeed, I have done that.  I think my larger issue is setting it up in WHM and Cpanel...  THIS is where I'm basically clueless.


Consider the polynomial $x^3+2x^2-5x+1$ with roots $\alpha$ and $\alpha^2+2\alpha-4$. Find the third root in terms of $\alpha$

Question: Consider the polynomial $x^3+2x^2-5x+1$ with roots $\alpha$ and $\alpha^2+2\alpha-4$. Find the third root $\beta$ in terms of $\alpha$
I have that $\alpha^3+2\alpha^2-5\alpha+1 = 0$, so $\alpha^3 = -2\alpha^2+5\alpha -1$.
And, $(\alpha^2+2\alpha-4)^3+2(\alpha^2+2\alpha-4)^2-5(\alpha^2+2\alpha-4)+1=0$ gives $\alpha^6+6\alpha^5+2\alpha^4-13\alpha^2+54\alpha-11=0$
Additionally, $\alpha^6 = (-2\alpha^2+5\alpha -1)^2 = 4\alpha^4-20\alpha^3+29\alpha^2-10\alpha+1$
I do not know how to move forward from here. I tried setting $f(x)$ equal to the product of the roots and expanding that out to a 14-term polynomial with $\alpha$ and $\beta$ coefficients but that seems unproductive.
Comment: The roots sum to $-2$.
Comment: @kt046172 The relations between the coefficients and root sum, product etc. are given by Vieta's Relations.
Comment: See also https://math.stackexchange.com/questions/1767252/expressing-the-roots-of-a-cubic-as-polynomials-in-one-root
Comment: @Batominovski can you clarify how you arrived at this?
Comment: ...and the root product is -1.
Comment: Check Vieta's Formulae [here](https://en.wikipedia.org/wiki/Vieta%27s_formulas).
Answer: Note
$$\alpha (\alpha^2+2\alpha -4)\beta =-1$$
Thus,
$$\beta =- \frac1{\alpha (\alpha^2+2\alpha -4)}
 =- \frac1{\alpha^3+2\alpha^2-4\alpha}
 =- \frac1{5\alpha -1 -4\alpha} =\frac1{1-\alpha}
$$
Answer: Since by Vieta's formulas the sum of the roots is $-2$, there is not much to do here: given that two roots are $\alpha$ and $\alpha^2+2\alpha-4$, the third one has to be $-\alpha^2-3\alpha+2$.

The interesting question, however, is: how do we realize that there are two
   roots $\alpha,\beta$ fulfilling $\beta=\alpha^2+2\alpha-4$ ?

Well, the discriminant of the polynomial is $361=19^2$, so all the roots are real  and the Galois group over $\mathbb{Q}$ is not $S_3$ but something simpler. By considering the depressed cubic we have
$$ \frac{27}{38\sqrt{19}}\,\underbrace{p\left(\frac{2}{3}(x\sqrt{19}-1)\right)}_{q(x)}=4x^3-3x+\frac{7}{2\sqrt{19}} $$
so by trigonometry we have that a root is given by
$$ \zeta = -\frac{2}{3}+\frac{2}{3}\sqrt{19}\cos\Big(\underbrace{\frac{1}{3}\arccos\left(\frac{-7}{2\sqrt{19}}\right)}_{\theta}\Big) $$
and the other roots are given by
$$ -\frac{2}{3}+\frac{2}{3}\sqrt{19}\cos(\theta+2\pi/3)\qquad\text{and}\qquad -\frac{2}{3}+\frac{2}{3}\sqrt{19}\cos(\theta+4\pi/3) $$
i.e. by
$$ -\frac{2}{3}-\frac{1}{3}\sqrt{19}\cos(\theta)-\frac{1}{\sqrt{3}}\sqrt{19}\sin(\theta)\qquad\text{and}\qquad -\frac{2}{3}-\frac{1}{3}\sqrt{19}\cos(\theta)+\frac{1}{\sqrt{3}}\sqrt{19}\sin(\theta) $$
which are clearly related (to each other, and to $\zeta$) via the Pythagorean theorem $\sin^2\theta+\cos^2\theta=1$.
Comment: or, $g(t) = t^3 + t^2 -6t-7$ has three real roots, each of which is the sum of six primitive 19th roots of unity. Then $-g(-1-x) = x^3 + 2 x^2 -5x + 1$
Comment: seee page 26 in https://books.google.com/books?id=wt7lgfeYqMQC&pg=PR1&lpg=PR1&dq=reuschle++tafeln+complexer+primzahlen&source=bl&ots=VGZFPrfUBn&sig=MlQ667PqXaQ9rAvLWkG3_F1rwsk&hl=en&sa=X&ved=0ahUKEwiIwtSvm9TQAhUJ-2MKHXJIA_kQ6AEIODAE#v=onepage&q=reuschle%20%20tafeln%20complexer%20primzahlen&f=false
Comment: Please take a look at this related question: https://math.stackexchange.com/questions/3647084.
Answer: Here is another, slightly more sophisticated, take:
The other root is $\beta= \gamma ^2+2\gamma-4$, where $\gamma = \alpha^2+2\alpha-4$.
Expanding $\beta$ in terms of $\alpha$ and reducing it mod $\alpha^3+2\alpha^2-5\alpha+1$ gives $\beta=-\alpha^2 - 3 \alpha + 2$. Note that $\beta=g(\gamma)=g(g(\alpha))$, where $g(x)=x^2+2x-4$.
(This is because $\mathbb Q(\alpha)$ must be the splitting field of $x^3+2x^2-5x+1$ since it already contains two roots and so must contain the third. The Galois group is cyclic of order $3$ and so the roots are $\alpha$, $g(\alpha)$, $g^2(\alpha)$.)
Comment: I tried to factorize $g\Big(g\big(g(x)\big)\Big)-x$ and got $$\big(g(x)-x\big)\,(x^3+2x^2-5x+1)\,(x^3+5x^2+4x-5)\,.$$  I suppose that $x^3+5x^2+4x-5$ is another cubic whose Galois group is generated by $g$.
Comment: I wonder: can we characterize all quadratic polynomials $g(x)\in\mathbb{Q}[x]$ that do something like this (that is, $g$ generates the Galois group of some irreducible cubic polynomial $f(x)\in\mathbb{Q}[x]$)?
Comment: @Batominovski, nice question! Perhaps ask a separate question?
Comment: Let me think about it for a bit.  Then, I will probably post a question later.  I will let you know when I do that.
Comment: @Batominovski: following my answer below, that happens any time the cubic polynomial has a square discriminant.
Comment: @lhf  Please take a look at https://math.stackexchange.com/questions/3647084.
Answer: Call the roots $\alpha, \alpha', \alpha''$ with $\alpha' = \alpha^2 + 2\alpha - 4$.
$$p(x) = x^3 + 2x^2 - 5x + 1 = (x - \alpha)(x - \alpha')(x - \alpha'') = q(x)(x - \alpha'')$$
with $$q(x) = x^2 + (-\alpha - 3 \alpha + 4) x + (\alpha^3 + 2 \alpha^2 - 4\alpha) = x^2 + (-\alpha - 3 \alpha + 4) x + (\alpha - 1)$$
(replacing $\alpha^2$ with $-2\alpha + 4$)
We can now compute the polynomial long division $p(x)/q(x)$ in $\mathbb Z(\alpha)$ to get $x - \alpha''$:
$$p(x) - x q(x) = (\alpha^2 + 3 \alpha - 2) x^2 + (-\alpha - 4) x + 1$$
$$p(x) - x q(x) - (\alpha^2 + 3 \alpha - 2) q(x) = 0$$
so $$p(x)/q(x) = x - (- \alpha^2 - 3 \alpha + 2).$$
Answer: Given three roots $\alpha, \beta,  \gamma$ of a polynomial, it can generally be written as
$$(x-\alpha)(x-\beta)(x-\gamma)=0$$
Note how each of the roots contribute in making the equality work. On expanding the braces,
$$(x-\alpha)(x-\beta)(x-\gamma)=0$$
$$[(x^2-x(\beta)-x(\alpha)+(\alpha\beta)](x-\gamma)=0$$
$$(x^3-x^2(\gamma)-x^2(\beta)+x(\beta\gamma)-x^2(\alpha)+x(\alpha\gamma)+x(\alpha\beta)-(\alpha\beta\gamma)=0$$
$$x^3-(\alpha+\beta+\gamma)x^2+(\alpha\beta+\beta\gamma+\alpha\gamma)x -(\alpha\beta\gamma)=0$$
Note that if any given equation is scaled down in such a way that the coefficient of $x^3$ is $1$ then the coefficient of $x^2$ gives the negative of sum of roots. More precisely, sum of roots of cubic equation = $-$(coefficient of $x^2$)/(coefficient of $ x^3$)
I hope you can take over from here. As pointed out already sum of roots is $-2$
Bonus: It can also be seen that product of roots of any given cubic equation is equal to the negative of the constant term divided by coefficient of $x^3$ and the sum of product of roots taken two at a time is, well, (coefficient of $x$)/(coefficient of $x^3$)
These are enough conditions on the given roots to get you started.


FacebookSDK: Can we add the FBLoginView to UINavigation?

Question: We can add UIButton to a UINavigation but can we add the FBLoginView instead too?
Answer: Yes login is a view so therefore you can. I have done it using ibaction method and within it pushed my view to the controller. That maybe the way for you as well.
Comment: Oh i just realized this isn't what i want. I want to that FBLoginView to a navigation bar. Is ok I found another way. Thanks


A way to see query after parameters are applied?

Question: In a C# application, I'm building a query by creating a query string with parameters, then to the command adding the parameters and their values.  For example:
string query = "UPDATE USERS u SET u.username = @PARM_USERNAME " +
               "WHERE u.id = @PARM_USERID ";

command.Parameters.AddWithValue("@PARM_USERNAME", user.username);
command.Parameters.AddWithValue("@PARM_USERID", user.id);

command.Connection.Open();
int res = command.ExecuteNonQuery();

It would be beneficial to see the query with parameters applied, is this doable in C#/Visual Studio?  I can check the command.CommandText, but it's only showing me the same content as the query above, with the parameter placeholders there.  If it helps, this is against MySQL.
Answer: If you want to see the query with parameters applied:
string tmp = command.CommandText.ToString();
foreach (SqlParameter p in cmd.Parameters) {
    tmp = tmp.Replace('@' + p.ParameterName.ToString(),"'" + p.Value.ToString() + "'");
}

tmp will then hold the query with the parameters applied.
Each parameter will be surrounded by single quotes.
Of course, it is NOT safe to execute.  I use it for debugging purposes.
Comment: If you do .AddWithValue("@P1", ...) then ParameterName already begins with an '@', so the above code tries to replace "@@P1" with the value, so it doesn't work. What am I missing?
Comment: I know this is old but your code has issues. First of all, you use `command` on the first line, and `cmd` on the others. They should be the same. Second, it is not necessary to call `ToString()` on `CommandText`. It is already a string. Next, the parameter should only be enclosed in quote if it's a quotable value. Integers, for example, are not. And finally, as already pointed out, you shouldn't prepend the `@` to the parameter name as it will normally already have it.
Comment: For MS SQL the 'SqlParameter' class inheritance hierarchy is System.Data.SqlClient.SqlParameter. For MySQL it would be MySql.Data.MySqlClient.MySqlParameter
Answer: There's no guarantee that there is such a thing as "the query with the parameters applied". I would hope that a driver would simply send down the command as SQL and the parameters in an appropriate form to represent each value. Why go to the bother of escaping values etc, only for the query processor to unescape them and parse them at the other side? It's more efficient and less risky to just pass the data in a binary format of some description.
You should regard it as some code (the SQL) which uses some data (the parameters) and keep the two concepts very separate in your mind. If you need to log what's going on, I would log it as the parameterized SQL and the parameter values separately.
Comment: Ahh, okay, I wasn't aware of that.  I thought the parameters and values were combined in the MySQL library before sending off to server, lesson learned.
Comment: @Mike: It's *possible* that they are - but certainly not *necessary*, and personally I hope they're not :)
Answer: The parameters remain separate all the way to the server, so the query string you see is what actually goes to the server, independently from the parameters. So I think you need to deal more directly with understanding how parameterized queries work rather than trying to see what the query would look like with the parameters in place.  You can use SQL trace to see the query come in.  The parameters will still be separate, but it will show you the values.
My experience is with SQL Server, so I'm not sure how applicable this is to MySQL.
Comment: Thanks for your response.  I didn't know the values stayed separate all the way to the server.
Answer: the @christopher answer was great but just string parameters will need ' (single quotation). the best is to use below method:
  private string getGeneratedSql(SqlCommand cmd)
    {
        string result = cmd.CommandText.ToString();
        foreach (SqlParameter p in cmd.Parameters)
        {
            string isQuted = (p.Value is string) ? "'" : "";
            result = result.Replace('@' + p.ParameterName.ToString(), isQuted + p.Value.ToString() + isQuted);
        }
        return result;
    }

Answer: Not sure why you need this, but if it's for debugging purposes you can always turn on the global log on your local mysql database machine to see the query sent to the database (you don't want to turn it on on a production machine though - it might slow it down significantly).
Comment: It is for debugging, essentially I have a query that's not resulting in what I expect.  I was hoping to just take the "final" query from the app and check it against the DB, guess I'll have to do it this way.  Thanks for your response.
Answer: If you would like to use a tool you could try using Toad for MySql which has a Profiler and you can see what is being sent to the server.
Answer: I use this for debuging in HTML. Must of the time is enough for testing with simple copy paste;

        public static string GetQueryHtml(string query, List<SqlParameter> parameters = null)
        {
            string _return = ""; string _parmStringValue; string _varlenght = "50";
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter.SqlDbType == SqlDbType.DateTime)
                {
                    _parmStringValue = "'" + ((DateTime)parameter.Value).ToString("yyyy-MM-dd hh:mm:ss") + "'";
                    _return += Environment.NewLine +  "DECLARE " + parameter.ParameterName + " AS " + parameter.SqlDbType.ToString() + " SET " + parameter.ParameterName + " = " + _parmStringValue;
                }
                else if (parameter.SqlDbType == SqlDbType.NVarChar || parameter.SqlDbType == SqlDbType.Char)
                {
                    _varlenght = parameter.Value.ToString().Length.ToString();
                    _parmStringValue = "'" + parameter.Value.ToString() + "'";
                    _return += Environment.NewLine + "DECLARE " + parameter.ParameterName + " AS " + parameter.SqlDbType.ToString() + "(" + _varlenght + ") SET " + parameter.ParameterName + " = " + _parmStringValue;
                }
                else
                {
                    _return += Environment.NewLine + "DECLARE " + parameter.ParameterName + " AS " + parameter.SqlDbType.ToString() + " SET " + parameter.ParameterName + " = " + parameter.Value.ToString();
                }

            }

            return "

" + _return + Environment.NewLine + Environment.NewLine + query + "

";

        }

Answer: For anyone wanting to use Christopher's answer with Mysql, this worked for me...
string tmp = cmd.CommandText.ToString();
foreach (MySqlParameter param in cmd.Parameters)
{
    tmp = tmp.Replace(param.ParameterName.ToString(), "'" + param.Value.ToString() + "'");
}


Como passar variáveis vindas de post, guardá-las até à ultimo step e mostrar todos os valores

Question: Tenho um formulário que está dividido em 10 partes, ou seja, vou guardando via post as variáveis de página para página. No entanto, caso faça refresh na página todas as variáveis anteriores são perdidas.
Como posso resolver o problema?
Esquema:
Fase 1 - fase1_view -> Post -> fase1controller -> loadview_fase2
Fase 2 - fase2_view -> variaveis_fase1 (input hidden)-> post-> fase2controller-> loadview_fase3 (envia todas as variaveis guardadas para a fase3)
Fase 3 - fase3_view -> variaveis_fase_1_e_2 (input hidden) -> post -> fase3controller -> loadview_fase_4 (envia todas as variaveis guardadas até ao momento para a view da fase 4)
.
.
.
Por ai em diante... Mas caso faça um refresh à página, todas as variáveis são perdidas.
Obrigado.
Answer: Podes gravar a informação usando php em base de dados ou então podes guardar em cookies
Deixa me mostrar-te um exemplo:
http://www.w3schools.com/php/php_forms.asp
O que eu faria seria, a cada passo ia guardando a informação em cookies então no fim do formulario quando tiveres de guardar a informação em base de dados ou enviar por e-mail eu iria buscar essa informação às cookies
http://www.w3schools.com/php/php_cookies.asp
<code>setcookie($nome_para_a_variavel_cookie, $variavel_com_conteudo_aguardar_nesta_cookie, time() + (86400 * 30), "/");
</code>
Answer: Use sessões, armazene cada etapa em uma array com os dados e coloque na sessão separado cada etapa por uma chave principal, exemplo:
<code>$array = array(
    'etapa 1' => array(),
    'etapa 2' => array(),
    'etapa 3' => array()
);

$this->session->set_userdata($array);
</code>


Mixed effect model specification for repeated measure placebo controlled trial

Question: I am analyzing gene expression data for a repeated measure placebo controlled clinical trial. Example dataset:
df <- data.frame(
  subject = c(paste0('Healthy', 1:8), paste0('PID', rep(1:12, 2))),
  disease = c(rep(FALSE, 8), rep(TRUE, 24)),
  treatment = c(rep('none', 8), rep(c('Placebo', 'Drug'), 12)),
  visit = c(rep('BL', 8), rep(c('BL', 'Day3'), each=12)),
  score = c(rep(NA,8), rep(c(0,0,30,30,50,50,70,70,90,90,100,100), 2)),
  gene = rnorm(32, 5)
)

Variables:
subject: IDs of either healthy controls or patients (PID prefix).
disease: is TRUE if subjects have the disease and FALSE if they are healthy controls.
treatment: 'none' for healthy and either 'Placebo' or 'Drug' for patients that will or did receive the corresponding treatment.
visit: is 'BL' for samples collected prior to treatment and 'Day3' for patient samples collected three days after treatment.
score: in an outcome that represents improvement in disease outcome and is measured 15 days after baseline. It could reasonably be modeled as an ordered factor but I decided to treat it as continuous for simplicity. This might not be appropriate as the maximum score is 100? Interpreting the polynomial terms confused me.
gene: is the expression of a sample gene that I want to ask questions about.
Model and Rationale:
mod <- lmerTest::lmer(gene ~ disease + treatment:visit + score:treatment:visit + (1|subject), data=df)

disease: I expect disease to independently affect the expression of gene (main effect).
treatment:visit: I expect to see an effect of being in the 'Drug' treated group only after treatment (visit Day3). I have omitted the main effect for treatment as it merely identifies healthy and randomization to Placebo or Drug groups. I have also omitted the main effect for visit as I don't expect gene expression to change on Day3 independent of treatment. Do these model specifications reflect my assumptions correctly?
score:treatment:visit: I am specifically interested in whether the expression of a given gene at both baseline and 3 days after treatment depends on disease improvement as measured by score on day 15. So, for example, gene expression could differ between subjects with disease before and after treatment in a way that depends on eventual score. Should the interaction be score:treatment:visit:disease to capture this?
Questions I want to address:
Does the expression of gene at baseline differ based on score at day 15?
Does the change in expression of gene between baseline and Day3 in subjects receiving the drug differ based on score at day 15?
Does the expression of gene at baseline differ between individuals with the disease and those without the disease?
How do I go about asking these questions using the model above (or an alternative specification if the above is incorrect)?
Thank you!
Comment: Could you please say some more about what the "score" variable represents in your model? The way you describe it, its (post-pre) difference seems more like an outcome than a predictor. And is this just one gene whose expression you're evaluating, or is this a multi-gene study?
Comment: Are the gene measurements only done post, or do you have post-pre differences for those too?
Comment: I added some clarifications to the original question. Thank you!
Answer: I think that you're trying to do too much with a single model. Things will be easier to understand and to explain to others if you break down the problem. Let's deal with the questions in reverse order.

Does the expression of gene at baseline differ between individuals with the disease and those without the disease?

To answer this question, it's simplest just to do a direct comparison of gene values between those 2 groups at baseline.
You might get slightly refined estimates with a mixed model that combines information from the 2 measurements taken on each of the individuals with disease. That could improve precision by a factor of about $\sqrt 2$ for the Disease group, but at some cost in extra assumptions and potential difficulty in explanation.
Although there are neither Day3 gene measurements nor a Drug category available for the Normal individuals, you could try something like the following. Apply the principle in this answer to deal with the data values that are impossible in your experimental design. Use 0/1 coding for disease (1 = Disease, 0 = Normal), treatment (1 = Drug, 0 for Normal and Placebo), and visit (1 = Day 3 visit, 0 for Normal and for the baseline visits). (Or if you prefer, False/True with False as the reference category.) That could give this mixed model (omitting the score variable for reasons explained below):
gene ~ disease + treatment*visit + (1|subject).

With the default treatment contrasts in R, the intercept in that model will be the model-estimated gene value for Normals (necessarily at a baseline visit and in the Placebo group with this coding). With that coding there are no further estimates made about treatment and visit effects for Normals, as they have 0 values for those. The random effect would model a distribution of intercept-value differences from that estimate (for Disease cases, taking into account the estimated fixed effect of Disease and any Drug-Placebo group difference at baseline).
Then: the disease coefficient would be the (Disease - Normal) group gene difference at the baseline visit (which could be considered an answer to this part of your question, although strictly this is the modeled difference of the Placebo group from Normal); the treatment coefficient would be the (Drug - Placebo) group gene difference at the baseline visit (ideally 0 if there are no baseline differences arising from treatment assignment); the visit coefficient would be the (Day3 - baseline) gene difference for the Placebo group (again, ideally 0 unless there is a Placebo effect on gene); the treatment:visit interaction would be the (Day3 - baseline) difference of gene values between the Drug group and the Placebo group (another result of interest).
I could see some objections, however, to modeling the random intercepts in the same way for the Normal and Disease individuals, even though the main effect of disease is accounted for in this modeling. For more complicated designs (like allowing for random effects of disease) you would have to make some assumptions about correlations between random intercepts and slopes, assumptions implicit but not always thought through in designing mixed-model formulas.

Does the change in expression of gene between baseline and Day3 in subjects receiving the drug differ based on score at day 15?

I (and I suspect many reviewers) would have a problem with causality in this type of model. Day 15 happens after the gene-expression measurements and the treatment. Using a value measured on Day 15 as a predictor, as in your proposed model, does not seem logical.
It would make more sense to treat score as the outcome and use the gene_difference as the predictor. (If you think that baseline gene values also matter, as implied by another of your questions, then you could use both baseline gene and gene_difference as predictors.) Restricting this analysis to those who received Drug, as you seem to propose, makes that pretty straightforward. You probably can get away with treating score as a continuous variable if its values cover a reasonable range.
Then you could combine information on all of your genes into a single model for score as the outcome variable. With a large number of genes you will have to model with methods like LASSO or ridge regression, but that's standard practice in gene-expression studies.

Does the expression of gene at baseline differ based on score at day 15?

In addition to the causality issue noted above, it's not clear from this how you intend to deal with the treatment issue here. With score as the outcome, I suppose you could restrict this analysis to the Placebo group and proceed as suggested above (using baseline gene values instead of the gene_difference values proposed for the Drug group). If there are no major differences in gene values for the Placebo group between baseline and Day3 then you could consider using the average of the baseline and Day 3 values to get potentially better estimates.
Finally, as a caution for future work, it's generally important to include all lower-level coefficients along with the interaction terms you are interested in. Your proposed model in this version of the question omits all single-predictor coefficients except disease and the 2-way interactions of treatment and visit with score. The full interaction model you proposed in an earlier version of the question would have been the correct form for a model with those 3 interacting predictors. See this page for extensive discussion.
Comment: @alexvpickering for comparing `gene` for baseline disease vs healthy, you won't have repeated measures on the healthy cases so it's not clear how much is gained by adding mixed modeling of the disease cases. I suppose a model that included `treatment` and `visit`, with their interaction, could provide somewhat more precise estimates of true "baseline" `gene` values for the disease cases, but I suspect that the advantage will be minimal and you will have to explain a more difficult model to your audience. Try both ways and see. Modeling is a process, not a one-off effort.
Comment: Thank you @EdM - a couple of questions. 1) For comparing baseline disease vs healthy doesn't it make sense to also model day3 disease so that I can include the subject random effect to model the within-individual correlation? This is partly an exercise for me to understand linear models so thank you for the comments/suggestions!
Comment: @alexvpickering I've added a potential mixed-effects model to the answer, which at least should help you think about some of the issues with mixed models and interaction terms. Note that even this relatively simple model estimates an intercept, a distribution of intercept values among subjects, three single-predictor coefficients, and an interaction coefficient. As I count it, you have only (2*2*12 + 8) = 56 `gene` observations in your example, so if that's the case in your study that might already be close to over-fitting.


Dificuldade em actualizar variável global. c

Question: Estou a desenvolver o seguinte código e estou a utilizar variáveis globais que podem ser alteradas em diferentes partes do código, mas quando altero por exemplo a variável state na função menu() o seu valor não é alterado nas outras funções que a utilizam, ou seja as variáveis são globais mas não são actualizadas.
Será por estar a fazer varios processos para correr todas as funções em simultâneo ou estou a fazer alguma coisa mal?
<code>/* menu para acesso as funcionalidades */
#include <wiringPi.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <stdbool.h>
#include <signal.h>

#define sensoralarme    3
#define saidaalarme     9
#define saidaalarme2   26
#define sensoralarme2 11
#define botaoreset 31
#define saidaclimatizacao 12
#define botaoaumenta 0
#define botaodiminui 2
#define saidajanela1 27
#define saidajanela2 23
#define abrirjanela 5
#define fecharjanela 4
#define ldr 29

void menu();
void iluminacacao();
void intrusao();
void janelas();
void toggle();
void disparo();
void reset();
void climatizacao();
void toggleclimatizacao();

//int disparo = (digitalRead(sensoralarme));
int estadoalarme;
int estadojanela;
int estadojanela2 = 3 ;
//int *ptr_int = &estadojanela2;
int rr;
 int bright=0 ;
 int state=0;
 int statedisparo=0;
int statedisparo2;
int toggleCount = 0;   // used to count number of falling edges received.
int estadoclimatizacao;
int estadoclimatizacao2;

int main()
{

    int i,r, n=5;
    wiringPiSetup ();
    pinMode (1, PWM_OUTPUT); /* pwm iluminação*/
    pinMode (0, INPUT);/*aumenta luminusidade*/
    pinMode (2, INPUT); /* diminui luminusidade*/
    pinMode (9, OUTPUT); /* saída disparo alarme*/
    pinMode (3, INPUT); /*sensor alarme*/
    pinMode (12, OUTPUT); /*saída climatização */
    pinMode (27, OUTPUT); /*saída janela abrir */
    pinMode (23, OUTPUT); /*saída janela fechar */
    pinMode (29, INPUT);/*ldr*/
    pinMode (5, INPUT);
    pinMode (4, INPUT);
    pinMode (6, INPUT);
    pinMode (25, OUTPUT);/*sensir janela aberta */
    pinMode (saidaalarme, OUTPUT);
    pinMode (saidaalarme2, OUTPUT);
    pinMode (sensoralarme, INPUT);
    pinMode (sensoralarme2, INPUT);
    pinMode (botaoreset, INPUT);
    digitalWrite(saidaalarme2, LOW);
    digitalWrite(saidaalarme, LOW);
    digitalWrite(saidaalarme,0);
    digitalWrite(saidaclimatizacao,0);
    digitalWrite(saidajanela1,0);
    digitalWrite(saidajanela2,0);
    //pwmWrite (1, 0);
    printf("Bem Vindo.\n");
    printf("Pressione OK para continuar\n");
    getchar();
    r=fork();
    if(r==0)
    {
        printf(" \n.....A iniciar sistemas iluminacao\n \n ");
        iluminacao();
        exit(0);
    }
    r=fork();
    if(r==0)
    {
        printf(" \n.....A iniciar sistemas intrusao \n \n ");
        intrusao();
        exit(0);
    }
    r=fork();
    if(r==0)
    {
        printf(" \n.....A iniciar sistemas  climatizacao\n \n ");
        climatizacao();
        exit(0);
    }
    r=fork();
    if(r==0)
    {
        printf(" \n.....A iniciar sistemas janelas \n \n ");
        janelas();
        exit(0);
    }
    delay (500);
    system( "clear" );
    menu();

    /*for(i=0; i<n; i++)
    {

        if(fork()) break;
    }

    if(i==n)
    {
        menu();

    }
    else
    {
        printf(" \n.....A iniciar sistemas \n \n ");
    }
    switch(i)
    {
        case 1:
        {
            iluminacao();
            break;
        }
        case 2:
        {
            intrusao();
            break;
        }
        case 3:
        {
            climatizacao();
            break;
        }
        case 4:
        {
            janelas();
            break;
        }
    }*/

 /*int r;
 r=fork();
 if (r==0)
 {iluminacao();intrusao();climatizacao();janelas();}
 else
 {menu();}
    return 0;*/

}

void menu()
{
    int escolha1;
    int r;
    int estadoclimatizacao;
    int lum;
    int estadointrusao;

    //printf(" estado janela2:%d\n",  *ptr_int);
    printf("SISTEMAS \n");
    printf("\n");
    printf("Escolha umas das seguintes opções:\n");
    printf("1. iluminação.\n");
    printf("2. Intrusão.\n");
    printf("3. Climatização.\n");
    printf("4. Janelas.\n");
    printf("0. Sair.\n");
    scanf("%d", &escolha1);
    switch ( escolha1 )
    {
        case 1:
        {
            printf("intruduza o nivel de luminusidade desejado de 0 a 10 \n");
            scanf("%d", &lum);
            bright=lum*102.4;
            printf("%d: lum\n",bright);
            pwmWrite (1, bright);
            menu();
            break;
        }
        case 2:
        {
            printf(" Para ligar prima 1\n Para desligar prima 0\n");
            scanf("%d", &estadointrusao);
            if (estadointrusao==1 && state ==0)
            {
                digitalWrite(saidaalarme, HIGH);
                state=1;
                menu();
                break;
            }
            else if (estadointrusao==1 && state ==1)
            {
                printf(" Sistema já se encontra ligado!\n");
                menu();
            }
            if (estadointrusao==0 && state == 1 && statedisparo == 0)
            {
                digitalWrite(saidaalarme, LOW);
                state=0;
                menu();
                break;
            }
            else if (estadointrusao==0 && state ==0)
            {
                printf(" Sistema já se encontra desligado!\n");
                menu();
            }
            else if (estadointrusao==0 && state ==1 && statedisparo == 0)
            {
                printf(" Sistema terá de ser desligado localmente!\n DISPARO\n");
                menu();
            }
        }
        case 3:
        {
            printf(" Para ligar prima 1\n Para desligar prima 0\n");
            scanf("%d", &estadoclimatizacao);
            if ( estadoclimatizacao == 1 )
            {
                digitalWrite(saidaclimatizacao,1);
                menu();
            }
            if ( estadoclimatizacao == 0 )
            {
                digitalWrite(saidaclimatizacao,0);
                menu();
            }
        }
        case 4:
        {
            printf(" Para abrir prima 1\n Para fechar prima 0\n Para verificar o estado prima 2\n");
            scanf("%d", &estadojanela);
            if (estadojanela ==2 && estadojanela2 ==1)
                {
                    printf("janela ABERTa \n");
                    menu();
                }
            if (estadojanela==2 && estadojanela2 == 0)
                {
                    printf("janela fechada \n");
                    menu();
                }
            if (estadojanela !=2 && rr==0)
            {

                    menu();
                    //sleep(600);

            }
            else
            {
                printf("passar para processo ja aberto \n");
                menu();
            }
        }

        case 0:
        {
            kill(0, SIGTERM);
            /*comando para matar todos os processos criados*/
            digitalWrite(saidaalarme2, LOW);
        digitalWrite(saidaalarme, LOW);
        digitalWrite(saidaalarme,0);
        digitalWrite(saidaclimatizacao,0);
        digitalWrite(saidajanela1,0);
        digitalWrite(saidajanela2,0);
        pwmWrite (1, 0);
            return (0);
            break;
        }
    }

}

void iluminacao()
{

  //int buttonmais = (digitalRead(0) );
  int buttonmenos = (digitalRead(2) );

  printf ("dimmer\n") ;

  if (wiringPiSetup () == -1)
    exit (1) ;

  pwmWrite (1, bright);

  while (1)
  {

      while (digitalRead(0) != LOW && digitalRead(2) == LOW && digitalRead(29) !=0)
      {

          if (bright  < 1024 && bright >= 0)
        {
        bright = bright+1;
        pwmWrite (1, bright) ;
        delay (4) ;

        }
        }
    while ( digitalRead(2) != LOW && digitalRead(0) == LOW && digitalRead(29) !=0)
    {
        if (bright  <= 1024 && bright > 0)
        {
            bright = bright-1;
        pwmWrite (1, bright) ;
        delay (4) ;
        }
    }

    if (digitalRead(0) != LOW && digitalRead(2) != LOW)
      {
          bright = 0;
          pwmWrite (1, bright);
      }
}

}

void janelas()
{
    while (1)
    {
        if ( estadojanela == 1 && digitalRead(25)==0 )/*abre janela via linha de comandos*/
                {
                    digitalWrite(saidajanela1,1);
                    digitalWrite(saidajanela2,0);
                    delay(500);
                    estadojanela2 = 1;
                    estadojanela=3;
                    printf("ABERTO \n");
                    digitalWrite(saidajanela1,0);
                    digitalWrite(25,1);

                }
                if ( estadojanela == 0 && digitalRead(25)==1)/* fecha janela via linha de comandos*/
                {
                    digitalWrite(saidajanela1,0);
                    digitalWrite(saidajanela2,1);
                    delay(500);
                    estadojanela2=0;
                    estadojanela=3;
                    printf("Fechado \n");
                    digitalWrite(saidajanela2,0);
                    digitalWrite(25,0);

                }
                if ( estadojanela == 1  && (digitalRead(saidajanela1)==1)  )/*para abertura de janela*/
                {
                    digitalWrite(saidajanela1,0);
                    digitalWrite(saidajanela2,0);

                    printf("ABERTura parada \n");

                }
                if ( estadojanela == 0  && (digitalRead(saidajanela2)==1)  )/*para fecho da janela*/
                {
                    digitalWrite(saidajanela1,0);
                    digitalWrite(saidajanela2,0);

                    printf("fecho parada \n");

                }
                if ( digitalRead(5)!=0 && digitalRead(25)==0 )/*abre janela via linha de comandos*/
                {
                    digitalWrite(saidajanela1,1);
                    digitalWrite(saidajanela2,0);
                    delay(500);
                    estadojanela2 = 1;
                    estadojanela=3;
                    printf("ABERTO \n");
                    digitalWrite(saidajanela1,0);
                    digitalWrite(25,1);

                }
                if ( digitalRead(4)!=0 && digitalRead(25)==1)
                {
                    digitalWrite(saidajanela1,0);
                    digitalWrite(saidajanela2,1);
                    delay(500);
                    estadojanela2=0;
                    estadojanela=3;
                    printf("Fechado \n");
                    digitalWrite(saidajanela2,0);
                    digitalWrite(25,0);

                }
    }

}

void intrusao()
{
    if (wiringPiISR(sensoralarme,INT_EDGE_FALLING,&toggle) != 0)
    {
        printf("Registering ISR failed\n");
        return 2;
    }
    if (wiringPiISR(sensoralarme2,INT_EDGE_FALLING,&disparo) != 0)
    {
        printf("Registering ISR failed\n");
        return 2;
    }
    if (wiringPiISR(botaoreset,INT_EDGE_FALLING,&reset) != 0)
    {
        printf("Registering ISR failed\n");
        return 2;
    }
    if ( saidaalarme == 1 && sensoralarme2 == 1)
    {
        digitalWrite(saidaalarme2, HIGH);
        delay(10);
    }

    // wait for ever so the program doesn't terminate.
    while(1)
    {

        // Yield the thread so CPU doesn't run 100%
        delay(5000);
    }
}

void toggle()
{

    // NOTE: LED is connected to +3.3V and to the PIN.
    // So configuration is active low.
    if(state==1 && statedisparo ==0)
    {
        // Set -ve lead of LED to ground.
        digitalWrite(saidaalarme,LOW);
        state = 0;
        printf("%d: ALARME OFF\n", toggleCount++);
    }

    else
    {
        // Set -ve lead of LED to +3.3V.
        digitalWrite(saidaalarme, HIGH);
        state = 1;
        printf("%d: ALARME ON\n", toggleCount++);
    }

}
void disparo()
{
    //statedisparo = 0;
    if(state==1 && statedisparo==0)
    {
        // Set -ve lead of LED to ground.
        digitalWrite(saidaalarme2,LOW);
        statedisparo = 1;
        statedisparo2 = 1;
       // printf("%d: disparo off\n", toggleCount++);

    /*  do
    {
            digitalWrite (LedPin2, HIGH) ; delay (300) ;
        digitalWrite (LedPin2, LOW) ; delay(300) ;
    }
    while (state==1);*/

        while(statedisparo2==1)
        {

            digitalWrite (saidaalarme2, HIGH) ; delay (300) ;
            digitalWrite (saidaalarme2, LOW) ; delay(300) ;

        }

    }
    else if(state==0 && /*ButtonPin2 ==1*/ statedisparo == 0)
    {
        // Set -ve lead of LED to +3.3V.
        digitalWrite(saidaalarme2, HIGH);
        //statedisparo = 1;
        printf("%d: ALARME OFF\n", toggleCount++);
        printf("%d: disparo ON\n", toggleCount++);
        digitalWrite (saidaalarme2, HIGH) ; delay (500) ;
        pwmWrite (1, 256);
        digitalWrite (saidaalarme2, LOW) ;

    }

}
void reset()
{
    if(state == 1)
    {
        // Set -ve lead of LED to +3.3V.
        digitalWrite(saidaalarme2, LOW);
        digitalWrite(saidaalarme, LOW);
        //statedisparo = 1;
        printf("%d: RESET\n", toggleCount++);
        state=0;
        statedisparo=0;
        statedisparo2=0;
        return;

    }
}

void climatizacao()
{
    //int flag=0;
    printf("climatização\n");

    if (wiringPiISR(digitalRead(6),INT_EDGE_FALLING,&toggleclimatizacao) != 0)
    {
        printf("Registering ISR failed\n");
        return 2;
    }
    while (1)
    {
        //if (digitalRead(6)!=0 && estadoclimatizacao2==0 && flag==0)
        //{
            //digitalWrite(saidaclimatizacao,1);
            //flag=1;
        //  estadoclimatizacao2=1;
        //}
        //if (digitalRead(6)!=0 && estadoclimatizacao2==1 && flag ==1)
        //{
            //digitalWrite(saidaclimatizacao,0);
            //flag=0;
        //  estadoclimatizacao2=0;
        //}
         delay(5000);

    }
}

void toggleclimatizacao()
{

    if(estadoclimatizacao==1 && statedisparo ==0)
    {

        digitalWrite(saidaclimatizacao,LOW);
        estadoclimatizacao = 0;
        printf(" climatizacao OFF\n");
    }

    else
    {
        // Set -ve lead of LED to +3.3V.
        digitalWrite(saidaclimatizacao, HIGH);
        estadoclimatizacao = 1;
        printf("climatizacao ON\n");
    }

}
</code>
Comment: Tem como postar o trecho de código que tem o problema? Fica difícil tentar ajudar quando tenho 17 telas de código para ler
Comment: Eu nem vou tentar ajudar por uma razão: este código tem tantos problemas que resolver isto não vai mudar nada. Me desculpe a sinceridade, mas só começando de novo, desta vez do jeito certo.
Comment: Acredito que o código tenha muitos problemas, mas para quem tem muito pouco conhecimento na área não é facil reconheccer certos problemas, e até seria melhor começar de novo da maneira correcta, mas seria necessário saber qual é a maneira correcta. Mas obrigado pela ajuda e pela opinião.
Answer: A função fork duplica todos os dados em memória do processo pai, incluindo variáveis globais. Então se você altera uma variável num dos processos, a mudança não será refletida nos outros.
Você tem que usar algum mecanismo de compartilhamento de memória entre processos pra atingir esse objetivo, ou criar threads em vez de processos, que teriam acesso às variáveis globais do processo que as criou.
Link em inglês, se ajudar:
https://stackoverflow.com/questions/13274786/how-to-share-memory-between-process-fork
Comment: Obrigado pelas dicas, vou analisar o que me sugeriu, usei a função fork() porque não tenho grade conhecimento de programação e como precisava de todas as funções a funcionar em ciclo infinito foi a maneira que consegui arranjar para o fazer, nunca me virei para threads porque nunca trabalhei com threads e não sei como usar.
Comment: A sua sugestão resolveu o meu problema! Obrigado


Show that $f$ is uniformly continuous given that $f'$ is bounded.

Question: Let $D\subset \mathbb{R}$ be an interval and $f:D\rightarrow \mathbb{R}$ a continuously differentiable function such that its derivative $f':D\rightarrow \mathbb{R}$ is bounded. Show that $f$ is uniformly continuous.
I will admit before I begin; I am stabbing in the dark.
If we restrict the domain of $f$ to some interval $[-X,X] \subset D$, then $f:[-X,X]\rightarrow \mathbb{R}$ is uniformly continuous.
Now since we know that $f'$ is bounded we can say that for some arbitrary $y \in D$, $|f'(x)| = \lim_{x \rightarrow y}\frac{|f(x) - f(y)|}{|x-y|} \leq K   ( \forall x \in D:x \neq y) $ for some $K >0 $
This is not going to sounds mathematical, but I need to somehow get rid of the limit so I can proceed with something like $\frac{|f(x) - f(y)|}{|x-y|} \leq K$
Comment: Do you know the relation between integral and derivative? If not, does 'mean value theorem' ring a bell?
Comment: antwon: If it bit you that would make it a "mean" value theorem indeed!
Comment: Did you try to estimate $|f(x)-f(y)|$ in terms of derivative?
Comment: It could have bit my nose if it had teeth. :( Thanks @Thomas
Answer: Let $D$ be the interval on which $f$ is defined, and $f'$ the derivative, assumed bounded on $D$ (left/right derivatives at endpoints). So there is $K>0$ for which $|f'(t)|<K$ for all $t \in D.$ Now suppose $x<y$ are two points in $D.$ By the mean value theorem, $(f(y)-f(x))/(y-x)=f'(c)$ for some $c$ with $x<c<y.$ This gives what you want since here $|f'(c)|<K.$
Note here the $c$ at which $f'$ gets evaluated is not an endpoint of $D$ since it is strictly between two elements of $D$ [Maybe that doesn't matter, but its the boundedness of the derivative at the collection of interior points of $D$ which is needed in the above argument.]
Answer: Another more abstract argument is the following one: a differentiable function with bounded derivative is Lipschitz continuous with Lipschitz constant given by the derivative's bound. And a Lipschitz continuous function is easily seen to be uniformly continuous.
Answer: Let $f:[-X,X]\rightarrow \mathbb{R}$ has the conditions that you want. Let $\epsilon>0$, then we want to find $\delta>0$ such that:
$$\forall x,y\in [-X,X](|x-y|<\delta \rightarrow |f(x)-f(y)|<\epsilon)$$
By Mean value theorem for every $x,y\in [-X,X],x<y$, there exists $c\in (-X,X)$ such that
$$\frac{f(y)-f(x)}{y-x}=f'(c)$$
Because for every $x\in (-X,X)$, we have $|f'(x)|<K$, therefore for every $x,y\in [-X,X],x<y$
$$\frac{|f(y)-f(x)|}{|y-x|}<K$$
so we choose $\delta = \frac{\epsilon}{K}$


VideoJS with multiple videos (slideshow) in Firefox

Question: I've been working on a site for a client, it's a WordPress site with Flexslider built-in to the theme. I am trying to get a slideshow of videos working, using VideoJS.
Inside the slideshow.php file, I have got it looping through the given slideshow posts and creating the necessary markup. It generates divs which contain the HTML5 video tag and gives it a unique ID. As the videos which are trying to be played are .mp4 format, and Firefox does not accept this, VideoJS should fallback to the Flash player - which it does, partially.
It seems that every other video on the slideshow works, and the others are left with an empty black box. Note: this is only happening in Firefox; Chrome, IE and Safari are fine, as far as I'm aware.
A live example can be seen here: http://churchcoalition.org/
If anyone has any suggestions for getting all the videos to work in Firefox, it'd be much appreciated.
Edit: It seems that now, none of the videos are working in FF, despite there being no changes to the code.
Regards.
Answer: You need to use plugins.Hope that will help you.
http://wordpress.org/extend/plugins/wpreso-video-featurebox/
http://wordpress.org/extend/plugins/captain-slider/
Comment: Like I said, it's using the Flexslider plugin which is built-in to the theme. The slideshow works, it's just that the videos aren't all working in Firefox. It works in every other browser I've tried.
Answer: Not the neatest way of fixing it, but a fix nevertheless.
I checked the user agent, and if the Firefox string was matched, it would output an  which used another Flash player, and if not, it would use the VideoJS code. I'm still not certain why the Flash fallback on VideoJS is not working, but this fix is working for me.


Expected number of games in the Baseball World Series

Question: Consider the following problem, from Understanding Probability by Henk Tijms.

In the World Series Baseball, the final two teams play a series
  consisting of a possible seven games until such time that one of the
  two teams has won four games. In one such final, two unevenly matched
  teams are pitted against each other and the probability that the
  weaker team will win any given game is equal to $p=0.45$. Assuming that
  the results of the various games are independent from each other,
  calculate the probability of the weaker team winning the final. What
  are the expected value and the standard deviation of the number of
  games the final will take?

The probability of the weaker team winning is:
$$
\sum_{k=0}^3 \binom{7}{k} (1-p)^kp^{7-k}\simeq 0.3917.
$$
For the expected value of the number of games, I consider the following table, where I list the number of possible wins for each of the two teams:
$$
\begin{array}{cc}
\text{strong team} & 4 & 4 & 4 & 4 & 0 & 1 & 2 & 3 \\
\text{weak team} & 0 & 1 & 2 & 3 & 4 & 4 & 4 & 4 \\
\end{array}
$$
which leads me to the expression:
$$
\sum_{k=0}^3 (4+k)\binom{4+k}{k}p^k(1-p)^4 + \sum_{k=0}^3 (4+k)\binom{4+k}{k}p^4(1-p)^k \simeq 8.622
$$
the result, however, is wrong. The only thing that I can think of is that I am counting in a wrong way the number of games with a given number of wins for the two teams.
I have found the solution of this problem here, but why is my approach wrong?
Comment: @vadim123, the OP probably meant to sum from $k=0$ to $3$, not $7$.
Comment: @barry-cipra, indeed, I will fix it immediately.
Answer: When you count all possibilities that the series finishes, e.g., 4-2 in favor of the stronger team, you count every time the stronger team wins 4 games and the weaker team wins 2, in any order, as a 6-game series. However, if the stronger team wins games 1,3,4,5, and the weaker team wins games 2,6, the series lasted only 5 games (and game 6 was never played). So not every arrangement of 4 strongenr-team-wins and 2 weaker-team-wins gives a legitimate 6-game series.
Answer: Your expression is almost right with the choose formula on both terms to be ${(4+k-1)\choose k}$ the reason being, the last one of p or (1-p) is fixed and that the the k games of the loser on both terms should find their way within (total number of games - 1) slots with the last being fixed.  Other than that your logic is right and is no different than the solution that you referred to.
Answer: @BallBoy's answer explains why your calculation is incorrect. To fix this, note that you should only count combinations where the $k$ games won by the losing team do not include the last game (the losing team can't win the last game). So that gives
$$\sum_{k=0}^3(4+k)\binom{3+k}kp^k(1-p)^4+\sum_{k=0}^3(4+k)\binom{3+k}kp^4(1-p)^k\approx 5.78$$


Why does this vi-ii-V-I progression evoke a sense of ii-V-I-vi?

Question: Could someone assist me in analyzing the chord progression found in 'Save My Soul, Not My Ship' by Enjoy?
A brief caveat with regard to the title:  please note that my analysis of the progressions may not be accurate. Kindly read on for additional information.
I've been a fan of the ii-V-I-vi progression ever since I heard it in Human Sadness.  Since then, I keep hearing it pop up in all sorts of songs.
Yesterday, my brother introduced me to this song by Enjoy and asked for my thoughts on the chord progression. After listening, I suggested that it sounded like a ii-V-I-vi progression (confirmation bias perhaps?). Interestingly, the progression even features a passing note in the bass (an A natural in this case), reminiscent of the passing note in the demo version of 'Human Sadness', which I believe is the third scale degree, leading to the root of the ii chord.
Upon further investigation of the Enjoy tune, I found myself confused on several fronts. Initially, I thought the progression was a ii-V-I-IV in the key of Gb Major (which would just be a slight variation on the progression discussed above). I stuck with that idea until I realized that the A natural passing tone doesn't belong to the key. Taking some of the guitar notes into consideration, I determined that the second chord is actually a minor chord—C#m. I then utilized a harmony tool plug-in in Ableton to expedite the process. The plug-in indicated that the progression was G#m-C#m-F#-B. When I inputted these chords into an online key-finder tool, it identified the key as B major. Consequently, the progression can be interpreted as vi-ii-V-I. What perplexed me was that despite the rearrangement, the chord progression still evoked the initial progression, and the presence of the A natural didn't align with the key of B major either!
If someone could lend a hand in analyzing this progression (and comparing it to the Human Sadness progression, if there is anything interesting to observe there) I would greatly appreciate it. It's been driving me crazy! Thank you in advance.
Comment: I listened to your entire suggested song by Enjoy and couldn't hear any G#m-C#m-F#-B chord progression in it. In fact, I heard the song as being in F major and sometimes F minor instead...and I even disagree with your chordal analysis (that starting chord isn't even consistently a vi chord, and the V chord also may even be more of a v chord instead). **Which timestamps in the Enjoy song do you want to highlight?**
Comment: Thank you for the comment and answer @Dekkadeci!  I'd say just 0:00 to 0:07, as that contains one full instance of the progression.
Answer: Taking your question naively, ii-V-I-vi and vi-ii-V-I are rotations of each other - just "claim" to start each looping chord progression in a different place or equivalently put the ending chord of one at the beginning and you get each other. It's rather like how a Google search for "vi IV I V" gets you a ton of results for its rotation I-V-vi-IV.
Comment: Thank you!  I noticed this pattern as well, but shouldn't having the tonic on the 3rd beat (strong beat) result in a significant difference compared with having the tonic on beat 4?  I rarely see the last chord of a progression being a I chord in pop songs, but that could just be me
Answer: As already noted, the root motion and main chords are the same, but I don't think that totally explains it.
It sounds like the chords in both songs aren't just triads, but include extensions (sevenths, sixths, ninths or other intervals in addition to the root, third and fifth). There may also be some inversions, for example a major six chord is an inverted version of a minor seven chord.
I am not honestly sure on the analysis of either song. They may even be the same chords. But if we include the inversions and extensions, even with different chords they could have the same root motion and contain chords that are only different by one note. For example, I6 - vi7 - IVmaj7 - V6 and vi7 - ii7 - V7 - Imaj7.
Answer: They sound the same, because it is the same progression of chords.
The only difference is the placement of the bar line...

|vi-ii-V--I|vi-ii-V--I|vi-ii-V--I|vi-ii-V--I|
   |ii-V--I-vi|ii-V--I-vi|ii-V--I-vi|ii-V--I-vi|

Placement of the bar line can be very important, especially if you're dealing with actual functional harmony and cadences. The difference between these two identical progressions is based on bar line placement...

I|V I
I V|I

...where the resulting difference is a half cadence versus an authentic cadence, and if you understand the structural importance of cadences it is a profound difference.
However, I imagine that your two progressions will involve a lot of repeating - ||:vi ii V I:|| or ||:ii V I vi:|| - and not necessarily aligned with phrase/section ending, and so are not particularly functional in the structural sense. In such cases the progressions may sound nearly identical, because there is no cadential/structural aspect at play to differentiate them.
I hope I'm not sounding to vague about cadence and structure. It requires familiarity two quite different harmonic styles. Something like the progressions/cadences/phrasing of a Bach chorale compared to the repetitious groove patterns found in pop/rock music. You may see chord root progression by descending fifths in both styles, but they are used very differently in terms of structure and phrasing.
Maybe the way to put is this: if the V and I chords in either of your progressions does not coincide with some kind of phrase or section ending, then they aren't really "functional" as dominant and tonic chords, not in the sense that function relates to structure, and without that distinction, there really isn't much to make the two progressions sound or feel different.
If, instead of...
||:vi ii V I:|| or ||:ii V I vi:||
...the bar lines were like this...
| ... vi ii | V     | I ...
or
| ... ii V  | I     | vi ...
...the two progression should then feel quite different.
You find that type of structural use of descending fifths progressions (in a pop music setting) with old 32 bar standards. Surely in other pop styles too, but old standards would be a good source to study.


Multiple sql inserts in spring boot

Question: I have a code as following :
Offre o = offreRepository.save(offre);
for(OffreCompetence offreCompetence : offre.getOffreCompetences()) {
    offreCompetence.setOffre(o);
    offreCompetenceRepository.save(offreCompetence);
}

So as you can see I'm calling the offreRepository for the first time to insert an Offre into database, then I call offreCompetenceRepository multiple times to insert each OffreCompetencein the Offre to the database.
The problem here is that I'm making a connection to the database multiple times.
Isn't there any other method to do these inserts in once ?
Edit :
I tried to add this line :
@OneToMany(cascade = CascadeType.ALL, mappedBy="offre")
   private Set<OffreCompetences> offreCompetences;

But the offreCompetences are not added to the database, when I checked the log file I noticed that Hibernate doesn't INSERT them but I can't find them in the database, I think the problem is when he try to add offreCompetences he doesn't know the id of the Offre for them :
Hibernate: insert into offre (date_expiration, date_publication, duree_mission, email_sended, etat, niveau_experience, nombre_postulant, nombre_vue, poste, profil_recherche, titre, code_type_contrat, code_ville) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2016-07-28 16:08:13.237 DEBUG 10736 --- [nio-8080-exec-4] org.hibernate.SQL                        : insert into offre_competence (competence, niveau_requis, offre) values (?, ?, ?)
Hibernate: insert into offre_competence (competence, niveau_requis, offre) values (?, ?, ?)
2016-07-28 16:08:13.304 DEBUG 10736 --- [nio-8080-exec-4] org.hibernate.SQL                        : insert into offre_competence (competence, niveau_requis, offre) values (?, ?, ?)
Hibernate: insert into offre_competence (competence, niveau_requis, offre) values (?, ?, ?)
2016-07-28 16:08:13.339 DEBUG 10736 --- [nio-8080-exec-4] org.hibernate.SQL                        : insert into offre_competence (competence, niveau_requis, offre) values (?, ?, ?)
Hibernate: insert into offre_competence (competence, niveau_requis, offre) values (?, ?, ?)

Answer: You need to ensure that the parent object is set in every object in the list. The Cascade persist will ensure that the object and its children are saved and linked correctly. Unfortunately, if it is not explicitly set it will not create the relationship in the database.
    for(OffreCompetence offreCompetence : offre.getOffreCompetences()) {
        offreCompetence.setOffre(offre);
    }
    Offre o = offreRepository.save(offre);

Answer: Set the CascadeType on the offre.offreCompetences relationship.
@Entity
public class Offre {

   @OneToMany(cascade = CascadeType.ALL, mappedBy="offre")
   private Set<OffreCompetences> offreCompetences
   ...
}

@Entity
public class OffreCompetences {
    @ManyToOne
    @JoinColumn(name = "..." )
    private Offre offre;
}

Once you do this, offreCompetences will be saved when you save offre.
Look at the JPA docs for CascadeType.
Comment: I realize we have a bit of a language barrier, but what does 'I can't find them in the database' mean? Did you commit the transaction? How are you looking for them? Basically, you really need to provide some details about **how** you are doing things for us to provide help. Regarding 'he doesn't know the id of the Offre', hibernate should handle this mapping for you. The '?' in the log are just placeholders.
Comment: thanks for your time, I've resolved my problem thanks to @KubenT answer's
Comment: Just to point out, your original example had you setting the offre in the offreCompetency. You must have removed it in between. The `CascadeType` is what solved your problem.

Multiple sql inserts in spring boot


How to swap elements in MutableList in Kotlin?

Question: I have a list with data that I pull from api. However, I need to make changes on this list (movieList). I need to swap the element at index 0 with the element at index 1. For example:

list[0] = movieA,
list[1] = movieB

then

list[0] = movieB,
list[1] = movieA

The class I intend to do these operations is below:
data class MovieListDto(
    val docs: List<Movie>,
    val limit: Int,
    val offset: Int,
    val page: Int,
    val pages: Int,
    val total: Int
)

fun MovieListDto.MovieListDtoToMovieList(): List<Movie> {
    val movieList = mutableListOf<Movie>()

    for (movie in docs) {
        if (movie._id == "5cd95395de30eff6ebccde5c" ||
            movie._id == "5cd95395de30eff6ebccde5b" ||
            movie._id == "5cd95395de30eff6ebccde5d"
        ) {
            movieList.add(movie)
        }
    }
    return movieList
}

How can I do this?
Answer: You could use a simple extension function for that:
fun <T> MutableList<T>.swap(index1: Int, index2: Int){
    val tmp = this[index1]
    this[index1] = this[index2]
    this[index2] = tmp
}

it can be use like this:
list.swap(0, 1)

Answer: I think you can use also scope function to swap
movieList[0] = movieList[1].also { movieList[1] = movieList[0] }

Answer: use Collections.swap() method in JDK
see https://developer.android.com/reference/java/util/Collections#swap(java.util.List%3C?%3E,%20int,%20int)
Answer: Use the Kotlin extension function, this function can be called on instances of the class.(@birneee answer)
fun <E> MutableList<E>.swap(index1: Int, index2: Int){
    this[index1] = this[index2].also { this[index2] = this[index1] }
}

or just use also scope function (@putra-nugraha answer)
list[index1] = list[index2].also { list[index2] = list[index1] }

Answer: val temp = movieList[0]
movieList[0] = movieList[1]
movieList[1] = temp

Comment: Yeah, it works of course, but I actually wanted to ask if there is a special function for this in Kotlin (my mistake).


How to solve this Green's theorem Question?

Question: I have been given the question by my university as an Assignment to solve. I have solved but when I shared with my fellows they are saying the answer of this question is zero, but I am getting the other answer. I have tried all the ways, I am so confused that how the answer is zero? Kindly anyone help me in this.
QUESTION:

MY TRY:

Kindly anyone help me in this.
Answer: You wrote the formula wrong.
$$\oint_{C}(Ldx+Mdy)=\iint_{D}\left(\frac{\partial M}{\partial x}-\frac{\partial L}{\partial y}\right)dxdy$$
$$\oint_{C}(2xydx+x^2dy)=\iint_{D}\left(2x-2x\right)dxdy=\iint_{D}0dxdy=0$$
Comment: There is a theorem that **says** that if $\frac{\partial Q}{\partial x}= \frac{\partial P}{\partial y}$ then the integral around any closed path is 0. That s because, in such a case, there exist F(x,y) such that $dF= P(x,y)dx+ Q(x,y)dy$.   In this case, you can see that by writing $2xydx+ x^2dy= d(x^2y)$ so that the *anti-derivative* is $F(x,y)= x^2y$.  Choose any point on the path as the mutual "starting point" and "ending point".  That anti-derivative, evaluated at the "starting point" and "ending point" will give the same thing so subtracting gives 0.
Comment: @KhubaibKhawar The cancellation is valid since $2x-2x=0$ for all $x$ and the integral becomes $0$ since you you can pull out a constant from the integral and you get $0\cdot$(Integral), which is $0$.
Comment: are you sure is it true? I mean I already realized that I wrote the formula wrong. But do not we have to go through the process of integration instead of just canceling them out and making it zero?
Comment: thank you buddy :) and yeah I know that the cancellation is valid, but I was still asking to be confirmed that if we still need to do the process of Integration or not. Thanks a lot :)
Comment: @KhubaibKhawar No problem :)
Answer: At one point you say, $\oint_C Pdx+ Qdy= -\int_R\int\left(\frac{\partial P}{\partial y}- \frac{\partial Q}{\partial x}\right)dxdy$ is the same as $\oint_C Pdx+ Qdy= \int_R\int\left(\frac{\partial P}{\partial y}+ \frac{\partial Q}{\partial x}\right)dxdy$. I don't know where you got that.  At first I thought you were just taking that outside negative into the integral but if you were doing that it would be $\int_R\int\left(-\frac{\partial P}{\partial y}+ \frac{\partial Q}{\partial x}\right) dxdy= \int_R\int\left(\frac{\partial Q}{\partial x}- \frac{\partial P}{\partial y}\right)dxdy$
Comment: Thank you, yeah I realized this mistake. But do we just cancel out the `Pdx` and `Qdy` as they are same or do we still need to go through the whole process of Integration?


Show that $z^5 - z +16$ has two roots in the right half plane

Question: Show that the polynomial
$$z^5 - z +16$$
has all of its roots in the region
$$\{z\in \mathbb{C} \; | \; 1< |z| < 2\},$$
and show that two of its roots have positive real part.
I have used Rouché's theorem to prove that all of its roots are in the above region. But I don't have any clue on how to show the second part, that two of the roots are in the right half plane.
Comment: Use the argument principle with a D shaped contour centered at the origin.
Comment: Do you want to show that *exactly* two of the roots have positive real part or *at least* two do?
Answer: Use the argument principle on a large D-shaped loop traversed anti-clockwise.
let $P(z) = z^5-z+16$ and first watch $P(z)$ on the imaginary axis.
$P(iy) = 16 + i(y^5-y)$ so it stays in the right half-plane, and looking at limits when $y \to \pm \infty$ we see that its argument decreases by $\pi$ as $y$ goes down from $+\infty$ to $-\infty$.
Meanwhile, if you look at $P$ on a large half-circle in the right half plane, $P(z) \sim z^5$, so that when $z$ follows along the circle, its argument increases by $\pi$ and so $z^5$ and $P(z)$'s argument increase by $5\pi$.
In total the argument changes by $5\pi-\pi = 4\pi$ during the entire loop, so it must have two roots inside it.
Comment: Why we subtract $5\pi$ with $\pi$? (not addition?)
Answer: Hint: Let $\mathcal{R}$ be the right half plane.

Let $P(X)$ be a polynomial with real coefficients. Show that if $\alpha$ is a root of $P(X)$, then so is its complex conjugate $\bar{\alpha}$.
Show that $P(X)=X^5-X+16$ has only one real root which is negative. (You can use your already existing result to show all real roots are negative. Furthermore, by showing thta $P(X)$ is monotonic in $1<|x|<2$, you'll be able to seal the deal).
Conclude that the roots of $P(X)$ are of the form $r\in \mathbb{R}$ negative, $\alpha, \bar{\alpha}$ and $\beta, \bar{\beta}$ all complex roots. Argue that $P(X)$ has either zero, two or four roots in $\mathcal{R}$. Also show that
$$P(X)=(X-r)(X^2-2AX+|\alpha|^2)(X^2-2BX+|\beta|^2)$$
where $A=\mathrm{Re}[\alpha]$ and $B=\mathrm{Re}[\beta]$.
By expanding the above relation (keep an eye on $X^4$), Prove that
$$
r=-2(A+B)
$$
Then show that $A+B>0$, and therefore having zero roots in $\mathcal{R}$ is impossible.
Again by expanding the above relation (keep an eye on $X^2$), and the previous part, show that
$$
|\alpha|^2 A +
|\beta|^2 B + 4AB(A+B)=0
$$
Argue that it is impossible to have both $A>0$ and $B>0$. This finishes the job.


parsing NSMutableDictionary with required format

Question: I have an objective C object 'Obj' with an
@property (strong, nonatomic) NSMutableDictionary *obj;

This gets populated with data from an api in following format.
{
  0 =     (  0, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59 );
  1 =      (  1, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );
  2 =     (  2, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );
  3 =     (  3, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );
  4 =     (  4, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );
  5 =     (  5, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );
  6 =      (  6, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59 );
}

I need to parse the data and send it back as an array in following format.
`{
[ 0, 7, 00, 8, 59 ],
[0, 15, 00, 16, 59] ,
[0, 19, 00, 20, 59] ,
[ 1, 7, 00, 8, 59 ],
[1, 15, 00, 16, 59] ,
[1, 19, 00, 20, 59],
……
……
[ 6, 7, 00, 8, 59 ],
[6, 15, 00, 16, 59] ,
[6, 19, 00, 20, 59]
}`

Where 0,1,2,3,4,5,6 are days and rest of the information is hours and mins. so for each slot, the format is
`[day, from_hour, from_min, to_hour, to_min],
 [0, 7, 0, 8, 59],`

A day could have multiple slots or just one slot.
So far I manage to run a loop and separate each day's record as below.
NSMutableArray *elementArray =[[NSMutableArray alloc ]init];
NSMutableArray *results =[[NSMutableArray alloc ]init];
NSInteger starthour = 0 ;
NSInteger startmin = 0 ;
NSInteger endhour = 0 ;
NSInteger endmin = 0 ;
NSMutableArray *temp = [[NSMutableArray alloc]init];
NSString *string;
int i = 0;
for ( i = 0; i <=6; i ++){
    string = [NSString stringWithFormat:@"%d",i];
    elementArray =[Obj.obj valueForKey:string];
    starthour = [[elementArray objectAtIndex:1]integerValue];
    startmin =([[elementArray objectAtIndex:1]floatValue]-[[elementArray objectAtIndex:1]integerValue])*100;
    endhour = [[elementArray objectAtIndex:2]integerValue];
    endmin =([[elementArray objectAtIndex:2]floatValue]-[[elementArray objectAtIndex:2]integerValue])*100;
    NSNumber *day = [NSNumber numberWithInteger:[string integerValue]];
    NSNumber *starthour1 = [NSNumber numberWithInteger:(int)starthour];
    NSNumber *startmin1 = [NSNumber numberWithInteger:(int)startmin];
    NSNumber *endhour1 = [NSNumber numberWithInteger:(int)endhour];
    NSNumber *endmin1 = [NSNumber numberWithInteger:(int)endmin];
    [temp addObject:day];
    [temp addObject:starthour1];
    [temp addObject:startmin1];
    [temp addObject:endhour1];
    [temp addObject:endmin1];
    [results addObject:temp];
}

This gives me access to each record. My thought process is saying I could solve this by going through each record and populating the required array as, 'i' being the day, then running a nest loop on each record and extracting hours and mins?
Comment: Are you getting information as JSON or any other formate?
Comment: Yes, i am getting information as JSON.
Comment: Share JSON so I can understand your problem
Comment: {
    "id" = "1234"; "temp" = "30.85";obj =    {
    0 =     (  0, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59 );  1 =      (  1, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );    2 =     (  2, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );    3 =     (  3, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );     4 =     (  4, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );  5 =     (  5, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59  );
    6 =      (  6, "7.00", "8.59", "15.00", "16.59", "19.00", "20.59 ); };}
Comment: this is not a valid JSON, Please share valid JSON.
Comment: JSON is not an issue, I have parsing and updating the incoming data correctly. Its the when I need to send back the data I need to only send 'obj' object as array.
Comment: ok. But how can I give you any suggestion with out looking in to input values
Comment: This is how I am getting after NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error]; Now I am updating few textfields successfully with obj data coming from servers, and these values are updated by UI and obj records always being updated, so values are constantly changing.
Comment: @AbdulRehmanWarraich It seems to be the print of a `NSDictionary`, nothing too complex here.
Comment: try to use regular expression. It will save your days in future.
Answer: You don't say what your problem actually is, i.e. you started on a solution and stopped and turned to SO, why?
Let's see if we can help you along with some pseudo-code.
You have a dictionary of arrays. the keys represent day numbers as do the first element of each array. After the first array element the elements come in pairs, each is a string containing a textual representation of hours and minutes separated by a full stop. You want and array of arrays where each element has 5 members: day number, start hour, start min, end hour, end minute, all as numbers.
A basic algorithm to handle this is two nested loops. You need somewhere to store the result:
results <- new empty array

Now you need to iterate over your dictionary:
for every key in sourceDictionary
   elementArray = sourceDictionary[key]

[This is the loop you've written, except you generated the keys and looked them up while here we extract the keys from the dictionary. If you wish to process the keys in a particular order then generating them in that order, or extracting and sorting them, will handle that.]
Now you'd better do some data validation, elementArray should have at least the day number and one pair of strings in it, test for that:
   check elementArray count > 1 and odd else handle error

Now you need to process each pair of strings, first access them:
   cursor <- 1 // element 0 is the repeated day number
   while cursor < elementArray count do
      startTime <- elementArray[cursor]
      endTime <- elementArray[cursor+1]
      cursor <- cursor + 2 // ready for next iteration

So now you have the day number, key, and the start and end times as string, startTime & endTime. Now you need to split your time strings at the full stop, returning an array of substrings:
      startParts <- startTime split at "."

More checks, did you get two parts?
      check startParts count is 2 else handle error

Now convert each substring to an integer:
      startHours <- parse startParts[0] as integer
      startMins <- parse startParts[1] as integer

And keep checking:
     check startHours in [0, 23] and startMins in [0, 59] else handle error

You've now got the five values you want, add them to your results array:
     results <- results append array of (key, startHours, startMins, endHours, endMins)

Now just convert that to Objective-C and fill in the details. The first loop could be a for in one, the second a for(init; test; increment) one. For splitting a string look at NSString's methods, one will fit the bill. For parsing there are multiple options including NSString methods.
HTH
Comment: int i = 0;

    do{
        NSLog(@"%@",[elementArray objectAtIndex:i]);
        i++;
    }
    while( i < [elementArray count]);  This gives me each day as (
    1,
    "7.00",
    "8.59",
    "15.00",
    "16.59",
    "22.00",
    "23.59"
)
Comment: @humble_pie What is your question? From your comment you now appear to have an array of arrays, rather then a dictionary of arrays (so `sourceDictionary` in the answer correspond with `elementArray` in your comment and `elementArray` in the answer corresponds with `[elementArray objectAtIndex:i]` in your comment). So where you have `NSLog` in your comment corresponds to the stage in the answer starting "Now you'd better do some data validation...". Is there something after that point which is causing you difficulty? If so what, what have you tried, etc.
Comment: @humble_pie **Edit your question** to provide further details as above, **do not** try to squeeze code into comments. You may add a comment to this this answer saying you've added information to your question if you wish.
Comment: I have updated the code. Basically I am extracting keys and values from dictionary into element's array as you suggested. Then In the for loop try to parse each day and time slots but it seems to run multiple times for each day
Comment: i got it working, but code looks a bit messy, please see my answer
Answer: I got it working with desired output, but code looks messy, could be made elegant.
` NSMutableArray *elementArray =[[NSMutableArray alloc ]init];
    NSMutableArray *results =[[NSMutableArray alloc ]init];
    NSInteger starthour = 0 ;
    NSInteger startmin = 0 ;
    NSInteger endhour = 0 ;
    NSInteger endmin = 0 ;

    NSNumber *starthour1 ;
    NSNumber *startmin1  ;
    NSNumber *endhour1 ;
    NSNumber *endmin1 ;
    NSMutableArray *temp = [[NSMutableArray alloc]init];
    NSString *string;
    int i = 0;
    for ( i = 0; i <=6; i ++){
        string = [NSString stringWithFormat:@"%d",i];
        elementArray =[Obj.obj valueForKey:string];
        starthour = [[elementArray objectAtIndex:1]integerValue];
        startmin =([[elementArray objectAtIndex:1]floatValue]-[[elementArray objectAtIndex:1]integerValue])*100;
        endhour = [[elementArray objectAtIndex:2]integerValue];
        endmin =([[elementArray objectAtIndex:2]floatValue]-[[elementArray objectAtIndex:2]integerValue])*100;
        NSNumber *day = [NSNumber numberWithInteger:[string integerValue]];
           starthour1 = [NSNumber numberWithInteger:(int)starthour];
           startmin1 = [NSNumber numberWithInteger:(int)startmin];
           endhour1 = [NSNumber numberWithInteger:(int)endhour];
           endmin1 = [NSNumber numberWithInteger:(int)endmin];
        [temp addObject:day];
        [temp addObject:starthour1];
        [temp addObject:startmin1];
        [temp addObject:endhour1];
        [temp addObject:endmin1];
        [results addObject:[temp copy]];

        [temp removeAllObjects];

        starthour = [[elementArray objectAtIndex:3]integerValue];
        startmin =([[elementArray objectAtIndex:3]floatValue]-[[elementArray objectAtIndex:3]integerValue])*100;
        endhour = [[elementArray objectAtIndex:4]integerValue];
        endmin =([[elementArray objectAtIndex:4]floatValue]-[[elementArray objectAtIndex:4]integerValue])*100;

        starthour1 = [NSNumber numberWithInteger:(int)starthour];
        startmin1 = [NSNumber numberWithInteger:(int)startmin];
        endhour1 = [NSNumber numberWithInteger:(int)endhour];
        endmin1 = [NSNumber numberWithInteger:(int)endmin];
        [temp addObject:day];
        [temp addObject:starthour1];
        [temp addObject:startmin1];
        [temp addObject:endhour1];
        [temp addObject:endmin1];
        [results addObject:[temp copy]];

        [temp removeAllObjects];
        starthour = [[elementArray objectAtIndex:5]integerValue];
        startmin =([[elementArray objectAtIndex:5]floatValue]-[[elementArray objectAtIndex:5]integerValue])*100;
        endhour = [[elementArray objectAtIndex:6]integerValue];
        endmin =([[elementArray objectAtIndex:6]floatValue]-[[elementArray objectAtIndex:6]integerValue])*100;

        starthour1 = [NSNumber numberWithInteger:(int)starthour];
        startmin1 = [NSNumber numberWithInteger:(int)startmin];
        endhour1 = [NSNumber numberWithInteger:(int)endhour];
        endmin1 = [NSNumber numberWithInteger:(int)endmin];
        [temp addObject:day];
        [temp addObject:starthour1];
        [temp addObject:startmin1];
        [temp addObject:endhour1];
        [temp addObject:endmin1];
        [results addObject:[temp copy]];

        [temp removeAllObjects];
`

The output is what I wanted looks like below.

(
          (
          0,
          7,
          0,
          8,
          59
      ),
          (
          0,
          15,
          0,
          16,
          59
      ),
          (
          0,
          19,
          0,
          20,
          59
      ),
          (
          1,
          7,
          0,
          8,
          59
      ),
          (
          1,
          15,
          0,
          16,
          59
      ),
          (
          1,
          22,
          0,
          23,
          59
      ),
          (
          2,
          7,
          0,
          8,
          59
      ),
          (
          2,
          15,
          0,
          16,
          59
      ),
          (
          2,
          19,
          0,
          20,
          59
      ),
          (
          3,
          7,
          0,
          8,
          59
      ),
          (
          3,
          15,
          0,
          16,
          59
      ),
          (
          3,
          22,
          0,
          23,
          59
      ),
          (
          4,
          7,
          0,
          8,
          59
      ),
          (
          4,
          15,
          0,
          16,
          59
      ),
          (
          4,
          19,
          0,
          20,
          59
      ),
          (
          5,
          7,
          0,
          8,
          59
      ),
          (
          5,
          15,
          0,
          16,
          59
      ),
          (
          5,
          22,
          0,
          23,
          59
      ),
          (
          6,
          7,
          0,
          8,
          59
      ),
          (
          6,
          15,
          0,
          16,
          59
      ),
          (
          6,
          19,
          0,
          20,
          59
      )
  )
Comment: It does appear to work according to your output, so well done. You might think it is untidy but there are some more problematic issues. First you have used floating point math as part of parsing two *integers* which happen to be separated by a full stop. Floating point math works in binary and so you are relying on the minute value being correct after it has been represented as a binary fraction (i.e. `.59` as a decimal fraction is 5/10 + 9/100, as a binary fraction it is 1/2 + 1/16 + 1/64 + ...). It is much better to parse integer values as integers. (cont)
Comment: Next in your question you have stated "A day could have multiple slots or just one slot", your solution essentially contains an "unrolled loop", repeating the same code 3 times and fixing the number of slots at 3. If you do have data with less than 3 time slots your code will fault. You would be better testing for the number of slots and using a loop so you both avoid faulting and repeating code. HTH
Comment: Yes floating point logic isn't great. I spent more and 2 hours finding better way of splitting the strings after decimal but couldn't get it working. On your second point, I made sure elsewhere in my code to always supply 3 time slots.
Comment: You might find [this method](https://developer.apple.com/documentation/foundation/nsstring/1413214-componentsseparatedbystring?language=objc) helpful.


Sum of $X\sim\chi^2_ \nu$ and $Y\sim\chi^2_ k$ and gamma function

Question: Suppose $X\sim\chi^2_ \nu$ and $Y\sim\chi^2_ k$ are independent.
(a) Show that $X+Y\sim\chi^2_{\nu+k}.$
(b) Additionally, find the value of
$$\int_0^1u^{\frac{\nu}{2}-1}(1-u)^{\frac{k}{2}-1}du$$
as a ratio of Gamma functions. This formula was discovered by Euler.
I was able to solve part (a) and this is my result.
Proof:
If $X$ is $\chi^2_\nu$ distributed then we can express $X$ as $X=A_1^2+\cdots+A_\nu^2$ where $A_1,\ldots,A_\nu$ are $N(0,1)$.
Similarly, if $Y$ is $\chi^2_k$ distributed then we can express $Y$ as $Y=B_1^2+\cdots+B_k^2$ where $B_1,\ldots,B_k$ are $N(0,1)$.
These two statements can be made due to the definition of $\chi_\nu^2$ with $\nu$ degrees of freedom.
Now, we know that the sum of two independent random variables preserves independence, therefore, adding $X+Y$ we obtain
$$X+Y=A_1^2+B_1^2+\cdots+A^2_\nu+B_k^2$$
We can conclude that
$$X+Y \sim \chi^2_{\nu+k}$$
However, I am uncertain as to how to compute (b). I have seen and computed Gamma integrals but they have been in the conventional form with an exponential term and $1$ variable. This integrals contains $2$ variables and so I am uncertain how to go about it.
Answer: Suppose the joint distribution of $R,S$ is
$$
\underbrace{\frac 1 {\Gamma(\nu/2)} \left( \frac r 2 \right)^{\nu/2-1} e^{-r/2} \, \frac{dr} 2} \times \underbrace{ \frac 1 {\Gamma(\kappa/2)} \left( \frac s 2 \right)^{\kappa/2} e^{-s/2} \, \frac{ds} 2} \tag 1
$$
so $R,S$ are independent and each has a chi-square distribution.
Let $t = r+s$ and $u= r/(r+s)$. Then $r=tu$ and $s=t(1-u).$ Then we have the Jacobian
$$
dr\,ds = \left| \frac{\partial(r,s)}{\partial(t,u)} \right| \, dt\,du = \frac{dt\,du} t.
$$
So $(1)$ becomes
\begin{align}
& \frac 1 {\Gamma(\nu/2)\Gamma(\kappa/2)} \left( \frac{tu} 2 \right)^{\nu/2-1} \left( \frac{t(1-u)} 2 \right)^{\kappa/2-1} e^{-t/2} \, \frac{dt\,du} {4t} \\[10pt]
= {} & \underbrace{ \frac {\Gamma((\nu+\kappa)/2)} {\Gamma(\nu/2)\Gamma(\kappa/2)} u^{\nu/2-1} (1-u)^{\kappa/2-1} \, du} \times \underbrace{ \frac 1 {\Gamma((\nu+\kappa)/2)} \left( \frac t 2\right)^{(\nu+\kappa)/2-1} e^{-t/2} \, \frac{dt} 2}
\end{align}
and from this we conclude that $R/(R+S)$ has a Beta distribution with parameters $\nu,\kappa$ and $R+S$ has a chi-square distribution with $\nu+\kappa$ degrees of freedom, and that $R/(R+S), R+S$ are independent.
Since we know the second factor in the last expression above is a probability measure rather than a constant multiple of one, we can conclude the same about the first factor, and thus conclude that
$$
\int_0^1 u^{\nu/2-1} (1-u)^{\kappa/2-1} \,du = \frac{\Gamma(\nu/2)\Gamma(\kappa/2)}{\Gamma((\nu+\kappa)/2)}.
$$


Problema com "on change" seguido de "on click"

Question: Tenho o seguinte código HTML:
<code><input type="text" id="esc" />
<input type="button" value="Ok" id="ok" />
</code>
E jquery/javascript:
<code>$(document).on("change", "#esc", function(){
    alert("esc");
});

$(document).on("click", "#ok", function(){
    alert("ok");
});
</code>
Quando eu digito um texto numa textbox e clico direto no Ok ele não executa o codigo dentro da função do click. Somente o código da função do change.
Segue exmeplo no fiddle: http://jsfiddle.net/8389g5rj/1/
Qual o motivo disso e como posso resolver esse "conflito" ?
Answer: Joao,
O que acontece é o seguinte.
Quando você altera o texto, liberando assim a trigger do change do textbox e tenta clicar no botão. O evento é disparado antes do click e o alert é chamado, fazendo então cancelar seu evento de click.
Se você mudar o código para o seguinte.
<code>$(document).on("change", "#esc", function(){
    console.log("esc");
});

$(document).on("click", "#ok", function(){
    console.log("ok");
});
</code>
Você vai ver que os dois eventos são disparados normalmente. O problema do seu exemplo é o alert, que se torna preemptivo e impede que dispare o evento de click do botão, porque ele "passa na frente".
Deu para entender?
Para explicar melhor. O evento do seu botão é o "click" certo? Ele é disparado quando o usuário clica no botão. Porém no seu text input ele dispara o evento de change assim que você sai do text input, e por milissegundos (perspetivável para nós seres humanos) ele dispara o evento de change e dentro do evento de change chama o alert ANTES de você ter conseguido efetivamente clicado no botão. E quando o alert foi chamado "cancelou" seu click, por que na verdade você não conseguiu click no botão Ok.
Comment: Então se eu não tiver nenhum alert no meu código real esse problema não irá ocorrer? Não captei a definição de preemptivo
Comment: @JoaoPaulo Se você não tiver nada que "interrompa" o próximo evento. Por que o alert é chamado, ele depende de uma ação do usuário e ele é preemptivo, em outras palavras para o browser um alert é mais importante do o próximo evento (por exemplo). De maneira simples sem os alerts seus evento vão ser disparados de forma encadeada normalmente.
Comment: Interessante, não sabia desse tipo de comportamento!
Comment: Veja minha última edição onde eu tento explicar melhor.


Forming a recurrence relation from tiling a block

Question: Suppose we wish to tile a $2\times n$ rectangular board with smaller tiles of $1\times 2$ and $2\times 2$ blocks.
Let $a_n$ be the number of ways this can be done.
Find a recurrence relation for $a_n$.
This is my attempt:
The area of our big block is $2n$. Suppose we tile it initially with a $2\times 2$ block. Then the remaining area is $2n-4 = 2(n-2)$. The rest of this can be tiled in $a_{n-2}$ ways.
Now, suppose we tile it initially with a $1\times 2$ block. Intuitively, we must, in the future, tile it with another $1\times 2$ block. Now once we place the $1\times 2$ block down, we have a joint piece of $1\times 2$ and a $2\times (n-2)$ block to fill. We fill the latter in $a_{n-2}$ ways. The former can be filled in $n/2$ ways (since it depends where we initially tiled the $1\times 2$.
So total is
$$a_n = 2a_{n-2} + \frac{n}{2}.$$
However, the solution is $a_n = a_{n-1} + 2a_{n-2}$.
Where in my flow of logic did I go wrong and how can I get their solution?
Answer: I think that here the tile $1\times 2$ can be rotated (otherwise $2\times n$ board can not be tiled when $n$ is odd).
Now the last tile in the board $2\times n$ can be:
$$\text{a $2\times 1$ rectangle, or a $2\times 2$ square, or a pair of $2\times 1$ rectangles.}$$
Since these final tiles yield distinct tilings, we have that for $n\geq 3$,
$$a_n=a_{n-1}+a_{n-2}+a_{n-2}=a_{n-1}+2a_{n-2}.$$
Note that $a_1=1$, $a_2=3$.


Some issues about Uniform Distibution in Inverse Transform Method

Question: There is a theorem about inverse transform method says if X is a continuous random variable with cdf F, then U=F(X)~U[0,1]
So I am wondering the logic in this sentence.
Why if X is a continuous random variable with cdf F, then U=F(X)~U[0,1]?
Why is it always be uniform and
how does this theorem work in real example?
Answer: This fundamental fact follows directly from the definition of a cumulative density function (CDF), after applying some clever manipulation.
The definition of the CDF is the following

A function $F$ is called the CDF of a random variable $X$ when, for every number $z$, $P(X < z) = F(z)$.

Now, if we are in the above situation, we can ask

What is the CDF of the random variable $F(X)$?

Let's see
$$P(F(X) < z) = P(F^{-1}(F(X)) < F^{-1}(z)) = P(X < F^{-1}(z)) = F(F^{-1}(z)) = z $$
Here:

In the first equality I have used that a CDF is always an increasing function.  Otherwise there would be no (or a much more complex) relation between the two probabilities.
In the second to last equality I have used the definition of a CDF, applied to the fact that $F$ is the CDF of the random variable $X$.

Reading from top to bottom:
$$P(F(X) < z) = z $$
Which, comparing with the definition of a CDF again, shows that the CDF of $F(X)$ is the identity function.  The identity function is also the CDF of the uniform distribution.  Distributions are the same if and only if their CDF is the same, so this also means that
$$ F(X) \sim U(0, 1) $$
Comment: @BrattSwan It's a classic.
Comment: This seems like a really interesting result and I finally figure it out. Thanks!
Comment: However, suppose I have a pdf f=3*x^2, the the cdf of f, which is F=x^3, the cdf of F, which is 0.25*x^4, which is not a identity function. Is there anything I misunderstood?


Entity Wrapper : how to delete multiple values field?

Question: I have a multiple values field on the user entity. This field is field_data.
There are several values in this field. I want to delete all of them.
I tried the following code:
for ($i = 0; $i < count($user->field_data->value()); $i++) {
    $user->field_data[$i]->delete();
}

But I get errors about ->delete() not being a method on this object. I also tried with ->clear() to no avail.
I've been looking for examples on Google for how to do this, but my Google-fu is not so strong today.
Comment: I think you are looking for [this solution](http://drupal.stackexchange.com/questions/31794/programmatically-delete-one-entry-from-one-field-on-one-entity).
Comment: @AnilSagar The solution provided in the answer doesn't use the wrapper. (which means it's language dependant, and others drawbacks as well)
Answer: Well, I solved it. The answer is kind of tricky.
You can't delete a value in a multiple values field. However, you can set it to "empty". When it's empty, it's removed.
Here is the code to use:
// Also, note the ->count() method
for ($i = 0; $i < $user->field_data->count(); $i++) {
  $user->field_data[$i]->set();
}

This way, values are now empty and the multiple fields have no value left. It's well shown in the UI too and the deltas are correctly handled in the database.
Comment: in php 7.2: ArgumentCountError: Too few arguments to function EntityDrupalWrapper::set(), 0 passed


codigo em linguagem R

Question: Alguem consegue me explicar o que o codigo abaixo executa?
cluster <- ml_kmeans(variaveis_clusters_tratado, CODCLI ~ ., k = 5)
clusters <- ml_predict(cluster, variaveis_clusters_tratado)

Answer: A linha cluster <- ml_kmeans(variaveis_clusters_tratado, CODCLI ~ ., k = 5) cria um modelo K-MEANS com os dados do dataset variaveis_clusters_tratado, seguindo a formula CODCLI ~ ., com 5 Clusters, isto é, k=5.
A linha clusters <- ml_predict(cluster, variaveis_clusters_tratado) tenta predizer os valores de variaveis_clusters_tratado usando o modelo que foi criado na primeira linha, isto é, o clusters.
Ao mesmo tempo em que faz isso, essa linha sobrepõe na memória do R o modelo criado. Isto é, ela usa o modelo e depois substitui ele com o resultado da predição, que provavelmente será um dataframe.
Comment: obrigada pela ajuda!!!

codigo em linguagem R


Invariant subfields and Galois group

Question: Let $f$ be an irreducible polynomial of degree $n$ over $\mathbb{Q}$. Let $K$ be the splitting field of $f$ over $\mathbb{Q}$. Let $\alpha\in K$ be a root of $f$. Let $H$ be the subgroup of $G$ that fixes $\alpha$. Let $N=N_G(H)=\{g\in G| g(\alpha)\in\mathbb{Q}(\alpha)\}$.

Is it true that the number of distinct subfields of $K$ which is ismorphic to $\mathbb{Q}(\alpha)$ equal $|G|/|N|$ (so this number doesn't depend on $n=deg(f)$ explicitly)? Thank you.
Answer: I believe so.
If $L$ is a subfield of $K$ isomorphic to $\mathbb{Q}(\alpha)$, then since $K$ is a splitting field this isomorphism can be extended to an automorphism $K \to K$ fixing $\mathbb{Q}$, i.e an element $\sigma$ of $G=Gal(K/\mathbb{Q})$. So $L=\sigma(\mathbb{Q}(\alpha))$, i.e every subfield of $L$ isomorphic to $\mathbb{Q}(a)$ is a Galois conjugate of $\mathbb{Q}(a)$.
So $G$ acts on the set of subfields of $K$ isomorphic to $\mathbb{Q}(a)$ (because this set is the same as the set of conjugates of $\mathbb{Q}(a)$), and the stabilizer for this action is $N=\{g \in G \mid g(\alpha) \in \mathbb{Q}(a)\}$. So the size of the orbit is the order of the group divided by the size of the stabilizer.

Invariant subfields and Galois group


PHP cURL request - Cloudflare

Question: is there any way to bypass Cloudflare with PHP cURL request?
Like solving the captcha manually and then passing the data to the cURL request?
Thanks in advance.
Answer: It's needed to save the cookies and control the session manually, so you can display the captcha for the user to solve through some page and then you will be able to resume the cURL process.
However it's a lot of work as you will have to sniff and understand how Cloudflare works in order to make the right requests. Therefore... haven't you considered using PhantomJS, CasperJS, SlimerJS or NightmareJS?

PHP cURL request - Cloudflare