strucchange package on ARIMA model

Question: Is there a way to use strucchange package in R on ARIMA models?
I haven't been able to find any.
Thanks a lot.
Answer: The package strucchange requires as input the formula of a linear model to be passed to lm. I don't think there is a straightforward way to use the package with function arima. I don't know either any other R packages implementing this but I can give some basic guidelines that may be helpful for your purposes.
You can carry out some diagnostics based on the cumulative sum of squared residuals (CUMSUM) and based on F-tests for the parameters of the model in different subsamples.
Let's take for illustration the following simulated AR process, x. The first 50 observations are generated from an AR(1) model and the next 100 observations
from an AR(2) model:
set.seed(135)
x1 <- arima.sim(model = list(order = c(1,0,0), ar = -0.2), n = 50)
x2 <- arima.sim(model = list(order = c(2,0,0), ar = c(0.3, 0.5)), n = 100)
x <- ts(c(x1, x2))

CUMSUM approach: Once an AR model is fitted to the entire series the CUMSUM process can be obtained as follows:
fit <- arima(x, order = c(2,0,0), include.mean = FALSE)
e <- residuals(fit)
sigma <- sqrt(fit$sigma2)
n <- length(x)
cs <- cumsum(e) / sigma

As a reference, confidence limits can be obtained as done in package strucchange for the OLS-based CUSUM test. For that, we can create an object of class efp and plot it:
require(strucchange)
retval <- list()
retval$coefficients <- coef(fit)
retval$sigma <- sigma
retval$process <- cs
retval$type.name <- "OLS-based CUSUM test"
retval$lim.process <- "Brownian bridge"
retval$datatsp <- tsp(x)
class(retval) <- c("efp")
plot(retval)

The confidence limits are just for reference, I'm not sure they are the right
values to carry out a formal test in this context. Regardless of this, a sudden change or shift in the sequence cs can be interpreted as a sign that something is going on around that time point, possibly a structural change. In the plot we observe that at around observation 50, where we introduced a change in the data generating process.
F-tests: Another approach is based on F-test statistics computed as:
$$
Fstat = \frac{RSS - USS}{RSS/n}
$$
where RSS is the residual sum of squares in the restricted model (the model fitted for the entire data) and USS is the residual sum of squares of models fitted to two subsamples. The statistics can be computed iteratively for the following sequence of subsamples: from observations 1 to 20 and 21 to $n$; then from 1 to 21 and a next subsample from 22 to $n$, and so on as done below:
rss <- sum(residuals(fit)^2)
sigma2 <- fit$sigma2
stats <- rep(NA, n)
for (i in seq.int(20, n-20))
{
  fit1 <- arima(x[seq(1,i)], order = c(2,0,0), include.mean = FALSE)
  fit2 <- arima(x[seq(i+1,n)], order = c(2,0,0), include.mean = FALSE)
  ess <- sum(c(residuals(fit1), residuals(fit2))^2)
  stats[i] <- (rss - ess)/sigma2
}

Similarly to the CUMSUM plot, a plot of the F-statistics may reveal the presence of a structural change. A 95% confidence limit can be obtained
based on the chi-square distribution.
plot(stats)
abline(h = qchisq(0.05, df = length(coef(fit)), lower.tail = FALSE), lty = 2, col = "red")

If the minimum p-value related to each statistic is below a significance level,
e.g. 0.05, then we can suspect that there is a structural change at that point. In this simulated series that happens at observation 50, when the AR coefficients changed in the data generating process:
which.min(1 - pchisq(stats, df = 2))
#[1] 50

You may find further details in the vignette of the strucchange package
that you probably already know and in the references therein.
Comment: @Frank The ideas in this answer gave an overall idea about how to adapt the methods already available in strucchange to the case of ARIMA models. There is literature specific for the detection of structural breaks in time series, see for example the references given [here](https://stats.stackexchange.com/questions/150998/equivalence-of-regression-models-and-arima-models/151002#151002).
Comment: @Frank It's interesting to see that the method shows a sensible performance in the simulation exercise. The issue that I see with using segments is that not all the data are used at the same time. The standard deviation of parameters may be higher and this may affect the test if no break is actually present. Anyway, with a relatively large sample as the one in your example, it seems a sensible approach to try.
Comment: @Frank Instead of segments like [0-50], [51-100], [101-150],... it could be interesting to use a moving window, e.g.: [0-50], [10-60], [20-70], ... and see the behavior of the statistic for structural break at each point. For example, see if there is a spike
when the window enters an observation,... The distribution of the statistic at a given observation in this moving-window-approach may in fact have a distribution under the null of no break, which could be worth exploring by simulations and perhaps analytically, but this would require some further thought.
Comment: @Frank Finally, another possibility is an iterative process in which ARIMA models are fitted to different segments as new structural breaks are found. For example, if a break is found at observation 60, then fit an ARIMA model for the first 60 observations an another for the remaining observations. Then reassess the significance of the break and test for another break given the last accepted multi-ARIMA model. If interested in a similar idea, see e.g. the documentation of the software [TRAMO](https://en.wikipedia.org/wiki/TRAMO) or [tsoutliers](http://cran.r-project.org/package=tsoutliers).
Comment: + very nice and thorough answer.
Comment: Thank you for this great answer. If there are multiple breakpoints, would I simply repeat the above process on each segment? For example, you identified a breakpoint at ```t = 50```. Should I take the segments ```[0, 50], [50, n]```, fit a new ARIMA model to each, and repeat the analysis to find other breakpoints? Or is there a better published method for detecting multiple breaks?
Comment: I simulated this with the F-test method you outlined, with 400 datapoints and a break at ```t = 50```. Every time I found a break ```x = t```, I cut off data ```x < t``` and performed the algorithm again.
This gave breaks at ```49, 174, 245, and 310```, with P-values of ```0.000314, 0.00671, 0.02216, 0.0157```

The algorithm seems to consistently find breaks that are not there when applied iteratively.
Comment: I wish I could post the code but too long. It may actually work if I use critical p-values below 10^-4, I'm trying to work out a good critical value. Unsure why they are so low though. I'm using ```which.min(1 - pchisq(stats, df = length(coef(fit)))```
Comment: @javlacalle Thank you for the references. I will read them and consider the moving window. Also thanks for replying because I know this post is very old. You have helped me a lot.
Comment: @javlacalle. Thanks four your great answer.  I am stuck with , at F-test, there seems some negative values. How can this be possible?
Answer: I have blogged about detecting structural break using the strucchange package in R. It is pretty straight forward - here's the outline:
# assuming you have a 'ts' object in R

# 1. install package 'strucchange'
# 2. Then write down this code:

library(strucchange)

# store the breakdates
bp_ts <- breakpoints(ts)

# this will give you the break dates and their confidence intervals
summary(bp_ts)

# store the confidence intervals
ci_ts <- confint(bp_ts)

## to plot the breakpoints with confidence intervals
plot(ts)
lines(bp_ts)
lines(ci_ts)

The time series data used in my blog happens to be an ARIMA(0,1,1) process. If you want to verify that, check my Github repo regarding the same.
Comment: @Repmat I'll surely improve my answer in a while, with more details on the method, the motivation and how it works.
Comment: Your blog post seems neat, however we prefer if the answers on this site are self contained. You could improve your answer be adding a bit about the method (how, and why it works for example).
Answer: If you want to check the existence of structure breaks, I would recommend you to:

Make outliers analysis, with the package tsoutliers. By using the function tso, you can check if your model has an isolated spike (additive outlier), an abrupt change in the mean level (level shift), a spike that takes a few periods to disappear (transient change) or a shock in the innovations of the model (intervention outlier).

Analyse the stability of parameters through the QLR test (see critical values in Andrews, 2006). This test is most appropriate when:
i) the break date is unknown,
ii) the lagged variable is an explanatory variable e/or
iii) the errors are heteroscedatic / autocorrelated.

To run this test, you have to add dummies to your model and make loop, in which regressions are calculated several times and the value of the dummies is changed over the time in order to capture possible breaks.
#Define the window to be tested. In general, the first and last 15% observations are excluded
window_breaks <- seq(inic_anomes, last_anomes, 1/12)

# Loop to run the regressions and compute the test statistic
for(i in 1:length(window_breaks)) {

  # Set up dummy variable
  D <- time(y) > window_breaks[i]

  # Estimate model with dummy
  model <- lm(y ~ x + D + D*x)

  # Compute and save the F-statistic
  Fstats[i] <- linearHypothesis(model,
                                c("D", "x:D"),
                                vcov = kernHAC)$F[2]
}

QLR <- max(Fstats) #if QLR < critical value, there is no break

strucchange package on ARIMA model


Can we pass object like textbox to a function?

Question: I wanna ask about winforms.
Is it possible to pass object like TextBox to a function that we can call it "Checker Validation" ?
because I'm too lazy check 1 by 1 on every textbox so I'm curious about how to check it with a function
public void checker(object)
{
    if(Object.Text == ""){ Object.BackColor = Color.Red;}
    else{Object.BackColor = Color.White;}

}
public void textbox_TextChanged(object sender,EventArgs e)
{
     checker(object);
}

i have no idea to input the object textbox on a function @.@
Comment: You might want to look into whether there are already validation systems available that you can make use of, rather than writing one yourself (which here, seems to be about mandatory inputs)
Answer: You can do
public void checker(TextBox txtBox)
{
   if(textbox == null)
   {
      return;
    }

    if(txtBox.Text == "")
    {
       txtBox.BackColor = Color.Red;
    }
    else
    {
      txtBox.BackColor = Color.White;
    }

}
public void textbox_TextChanged(object sender,EventArgs e)
{
     checker(sender as TextBox);
}

Comment: Though we were both correct, props to Mohit for the really through answer!
Comment: so sender is a object which contain value on form? @.@ and btw thanks for your answer ! it's work on me
Answer: Yes.. basically just make the param to your function a textbox...
private void Checktext(textbox mytext)
{
    if (mytext.Text=="whatever")
    { }
    else
    { }
}

Thats psudo code off top of my head, but it will get you there.


Evento JQuery no primeiro input executa em todos os outros

Question:
Olá, estou com um problema com inputs, vejam o código abaixo:

// fixar descrição do campo
var campo = $('.campo-formulario');
var descricao = $('.descricao-campo');

campo.on('input',function(){
   if(campo.val().length > 0){
       descricao.addClass('descricao-fixa');
   } else{
       descricao.removeClass('descricao-fixa');
   }
});

Ele trava a label do meu input quando tem algo digitado nele, e até funciona quando estou com apenas um input, mas quando tenho mais de um começa o problema.
Quando eu ativo o primeiro input e digito alguma coisa, o script executa em todos os outros campos, quando ele deveria funcionar só no primeiro.
Outra coisa que acontece, é que o script só ativa quando eu digito no primeiro campo, se eu digitar em qualquer outro, ele não funciona.
O que eu preciso exatamente é que só a label do input que eu digitei fixasse quando eu digitasse algo, por exemplo:

digitei no input 1, a label subiu e fixou
Label do input 2, 3, 4... continua embaixo.

Já procurei em tudo mas não consigo achar uma solução, me ajudem por favor, isso é meu projeto final de um curso de informática.
Segue o HTML e CSS:

input {
outline: none;
width: 100%;
border: 1px solid #ccc;
height: 40px;
padding: 0 15px;
font-family: 'Texto';
color: #222;
font-size: 105%;
background: none;
}

.container-campo {
width: 49%;
position: relative;
}

.descricao-campo {
position: absolute;
left: 15px;
top: 7px;
transition: all .2s;
cursor: text;
}

.descricao-fixa {
top: -10px;
left: 8px;
transition: all .2s;
z-index: 3;
background: #fff;
padding: 0 5px;
font-size: 80%;
font-weight: bold;
}

input:focus ~ .descricao-campo {
top: -10px;
left: 8px;
transition: all .2s;
z-index: 3;
background: #fff;
padding: 0 5px;
font-size: 80%;
color: dodgerblue;
font-weight: bold;
}

input:focus {
border: 1.5px solid dodgerblue;
}

.campos-dados-produto {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}

.dados-produto {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}

    <input type="text" name="codigo" class="campo-formulario" id="codigo" required>
    Código

    <input type="text" name="descricao" class="campo-formulario" id="descricao" required>
    dsdds

Answer: Esse seletor $('.descricao-campo'); se applica nos seus 2 campos. Quando voce faz isso na sua funcao descricao.addClass('descricao-fixa'); o que acontece e que voce esta manipulando todos os elementos com a classe .descricao-campo, por isso afeta os 2 campos ao mesmo tempo.
Um jeito de isolar o campo é encontrar seu label a partir do elemento pai, no caso o .container-campo.
Importante notar o $(this) ele aponta para o elemento atual o .parent() vai apontar para o .container-campo logo acima, e por fim o find('.descricao-campo') vai esta apontado para o 1 unico elemento.
Segue um trecho funcional de tudo isso junto.

// fixar descrição do campo
var campo = $('.campo-formulario');
var descricao = $('.descricao-campo');

campo.on('input',function(){
    var descricaoAtual = $(this).parent().find('.descricao-campo');
   if($(this).val().length > 0){
       descricaoAtual.addClass('descricao-fixa');
   } else{
       descricaoAtual.removeClass('descricao-fixa');
   }
});
input {
outline: none;
width: 100%;
border: 1px solid #ccc;
height: 40px;
padding: 0 15px;
font-family: 'Texto';
color: #222;
font-size: 105%;
background: none;
}

.container-campo {
width: 49%;
position: relative;
}

.descricao-campo {
position: absolute;
left: 15px;
top: 7px;
transition: all .2s;
cursor: text;
}

.descricao-fixa {
top: -10px;
left: 8px;
transition: all .2s;
z-index: 3;
background: #fff;
padding: 0 5px;
font-size: 80%;
font-weight: bold;
}

input:focus ~ .descricao-campo {
top: -10px;
left: 8px;
transition: all .2s;
z-index: 3;
background: #fff;
padding: 0 5px;
font-size: 80%;
color: dodgerblue;
font-weight: bold;
}

input:focus {
border: 1.5px solid dodgerblue;
}

.campos-dados-produto {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}

.dados-produto {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}

    <input type="text" name="codigo" class="campo-formulario" id="codigo" required>
    Código

    <input type="text" name="descricao" class="campo-formulario" id="descricao" required>
    dsdds

Comment: essa sim funcionou corretamente! porém só tem um problema. tenho um input com mascara e a função não está se aplicando nesse campo, teria como arrumar?
Answer: Você pode usar o $(this).next(); para pegar o próximo elemento

// fixar descrição do campo
var campo = $('.campo-formulario');

campo.on('input',function(){
    var descricao = $(this).next();

   if(campo.val().length > 0){
       descricao.addClass('descricao-fixa');
   } else{
       descricao.removeClass('descricao-fixa');
   }
});
input {
outline: none;
width: 100%;
border: 1px solid #ccc;
height: 40px;
padding: 0 15px;
font-family: 'Texto';
color: #222;
font-size: 105%;
background: none;
}

.container-campo {
width: 49%;
position: relative;
}

.descricao-campo {
position: absolute;
left: 15px;
top: 7px;
transition: all .2s;
cursor: text;
}

.descricao-fixa {
top: -10px;
left: 8px;
transition: all .2s;
z-index: 3;
background: #fff;
padding: 0 5px;
font-size: 80%;
font-weight: bold;
}

input:focus ~ .descricao-campo {
top: -10px;
left: 8px;
transition: all .2s;
z-index: 3;
background: #fff;
padding: 0 5px;
font-size: 80%;
color: dodgerblue;
font-weight: bold;
}

input:focus {
border: 1.5px solid dodgerblue;
}

.campos-dados-produto {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}

.dados-produto {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}

    <input type="text" name="codigo" class="campo-formulario" id="codigo" required>
    Código

    <input type="text" name="descricao" class="campo-formulario" id="descricao" required>
    dsdds


Making beaver builder module settings chose able?

Question: I am developing a beaver builder extension and every thing is working fine, but the issue is that I want to give some select able options to client so that he/she can choose their respective options and we can provide functionality as per their selection.
For Example, I want to give 2 options. Option one, select your post type ? Options are "post", "custom post" ... now if he/she selects "post" i want to show some options only post relevant but if he/she selects "custom post" I want to show options related to custom post. I did this thing in visual composer but unable to do in beaver builder so far.
Here is some of mine code:
<code>'sections'      => array( // Tab Sections
        'general'       => array( // Section
            'title'         => __('Section Title', 'fl-builder'), // Section Title
            'fields'        => array( // Section Fields
                'select_field'   => array(
                    'type'          => 'select',
                    'label'         => __('Show Filter or Not?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
                'no_of_posts' => array(
                    'type'          => 'my-custom-field',
                    'label'         => __('Provide your desired number of Posts', 'fl-builder'),
                    'default'       => '8'
                ),
                'no_of_cols' => array(
                    'type'          => 'select',
                    'label'         => __('Provide your desired number of Cols', 'fl-builder'),
                    'default'       => 'option-2',
                    'options'       => array(
                        'option-1'      => __('2', 'fl-builder'),
                        'option-2'      => __('3', 'fl-builder'),
                        'option-3'      => __('4', 'fl-builder'),
                        'option-4'      => __('6', 'fl-builder')
                    )
                ),
                'show_overlay' => array(
                    'type'          => 'select',
                    'label'         => __('Do You Want to Show Overlay?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
                'show_lightbox' => array(
                    'type'          => 'select',
                    'label'         => __('Do You Want to Open Image in lightbox?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
                'show_lightbox_link' => array(
                    'type'          => 'select',
                    'label'         => __('Do You Want to show Link Icon in Lightbox?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
                'show_title' => array(
                    'type'          => 'select',
                    'label'         => __('Do You Want to show Post Title?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
                'show_title_link' => array(
                    'type'          => 'select',
                    'label'         => __('Do You Want to use Link in Post Title?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
                'show_content' => array(
                    'type'          => 'select',
                    'label'         => __('Do You Want to show Post Content?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
                'show_link' => array(
                    'type'          => 'select',
                    'label'         => __('Do You Want to show Post Link?', 'fl-builder'),
                    'default'       => 'option-1',
                    'options'       => array(
                        'option-1'      => __('Yes', 'fl-builder'),
                        'option-2'      => __('No', 'fl-builder')
                    )
                ),
</code>
The point is again simple: I want to show my options only when some other relevant option is selected.
For example, if user selects option "post" then this should be done
<code>'no_of_cols' => array(
                'type'          => 'select',
                'label'         => __('Provide your desired number of Cols', 'fl-builder'),
                'default'       => 'option-2',
                'options'       => array(
                    'option-1'      => __('2', 'fl-builder'),
                    'option-2'      => __('3', 'fl-builder'),
                    'option-3'      => __('4', 'fl-builder'),
                    'option-4'      => __('6', 'fl-builder')
                )
            ),
</code>
Means I want to show options for selection only if post is selected etc. Hope I conveyed my problem clearly.
Answer: I'm perhaps too late for this!
But you simply need to use 'toggle'.
<code>'select_field'   => array(
  'type'          => 'select',
  'label'         => __('Show Filter or Not?', 'fl-builder'),
  'default'       => 'option-1',
  'options'       => array(
    'option-1'      => __('Yes', 'fl-builder'),
    'option-2'      => __('No', 'fl-builder')
  ),
  'toggle' => array(
    'option-1' = array(
      'fields' => array('another_field')
    )
  )
),
'another_field' => array()
</code>


The group $\mathbb{Q}$ of rationals can't be finitely generated - correct proof?

Question: I am trying to prove that the group $\mathbb{Q}$ of rationals can't be finitely generated. Please judge my proof. Is it too informal?

The order of the group $\mathbb{Q}$ is $\aleph_0$, and so it is infinite. Suppose, however, that it still can be generated somehow from a finite group $G$, whose cardinality is $k$. Then
$$\left<G\right>=\{a_1^{e_1}*...*a_m^{e_m}\left.\right|\,a_i\in G, e_i=\pm 1, \,\, 1\leq m \leq k\}$$
But we have taken combinatorics before, and we know that this situation can be reformulated as the following illustration depicts.

As the illustration suggests, we know that the number of elements in $\left<G\right>$ is simply $3^k-1$, which is finite (i.e. less than $\aleph_0$). Contradiction.

EDIT: I think I may have pinpointed my misconception about generations of subgroups. I was under the impression that each element in a finitely-generated group had to be the product of a finite number of distinct elements in the group from which it is being generated from with no repeating elements or an element and its inverse. Basically, I thought $a^2$ couldn't be in there.
Comment: I don't understand what you're trying to say at all. It's certainly not true that finitely generated subgroups of $\Bbb Q$ are finite.
Comment: Your illustration does not suggest *me* absolutely anything, I am afraid.
Comment: @MikeMiller could you expand on that?
Comment: Your mistake is in thinking that finitely generated means generated by a finite group (which makes no sense). By your argument the integers would not be finitely generated.
Comment: "A group is called *finitely generated* if it can be generated by a finite number of elements." That's exactly what my book says. Where in my faulty proof do I stray from this definition?
Answer: Your proof is false, because you assume that $e_i=\pm 1$ and that none of the $a_i$ are repeating in more than one block. This is not true in general, for instance you are allowed to have elements like $a_1^2a_2a_1a_3^3$ in the group. Also for an abelian group like $\mathbb{Q}$, it is better to think of the group operation as addition, rather than multiplication.
Moreover, your method of proof will not work because most finitely generated subgroups of $\mathbb{Q}$ do in fact have the same cardinality as $\mathbb{Q}$! So a simple cardinality argument will not do.
I would suggest the following method, based on the infinitude of primes. If you fix a finite set of rationals, $S$, then there will be a large prime $P$ bigger than all prime factors appearing in elements of $S$. Then one may show that $1/P$ is not in the subgroup generated by $S$, contradiction.
Comment: Ok I see what you mean by "...you assume... that none of the $a_i$ are repeating in more than one block." I did assume that because the definition my book gave me made it seem that that was the case.


Grouping data based on a specific pattern

Question: I have a collection of data for a multiplayer game (2000 games, 10 players each). I would like to create clusters from this data, each containing the ids of 3 players that had played against each other. For example, assume player A played against player B, B played against C, and C played against A. I'm trying to figure out a way to detect A,B, and C from the data. I was thinking of using kmeans but this may not work as i do not know the number of clusters. Please help
Comment: What's the question?
Comment: How do i create groups/clusters representing 3 players that had all played against each other from the data
Comment: The data includes columns for match id, player id, team id, and Boolean for result
Comment: There is a lot of confusion in the question but it does not seem to be so unclear as to be unanswerable - even if the answer is not at all to do with clustering - so I don't think the question should be closed as unclear
Comment: What are you hoping for if A played against B, A against B, A against C, A against D, B against C, B against D, c against D? Or some variants of that?
Comment: Detecting a non transitive relation
Comment: This doesn't seem to be a statistics question.  Certainly not a clustering one.  I think it should be moved to StackOverflow.
Comment: @Silverfish How can you answer a question when no question is asked?
Comment: @Firebug It struck me that Anony-Mousse had penetrated the underlying confusion here - the OP seems mixed up between cliques and clusters. As it's a statistical misunderstanding I think it's at least arguable that it has a place here though I wouldn't argue against the consensus decision. (I felt the question was rather implicit.)
Comment: I apologize for the confusion in my question. I was not aware of cliques, the question i posted is part of a project i am working on for a data science course. I replied to Anony-Mousse's answer an update to what i have reached so far.
Answer: You appear to be looking for 3-Cliques, not for clusters.
Unless you are also looking for larger cliques, you likely won't find an "algorithm" for this, because it is straightforward.
<code>For any node A:
  For any neighbors B < C of A:
    If A < B and B and C are connected:
      report ABC as 3-clique
</code>
Clustering algorithms try to solve a different problem, so they won't be useful to you.
Comment: Thank you for your reply. I researched cliques and understood that they are detected from graphs. I can use networkx to solve this in python. I read the documentation on networkx, but have not successfully managed to go about it. Do you know where i can find a good tutorial for solving this? I'm currently stuck in building a graph representation from the dataframe. My data columns are gameId, players ids under each team, and the outcome of the game for each team.


Test for Statistical Significance in the Accuracy of a Machine Learning System

Question: I have what I imagine is an elementary question about evaluating statistical significance, but while I know a lot about probability I can't t-test my way out of a paper bag. From here I'm hoping to get a pointer to where I should look for the answer.
I have a machine learning system and a test set of N questions. I run the test and the system gets r questions right and w questions wrong where r + w = N. I measure the performance of my system with its accuracy, which I define to be r/N.
I make a change to my machine learning system and rerun the same test. Now I get a different accuracy. Is is possible to ask whether or not the change in accuracy is statistically significant?
I suppose the null hypothesis is that the change in accuracy is just due to chance. The system is deterministic, so in theory there is no chance involved. However, certain questions will be hard ones that lie on its decision boundary, making them so sensitive to the system's configuration their correctness is essentially random.
Is it meaningful to talk about statistical significance in this instance? If so, what test should I use?

Following up on the cross-validation suggestions in the comments below, would the following work?
I have a test data set of size N. It is divided into M disjoint partitions. To test my system, I calculate its accuracy on each of the M partitions. Then I can take the mean and standard deviation of this accuracy.
To compare the performance of two systems, I run them both on the same set of M partitions, and then see if the difference between the mean accuracies is statistically significant. Would I use Welch's Test for this?
Here the "randomness" in the accuracies arises from overfitting.
Comment: doesn't this depend on how you determine accuracy? If you're using your training set to determine accuracy this is an issue. Similarly with split sample. But if you're using some form of cross-validation you might well obtain a distribution of OOB estimates from which to generate some sense of the reliability of estimate. (The key being that the training set accuracy is deterministic, but you're interested in the OOB accuracy that can only be estimated.)
Comment: Usual data hygiene rules apply. The training and evaluation sets are separate. I have enough data so that I can have a dedicated evaluation set instead of doing cross-validation.
Comment: Or are you saying that if I randomly chose multiple evaluation sets (e.g. via cross validation) I could get a distribution over accuracy numbers which I could then compare with a different distribution using standard techniques?
Comment: I might misunderstand. Sorry. But the type of graph/output you want might be (http://www.stanford.edu/~hastie/local.ftp/Springer/OLD/ESLII_print4.pdf) page 244, 314, 378,... I believe Hastie et al have even popularized a "one-standard deviation" (?) rule of thumb such that CV values within 1-SD are not considered different. How you practically obtain this information from CV I have no idea.
Comment: If you have a test set (rather than use CV of some sort), I have not idea. Since you'll just obtain a point estimate without any sort of idea of the distribution. (My assumption, but would be interested if someone knows more, is that this is part of the popularity of CV. Usually these researches have datasets that are large enough that split sampling could reasonably be used if they wanted to)
Answer: You should look in to Area Under the ROC Curve as a method.  You can use that as a metric for how well each method separates the datasets.


Dynamically filling up fields of a node in Drupal

Question: We have a content type named "Person", which has fields as Full Name, Age, Address etc.
There are thousands of people entries on the site. We are using Views to sort out people's list on different pages as per need.
Lately, there has been a requirement that we need to sort the list of people by Last Name. But the problem is that there's no last name field as there's only "Full Name" field of the person in the site.
I am using views to sort the results in the pages and I am not sure how to sort the results by last name. Is there any way I can achieve this?
May be I can create a field as "Last Name" in the content field but is there a way I can dynamically fill in the Last Name by extracting Last word from Full Name?
May be through someway in SQL?
Any idea or assistance would be highly appreciated.
Thanks.
Comment: Try this

`ALTER TABLE `tbl_name`
    ADD LastName AS
        RIGHT(FullName, CHARINDEX(' ', REVERSE(FullName)) - 1) PERSISTED`
Answer: Here is my way of doing it:

Create a Computed Field to manipulate the substring (Last Name) and store it as a field

Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code.

Use Computed Field Tools to bulk update the value for the existing nodes

The Computed Field module only updates its computed values on saves or
  on load (if no computed value is computed yet). This is not optimal
  when using computed values in lists etc., or if you should wish to
  change the logic in the computed field.

Use this Computed Field as a sort criteria in Views.
Answer: You can create a user defined function for this

MySQL Split String Function

With that function, you would be able to build your query as follows:
SELECT SPLIT_STR(fullname, ' ', 1) as fullfirst,
       SPLIT_STR(fullname, ' ', 2) as fulllast
FROM   users;

You can also do the following:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) as fullfirst,
       SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1) as fulllast
FROM   users;

Comment: Most welcome @user219492


Convolution is communicative from 2 view

Question: Assume convolution between $f(x)$ and $g(x)$. $f(x)*g(x)=\int_{\infty}^{\infty}f(\tau)g(t-\tau)d_{\tau}$. We know that convolution is communicative, to prove this property, we can change the variable $\tau'=t-\tau$, so $f(x)*g(x) = -\int_{\infty}^{\infty}f(t-\tau')g(\tau')d_{\tau'}$ and to remove minus we change the bounds of integral, but if we define the variable as $\tau' = \tau-t$ , the convolution would be $f(x)*g(x) = \int_{\infty}^{\infty}f(\tau'+t)g(-\tau')d_{\tau'}$, is there any way to prove that the first way and the second one are the same?
Comment: Should we surmise that where you wrote "communicative" you meant "commutative"?
Answer: By the change of variable $\tau=-\tau'$, $d\tau'=-d\tau$, one gets
$$
 \int_{-\infty}^{\infty}f(\tau'+t)g(-\tau')\:d{\tau'}=\int_{\infty}^{-\infty}f(-\tau+t)g(\tau)\:(-d{\tau})=\int_{-\infty}^{\infty}f(t-\tau)g(\tau)\:d{\tau}
$$ which is your first expression.
Comment: But I want the solution without changing the bounds of integral, is there any?
Comment: @user137927 Please, in your question above the bounds are the same, is there a typo?
Comment: I want to interpret the second approach in a way that we interpret the convolution (that we flip the $f$ and move it through $g$)


What does the surface |z₁|² = |z₂|² look like?

Question: In a quaternionic plane there are 2 axes and each point corresponds to $q \in \mathbb C^2$. Now, $|z_1|^2 = |z_2|^2$ should define a surface that divides a 3-sphere $|z_1|^2 + |z_2|^2 = 1$ into two pieces, where $z_1, z_2 \in \mathbb C$. What does this surface look like? Describe the two pieces.

We know that a point say $q \in \mathbb C^2$ defines a circle, and in the special case where $q \in S^3$ then it should be a fiber in Hopf fibration.
We also know that the intersection of $|z_1|^2 = |z_2|^2$ and $|z_1|^2 + |z_2|^2 = 1$ consists of 4 unit quaternions, which under stereographic projection also defines the 16 vertices of a 4-cube in $\mathbb R^3$.
It is too difficult for me to see how the surface $|z_1|^2 = |z_2|^2$ cuts an $S^3$ into 2 parts, if anything it should cut it into 4 parts, (referring to the quaternionic plane where $S^3$ is represented as a circle.)
Reference: Zachary Treisman (2009) exercise 2.23. arXiv:0908.1205 [math.HO]
Comment: How do you think $q\in\Bbb C^2$ defines a circle? Are you talking about the Hopf fiber that contains a particular quaternion $q\in S^3$?
Answer: A number of misconceptions:

The intersection of $|z_1|^2=|z_2|^2$ and $|z_1|^2+|z_2|^2=1$ is not just four quaternions, it's an entire $2$-torus worth of quaternions, defined by $|z_1|=1/\sqrt{2}$ and $|z_2|=1/\sqrt{2}$.
Stereographic projection turns four points into four points, not sixteen.
The $4$-cube resides in $\mathbb{R}^4$, not $\mathbb{R}^3$. (Unless you're talking about a projection of it, which is typical of depictions of the tesseract.)
Four points would not cut $S^3$ into four pieces, any more than three would cut $S^2$ into three; the sphere will remain connected no matter how (finitely) many points you delete.

The two pieces $S^1\times S^1$ separates $S^3$ into are defined by $|z_1|<|z_2|$ and $|z_1|>|z_2|$. Can you figure out what these two $3$-dimensional shapes these are?
Comment: These two 3-dimensional shapes should be a pair of solid tori that are linked together. https://youtu.be/KC25GKKaqdM
Comment: I don't see how the 600-cell is relevant but yes a pair of solid tori.
Comment: Implemented a filter using |z_1| < |z_2| and |z_1| > |z_2| to divide a 600-cell into two pieces. Since the 600-cell is inscribed inside a 3-sphere, its 120 vertices are also in S³, and they are either in the first shape or in the second one. I thought that the visual model could help with the intuition, as the two solid tori are visualized with roughly the same shape. It's only an efficient approximation of what an S³ would look like under stereographic projection.


scrollLeft javaScript horizontal scroll issue

Question: Well I have a horizontal website that scrolls left.
I'm trying to get the navigation which is fixed to the top to scroll horizontally to each nav ID's anchor tag.
Here's the JSFiddle for the file.
The code snippet is as follows:

$(document).ready(function(){

    $('.scrollPage').click(function() {
        var anchor = String($(this).attr("href")).replace("#","");
        var selector = 'div[name="' + anchor + '"]';
        var e = $(selector);
        var left = e.offset().left;
       $('html, body').animate({scrollLeft: left }, 800);
       return false;
    });
});

body {
    background:url(images/fill.jpg) #74beb2 repeat scroll;
    font-size: 12px;
    margin-top:0;
    min-width:1140px;
    overflow: scroll;
    padding-top:0;
    height:768px;
}

#container {
    height:768px;
    width:17000px;
    float:left;
    position:relative;
}

nav {
    background:url(images/nav.png) no-repeat;
    height:80px;
    width:977px;
    position:fixed;
    margin-left:67px;
    margin-top:10px;
    z-index:100;
}

.navtype {
    width:845px;
    height:27px;
    margin-left:130px;
    margin-top:35px;
}

/*NAV*/

/*-------------------------------------------------*/

/*SECTIONING*/

#sectionone {
    background:url(images/sectionone.jpg) no-repeat scroll;
    height:768px;
    width:1140px;
    float:left;
}

#sectiontwo {
    background:url(images/sectiontwo.jpg) no-repeat scroll;
    height:768px;
    width:622px;
    float:left;
}

#sectionthree {
    background:url(images/sectionthree.jpg) no-repeat scroll;
    height:768px;
    width:1140px;
    float:left;
}

#sectionfour {
    background:url(images/sectionfour.jpg) no-repeat scroll;
    width:1238px;
    height:768px;
    float:left;
}

ABOUT

FILMS

CONTACT

LODGING

TICKETS

About

The Stay Gold Movie Festival in Brooklyn, New York prides itself on bringing not only the classics when it comes to youth in revolt films, but also the spirit of the New York City life experience. The Films of The Wanderers, The Warriors, and The Outsiders are instant hits showing the comradery and friendship anyone would enjoy, not to mention the introduction of the good old "one-two" punch when it comes to taking out the pretty boys from the burbs. All in all if you want a heartfelt journey, filled with action, suspense, and good old greaer gang attitude, Stay Gold is the best for you.

Comment: "Something's wrong." I love the details!
Comment: Can you include more code (perhaps a jsfiddle)? It is hard to understand exactly what you are trying to do with your selectors.
Comment: You code looks good. What happens when you execute this? Any error?
Answer: I don't think you are handling the anchor correctly. Your selector is just putting in the href of the  and I don't think that works with jQuery. I put together a sample jsfiddle that does work, but I strip the # and use the div[name="anchor"] selector.
http://jsfiddle.net/pseudosavant/C9JSx/
Answer: Also, you might wanna use a single tag so the action won't get caught/executed by both tags (html and body).


Função customizada para a função sorted em python 3.x

Question: Em python 2.x eu consigo passar uma função customizada para função sorted, como fazer isso em python 3.x?
Basicamente converter o código abaixo
def numeric_compare(x, y):
    return x - y

print(sorted([5, 2, 4, 1, 3], cmp=numeric_compare) )

Answer: Utilize o método cmp_to_key da biblioteca functools
Ficará desta forma:
import functools
def numeric_compare(x, y):
    return x - y

print(sorted([5, 2, 4, 1, 3], key=functools.cmp_to_key(numeric_compare)))

Comment: vlw bro! so corrige o import q ta faltando um s
Comment: Corrigido, que bom que resolveu.


Faça uma função que retorne a média das notas que pessoa participa em R

Question:
Como eu posso fazer uma função que retorne a  média das notas de MARIA
meu código está assim:
PESSOA = (got$Personagens)
NOTAS = (got$Nota)

medianotas = function(tabelaNotas, tabelaPessoas, nome)
    Nota = c()
    arrayPessoas = c()

    for(i in 1:length(tabelaPessoas))
        arrayPessoas = c(arrayPessoas, PESSOA[i])
        arraySplit = c(unlist(strsplit(as.character(arrayPessoas,","))))

    return()

resposta = medianotas(got$Nota, got$Personagens, "MARIA")
print(resposta)

Após cada nome tem uma vírgula
Dados.
Notas <- c(9, 8.1, 7)
Personagens <- c("João,Maria,Eduardo",
             "Pedro,Carlos,Maria",
             "Bruno,Patrícia,Joana")
got <- data.frame(Notas, Personagens)

Answer: A seguinte função faz o que a pergunta pede. Não são necessários ciclos for, é tudo vetorizado. O trabalho principal é dividir a coluna "Personagens" pelas vírgulas e depois usar a função lengths para obter os comprimentos de cada vetor correspondente aos nomes já separados.
medianota <- function(DF, Pessoa){
  s <- strsplit(as.character(DF[["Personagens"]]), ',')
  dftmp <- data.frame(Personagens = trimws(unlist(s)),
                      Notas = rep(DF[["Notas"]], lengths(s)))
  inx <- tolower(dftmp[["Personagens"]]) == tolower(Pessoa)
  NotasPessoa <- dftmp[["Notas"]][inx]
  mean(NotasPessoa)
}

medianota(got, "Maria")
#[1] 8.55

Dados.
Notas <- c(9, 8.1, 7)
Personagens <- c("João, Maria, Eduardo",
             "Pedro, Carlos, Maria",
             "Bruno, Patrícia, Joana")
got <- data.frame(Notas, Personagens)


No of right angled triangles

Question: How many right angled triangles are possible with the perpendicular side equal to 36 units. I took the side $x$ and $y$ and using Pythagoras theorem you have $(x+y)(x-y) = 1296$ and $1296$ has $25$ factors. What next?
Comment: I think we wants the ones with integer side lengths
Comment: Do you want the sides to have integer lengths?  It's not clear from your question, so I'm voting to close as unclear what is being asked.
Comment: I think what you are asking for are the triples where one or the other leg is $36$ units long. Those are $f(10,8)=(36,160,164)$ and $f(9,2)=(77,36,85)$
Comment: If you want to match any sides [this answer](https://math.stackexchange.com/questions/1590629/how-to-find-all-pythagorean-triples-containing-a-given-number/3272945#3272945) will show you how.
Answer: We will count the integer-sided triangles. I would rather call the hypotenuse $z$ and the other leg $y$, so we want $(z-y)(z+y)=36^2$. But $z-y$ and $z+y$ must both be even, else $z$ and $y$ would not be integers.  So $z+y=2\alpha$ and $z-y=2\beta$, where $\alpha$ and $\beta$ are integers and $\alpha\gt\beta$ and $\alpha\beta=18^2$.
Now $18^2=2^2\cdot 3^4$, so $18^2$ has $15$ factors $\alpha$. One of them, $18$, gives $\beta=18$, so must be discarded. Exactly half of the remaining factors give $\alpha\lt\beta$. So there are $7$ Pythagorean triangles with one leg equal to $36$.

No of right angled triangles


How can I fix an "Access Denied" error on image styles, despite the correct filesystem permissions being set?

Question: On a Drupal 8 site, image styles are no longer generating correctly.
The sample.png used in the image styles configuration page is generated fine (including when I manually delete the file from the image styles directory). I have recursively set to 0775 and 0664 the directory and file permissions for the entire sites/default/files directory, but the error persists. The log just shows access denied.
The Drupal version is 8.1.9.
How can I fix this error?
Comment: I would also check owner and group for sites/default/files.
Comment: Just checked - all owned by the main web-server user / FTP user. This includes all subfolders and files in /sites/default/files/styles/...
Answer: I have had issues in the past where derivatives weren't generating correctly intermittently and it was due to disc space running out.  When logs were purged the image derivatives would generate, but otherwise, the server was running out of space.  So that's one idea.
Comment: Thanks for suggestion - hope it helps others. Sadly, we have plenty of space and it's still failing.
Answer: I have at last worked out what is causing the issue - but not why it suddenly started happening.
Going through our hosting cPanel, I stumbled across xVarnish, which is enabled across the board. Disabling it on our website immediately made the image styles generate correctly.
It may be that I can configure it to ignore image styles (thoughts welcome!) but for now, I have so much caching enabled Drupal-side that I think I can do without Varnish.
However, unless someone has suddenly turned on Varnish without consulting me (unlikely, but hard to ascertain in my org) then I'm totally at sea as to why it suddenly started being a problem.
Answer: Sometimes this problem can be caused by wrong or absent of the image token. Try to insert config line in the settings.php to check:
<code>$config['image.settings'] = ['allow_insecure_derivatives' => true];
</code>
If after this change your picture style is showing correctly, your picture URL has wrong parameter "itok", for example:
<code>/sites/default/files/styles/your_style_name/public/post-images/2021-07/photo_2021-06.webp?itok=0I_xdyI7
</code>


Finding the eigenvalues when $c$ is unknown

Question: Given that $$A=\begin{bmatrix} \ 0 & 1 & 0 \\-c & c+1 & 0 \\1 & 1 &-1\end{bmatrix},$$
determine the eigenvalues of $A$.
I have found that  $\lambda^3-c\lambda^2-\lambda-c=0 $. How can I continue from here?
Comment: …hmm…have you noticed that (1,1,1) is an eigenvector? Now you should be able to find an eigenvalue, and then you can factor the characteristic polynomial, and then factor the resulting quadratic in the usual manner…(I found the eigenvector just by staring at the matrix and guessing a little, in case this seems like magic)
Comment: A general way that can be used to find the eigenvalues of a square matrix is to use elementary row (column) operations on it to transform it into a triangular matrix and then the elements on the principal diagonal will be the eigenvalues. This works because similar matrices preserve eigenvalues and eigenvalues of a triangular matrix are its diagonal elements.
Comment: nope i did not notice that , it seem like i am still unfamiliar with eigenvector & eigenvalue.. still in the mid of learning :P  currently doing textbook question
Answer: Expanding the characteristic polynomial along the last column:
$$
\det(\lambda I-A_c)=
\det\begin{bmatrix}
\lambda & -1 & 0 \\
c & \lambda - c - 1 & 0 \\
-1 & -1 & \lambda + 1
\end{bmatrix}=
(\lambda+1)\det\begin{bmatrix}
\lambda & -1 \\
c & \lambda - c - 1 \\
\end{bmatrix}
$$
Now
$$
\det\begin{bmatrix}
\lambda & -1 \\
c & \lambda - c - 1 \\
\end{bmatrix}=
\lambda^2-(c+1)\lambda+c=
(\lambda-c)(\lambda-1)
$$
so we finally get
$$
\det(\lambda I-A_c)=(\lambda+1)(\lambda-c)(\lambda-1)
$$
The long version is
$$
\det(\lambda I-A_c)=\lambda^3-c\lambda^2-\lambda+c
$$
and you have a wrong constant term.
I don't know where your mistake was; if you used Sarrus' rule, be careful with it: expanding with respect to a row or column that only has a nonzero coefficient is better.
Answer: You have the wrong characteristic polynomial.
\begin{align}\det(A-\lambda I) & =-(\lambda(\lambda-c-1)+c)(\lambda+1)=-(\lambda^2-(c+1)\lambda+c)(\lambda+1)\\ &= -(\lambda-c)(\lambda-1)(\lambda+1).\end{align}
Alternatively : as pointed out in the comments, $(1,1,1)$ is an eigenvector with eigenvalue $1$ (because the sum of the elemens in every line is $1$), and $(0,0,1)$ is an eigenvector with eigenvalue $-1$. Since $\det A=-c$ is the product of the eigenvalues and $\operatorname{tr}(A)=c$ is their sum, the last eigenvalue must be $c$.
Comment: noted :) i realize that i did wrongly..


Converting an expression to VBA in access

Question: I have created an expression to add 3 textboxes together into a 4th total box. The expression is:
=Cdbl(Nz[txtPart1],0)) + Cdbl(Nz[txtPart2],0)) + Cdbl(Nz[txtPart3],0))

I am trying to convert this into VBA code because the form I have created has so many things running on it thats why the calculation is slow. I want to be able to add an hour glass so the user doesn't think that the program is not working. I tried putting a code that sums the 3 in the after update event of all three textboxes but that did not work. Please help!
I have this code in the AfterUpdate of the 3 textboxes:
me.total = me.txtpPart1 + me.txtPart2 + me.txtPart3

Thanks
Comment: Yes, the "Discover Time" text box will remain empty.  I'm only suggesting you test the impact of disabling the timer.  If it helps, you will need to decide what to do about "Discover Time" later.  If it doesn't help, set it back to 125 and look elsewhere for improvements.
Comment: Excellent!  I think you made the right choice there, BC.  You acknowledged *"the form I have created has so many things running on it thats why the calculation is slow"*.  Updating  "Discover Time" 8 times per second only added to that workload.  And actually, I didn't see why displaying "Discover Time" at all was valuable.  Suggest you look for other opportunities to simplify that form.  Good luck.
Comment: This expression is very fast, so you probably have to look elsewhere for optimization. And it _will_ work if your textboxes contain numerals, so what is your code, please?
Comment: I added the my code I have to the post
Comment: Test with your form's *Timer Interval* property set to 0.  Does that make the "4th total box" more responsive?  It seemed to in my copy of your db.
Comment: HansUp if I change the timer will that make my live clock not work?
Comment: It does help alot I will just have to not have a live clock thanks so much!
Answer: Then you could use:
Me!Total.Value = 0
' Ignore error from non-numeric input.
On Error Resume Next
Me!Total.Value = CDbl(Nz(Me!txtPart1.Value, 0)) + CDbl(Nz(Me!txtPart2.Value, 0)) + CDbl(Nz(Me!txtPart3.Value, 0))

Comment: Ok so I should put this in the afterupdate of each of the three textboxes?
Comment: No. You would save it in a function called, say, `UpdateTotal` and then call this function from the three `AfterUpdate` events.


Setting up shared common Pods for multiple targets within projects

Question: I am trying to install Pod using  abstract_target to share common Pods for multiple target. I am follow CocoaPods to install Pods. But it generates following error.
[!] Invalid `Podfile` file: undefined method `abstract_target' for #<Pod::Podfile:0x007fcd7380d098>. Updating CocoaPods might fix the issue.

 #  from /Users/Sagar/Desktop/CocoaPodsMultipleTarget/Podfile:5
 #  -------------------------------------------
 #
 >  abstract_target "Networking" do
 #
 #  -------------------------------------------

I updated my CocoaPods and my current version is :
/Users/Sagar/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/cocoapods-1.0.0.beta.2/lib/cocoapods.rb

Below is my Podfile.
# Uncomment this line if you're using Swift
use_frameworks!

abstract_target 'Networking' do

    pod 'AlamoFire'

    target 'CocoaPodsMultipleTarget' do

    platform :ios, '9.0'

        pod 'IQKeyboardManagerSwift'

    end

    target 'MyWatchDemo Extension' do

    platform :watchos, '2.0'

    end

end

Is there any thing wrong with my Podfile ?
Any help or suggestion should be appreciated.
Comment: I had the same problem; turned out rvm was loading an old version of cocoapods. Imploded rvm and reinstalled, the installed the latest cocoapods 1.0 beta... and it worked! You can check what version is actually being used by `$ which pod` and `$ pod --version`
Comment: As i mentioned in my question, i already installed `cocoapods-1.0.0.beta.2` ,but not working. If you have solution then please post answer.
Answer: Are you sure your version of CocoaPods is 1.0 and not 0.39.0? Using abstract_target only works on 1.0 and above. In your terminal...
Check version:
$ pod --version

Update for the pre-release version:
$ [sudo] gem install cocoapods --pre

For reference: https://guides.cocoapods.org/using/getting-started.html


implementando onClick

Question: Meu problema é o seguinte:
Tenho um Array de string com o nome frases, onde tenho várias frases.
E gostaria de mostra-las todas no mesmo TextView uma a uma cada vez que pressionar o botão "próxima".
Qualquer dica será bem recebida obrigado.
Comment: Seja bem vindo ao Stack Overflow! Para que a comunidade possa te ajudar, é importante que se explique detalhadamente o seu problema, E exiba o que você fez até o momento!

Sugiro que leia os artigos: [Tour](http://pt.stackoverflow.com/tour) e [como realizar uma pergunta](http://pt.stackoverflow.com/help/how-to-ask).    Obrigado!
Answer: Olá !
Segue um exemplo de como deve ficar seu OnCLick:
int ponteiro = 0;
private View.OnClickListener nextAction(){
return  new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // vamos ver se o ponteiro é menor que o tamanho da lista
        // tiramos 1, pois abaixo vamos adicionar mais 1!
        if(ponteiro < (frases.size()-1) ){
        // vamos andar uma posição com o ponteiro
        ponteiro++;
        }else{
       // vamos zerar o ponteiro
        ponteiro = 0;
       }
         // Agora vamos mostrar o item da Lista
         meuTextView.setText(frases.get(ponteiro));
};
}

Para adicionar a ação em seu botão :
botaoProximo.setOnClickListener(nextAction());

Comment: fala Thiago Luiz Domacosk, obrigado por tentar ajudar cara, então. declarei meu array assim: String [] frases = getResources().getStringArray (R.array.frases);  porem quando tento usar a combinação frases.size na iteração if o "size " não existe...sabe me dizer porque?
Comment: Tente **length** no lugar de **size()**. A propriedade **length** refere-se ao **String[]**, e o método **size()** e de um **List**
Comment: E ao invés de **frases.get(ponteiro)** use **frases[ponteiro]**
Comment: Vlw Thiago Luiz Domacoski. Deu certo. Obrigado.
Comment: Thiago to tentando implementar o botão "anterior" e fiz assim dentro do metodo:      'if (ponteiro0) Enquanto for **maior** que zero decrementa, senão volta pro fim
Comment: Não ta dando o erro agora acontece na passagem de 1 pra 0 o app trava
Comment: Qual erro ele mostra?
Comment: Tente: ponteiro= frases.length-1;
Comment: Agora deu certo Thiago, so faltava "frases.length-1
Comment: Obrigado Thiago

implementando onClick


One vs. multiple entry points in web apps

Question: I'm working on a major refactoring of a web application.
It currently consists of some common scripts included from all pages (common, functions, header, footer...), plus entry points for all kinds of actions (login.php, viewthis.php, viewthat.php).
Now I'm thinking of introducing a front controller and using some kind of model architecture instead.
I'd like to know:
What are the pros and cons of both architectures? Any special benefits? What should be used in general (if any)?
Comment: I think you need to go into a little more detail about what your plan is before anyone can tell you if it's a good idea or not.
Comment: Not sure. What exactly isn't clear? I'm asking because I am not sure yet. ;)
Comment: What are pros and cons of both architectures? Any special benefits? Well, that depends on what you want. There are always going to be pros and cons. But, what do you actually want. For instance, if your website is slow, you can work on it to improve performance. If its fine, why bother changing architecture at all? So, what problems are you facing with the current architecture?
Comment: Ah, okay. There are no problems actually, but front controller seems to be fairly widespread today. And I'm thinking why? Also, I know of some of the benefits (easier access control etc.), but I'm not sure how the weigh against possible downsides. The software is everything but slow. We're just trying to modernize it and this was one of the things I had on my list.
Answer: I'd recommend a controller. You'll gain in centralized validation of in-data, easier adaptation for mod_rewrite etc.
Can't see any real point of the other technique. It's just old.
regards,
/t


How to change the display of my field?

Question: I have a field in one of my content types called lab_test_id. When Editors add content of that type they enter all the ids of the lab tests associated with that node. I need to be able to take that id, call that lab test database, and display the lab test fields I get back.
Can I accomplish that by changing the display of the lab_test_id field via hook_field_display_alter or should I find another way to accomplish that?
Comment: "call that lab test database, and display the lab test fields I get back." - are "lab tests" drupal content, or is that completely separate custom database outside drupal?
Comment: It is a completely separate custom database
Comment: Drupal works easier if the content is located within its own database. If you would have 'lab tests' as a content type, it would as easy as to work with Entity reference and Display Suite :-) You 'could' duplicate the data to Drupal first with Feeds or something if that is an approach you would like.
Answer: I think you can do this using hook_field_display_alter, however, I would personally prefer to create a custom formatter for the used field type. With the main advantage that you can save settings for the field formatter.
See the answers of How do I write an additional field formatter for an existing field for basic steps on how to create your own field formatter.
Comment: Going to your link I found a nice little module called Custom Formatters which might do the trick too.
It does the same thing just is set up so that you don't have to set up a custom module.
Comment: Interesting module, didn't know about that one yet :)

How to change the display of my field?


Did Joaquin Rodrigo's Concierto de Aranjuez infringe on Mahler's Sixth Symphony?

Question: I happened to hear Mahler's Symphony no 6 in A minor Tragic, 3rd Movement, Andante Moderato this week for the first time and was surprised to hear what sounded like the primary theme from Joaquín Rodrigo's Concierto de Aranjuez, Second Movement, Andante Moderato.
I looked at the dates on both works and found Mahler composed his 6th Symphony in 1903-1904. Rodgrigo composed Concierto de Aranjuez in 1939.
Here is the theme from Rodrigo's Andante Moderato:
Andante Moderato theme
Here is the theme from Mahler's 6th, 3d Movement:
Mahler's 6th 3d Movement
There are a few technical questions, some of law and some of music theory (which I trust will justify presenting the matter in this forum), which are pertinent. Is there substantial similarity in the relevant musical phrase in question? Is the phrase so common that one might claim scenes a faire, i.e., in common use in the genre?
As a matter of legal distinction, but this also pertains to attempting to understand the similarity of the similar phrase here, did Rodrigo have access to Mahler's work, i.e., was it possible that Rodrigo heard Mahler's work before composing his?
Interestingly, Rodgrigo studied music in Paris sometime after 1917, first at Ecole Normale de Musique and then with Maurice Emmanuel and Andre Pirro (in Paris). Rodrigo subsequently composed Concierto de Aranjuez in Paris in 1939. He recalls "...I heard a voice inside me singing the entire theme of the Adagio [his Second Movement] at one go, without hesitation...born of an irresistable and supernatural inspiration.."
At the time of his death in 1911, Mahler was "...a major musical figure in Europe...his music performed in St. Petersburg in the east, Helsinki in the north, and in Paris in the west."
May we conclude that that Rodrigo probably unconsciously used Mahler's phrase in his own work in 1939?
Comment: @Richard I'm glad someone else hears a connection (and that it is not well-known). Last week I "discovered" Eric Carmen borrowed most of the melody for his 1975 hit "All by Myself" (not one of my favorites) from Rachmaninoff's Piano Concerto No. 2 (2nd movement), only to find that Carmen had acknowledged it and even paid 12% royalty to the Rachmaninoff estate.
Comment: Wow. I've known both of these pieces for years and never heard any connection, but I definitely hear it once you point it out. Great question!
Answer: To recap, we are considering the question of whether the minor key theme in Mahler's Sixth Symphony, Andante Moderato movement, is similar to the subsequent composition of either or both of the two melodic themes in Rodrigo's Concierto de Aranjuez, Adagio (the second movement in this work), so similar as to support a hypothesis that Rodrigo unconsciously relied on Mahler's 1903 phrase in his 1939 composition.
Can an average listener hear so much similarity as to suggest these segments reflect copying of some kind? Stripping the compositions under consideration down to just the bare primary melody sequences and transposing Rodrigo from D/Bm to Eb/Cm to facilitate comparison with Mahler's theme in the same key (and adjusting the timing to put them in about the same rhythm) we can display the musical score and highlight the notes as they are sounded in the following videos. In the first YouTube video we present the minor theme from Mahler's Sixth ("MAH") followed by Rodrigo's first theme ("ROD-I"), followed by Mahler again as it seems most people immediately want a second hearing:
MAH V ROD-I youtube comparison
In the second video we present the same minor theme from Mahler's Sixth ("MAH") followed by Rodrigo's second theme ("ROD-II"), followed by Mahler again:
MAH V ROD-II youtube comparison
Many people will probably hear some similarity in these segments, musically and in the emotion they invoke, but can we make a more objective comparison? For cases of outright replication of one song by another it is enough to present them in the fashion above (or running concurrently, when there is literal copying), but this is not the case here.
As a first step in a more technical analysis, it might be useful to examine the way the two composers developed their melodies, i.e., did the notes leap large pitch distances between successive notes, did they use similar transitions, etc. In music theory you will be familiar with the distance between two successive pitches (notes) as intervals in the diatonic scale and they will be defined by the number of semitones in the step. I assume the reader has a basic education in music theory, but if not (or if you want to check definitions, I found the 1914 textbook by Gehrkens to be an excellent resource; freely available at Project Gutenberg) Gehrkens Music Notation and Terminology
I used Matplotlib, an open source Python-based plotting library widely used in the scientific computing community (see the interesting article by the creators of Matplotlib at article by the creators of Matplotlib
to create a  stacked histogram (a bar chart) with bins equal to the intervals appearing in the melodies under examination and the frequencies the number of occurrences of that particular interval, e.g., -3 semitones on the x-axis is a falling minor 3rd interval. The three melody sequences are color coded and the respective frequency of occurrence in their melodies is stacked (so the length of a particular color segment within a histogram bar indicates the number of occurrences of that interval in the melody coded with that color):

Looking at that stacked histogram of the frequency of occurrence of ascending and descending melodic intervals in MAH and ROD-I and ROD-II it appears that if you discard the repetitive notes (the "0" bin which indicates repeated notes, which are used only by Rodrigo) there is a close correspondence between Mahler and Rodrigo, closer perhaps between Mahler and ROD-II where they each have added a unique outlier, otherwise making similar use of interval motion.
But interval motion presented in a histogram doesn't give a gestalt impression of the actual flow of the melody, so let us look at a contour graph, a line plot of the actual notes of these melody segments as they appear one after another in time. This can be done by hand, sketching up and down line segments above the musical score to show the rough contour of the melody, but I will instead use Matplotlib again.
Here is the line plot of MAH, which gives you an idea of the shape of the melody, the types of changes in slope sign (up or down movement of the notes) and whether the notes leap or make step-wise movement to the next note:

you can see more or less a descent of the melody in several groups to the terminating note. This helps me somewhat to understand the emotion associated with this segment (the affect), somewhat of a continuing descending lament, being notes from the melodic minor scale. The sequence begins on the dominant and briefly touches the tonic once before sinking in melancholy musing to the dominant again, leaving an unsettled feeling (of not resolving to the tonic). Mahler (I note that I have only studied Mahler's Andante of the Sixth, the Adagietto of the Fifth and the First movement of his unfinished Tenth) seems often to communicate through his music that we savor the peaks in human existence only to the extent we must climb from the dark valleys and that there eventually will come to us all a time when we are unable to make the ascent again.
Looking at ROD-I:

and ROD-II:
We immediately find the same pattern of stepped descent we saw in the Mahler segment, perhaps more so in ROD-II. Rodrigo stays within the Primitive/Aeolian minor scale, not using the natural on the sixth that Mahler adds (Mahler freely using this feature of the melodic minor scale on ascent and descent and otherwise mixes from the primitive/aeolian scale). However, this does not distinguish the emotional effect of the segments appreciably to my hearing. Unlike Mahler, Rodrigo closes his descending melancholy introspection on the tonic, providing somewhat more of a termination to the feeling (one still has the impression that there was some resistance to that final descent though).
I wondered what another theme in a minor key might look like in comparison to these three, i.e., is this a relatively distinctive shape (the continued descent), so I graphed the basic theme of Mozart's Requiem Aeternam (transposed to Eb/Cm):
Quite a difference in shape! Mozart's theme climbs in sad majesty as befitting one leaving this life and ascending to eternity.
One could examine the relationship of notes of a melody with the accompanying chords, i.e., harmonic analysis, but I don't believe that is necessary in the present context. Mahler's and Rodrigo's themes here seem to suggest harmony to me rather than to acquire essential character from it (an opinion I arrived at after doing this work).
There has been an ongoing effort for some years now, driven in large part by the business of content-based music retrieval (or the possibilities of that capability), to define similarity measures between pieces of music. A simple approach to computing melodic similarity might be to represent the melodic profile of pieces using three classes of pitch intervals, i.e., ascending, descending, and same, much as we did earlier by constructing a histogram based on this data structure.
More complex representations may use finer quantization of the intervals, add analysis of the relationship of harmony (melody note relation to accompanying chord) and metric weight (position and duration of the note in the sequence). Software implementing melodic similarity analysis may use a sliding window, looking for the best match between successive portions of one melody while holding the query segment constant, aligning elements of one sequence with an element of another (or with a gap). [see A Measure Of Melodic Similarity Based On A Graph
Representation Of The Music Structure; Orio and Roda 2009 ] The implication/realization model looks at three note sequences constituting two intervals, categorizing experimentally determined expectations by listeners on how the melody will continue. Once categorized as sequential data, general methods for comparing sequential data, e.g., edit distance, can be used to evaluate similarity of one sequence with another. [see Melody Retrieval using the Implication/Realization Model; Grachten, Arcos and Mantaras].
The Répertoire International des Sources Musicales or RISM maintains a comprehensive database of music, including a music incipit search, which makes it possible to search (using melodic similarity software) a database of about one million incipits for works that are musically similar, based on the progression of the beginning notes of a composition (the note names can be typed or entered with an onscreen piano keyboard). These seem to be primarily works prior to 1800, however, this is still a valuable database for testing melody similarity software, among other purposes. I found the online search provided by Ultrecht University at Online RISM incipit search
to be more useful as a hook into the RISM incipits. With that facility I found incipits by Domenico Gallo "Dixit Dominus" (18th century) that were considered to be most similar to Rodrigo in part and Antonio Cesti "Bella Clori" (17th century) most similar to a portion of Mahler (keep in mind that this simply means for the million or so incipits, the returned segments had the highest computed similarity scores, i.e., it doesn't mean that they matched exactly the query, but I could hear brief similarity of significance).
I thought it might be interesting to use melody similarity software, MelodyShape, developed by Julian Urbano [available atUrbano MelodyShape program
using algorithms he achieved best results with in the MIREX Symbolic Melodic Similarity task competition 2010 – 2015, to run some comparisons on the Mahler and Rodrigo segments, as well as incidental pieces for comparison.
Urbano's MelodyShape Java software accepts MIDI files for comparison and "transforms note trigrams to a series of B-spline interpolations, which are curves fitted to the contours of the note trigrams. The resulting series of B-splines of two melodies are then compared through alignment," quoting from A Comparison Of Symbolic Similarity Measures For Finding Occurrences Of Melodic Segments; Janssen et al, 16th International Society for Music Information Retrieval Conference 2015. In other words, MelodyShape does something similar to what we did earlier in plotting lines connecting the notes of the melodies in order to get a feel for the shape of the resulting contour. Each group of three notes in succession has a smooth curve calculated to connect them; that mathematical function is then a "spline" defined for that section. Another spline is calculated for the next group of three notes, designed to connect smoothly with the previous spline also. In this way a piecewise smooth numerical characterization of the shape of each melody segment is obtained and then compared in successive alignment to find the areas where the shape matches in the two melodies under comparison. Good matches should return a high value, bad matches a low, possibly negative value.
Running MelodyShape (installed locally on my computer) with Mahler as the query I obtained the following results:
Mahler compared to itself:  6.55140000
compared to Antonio Cesti "Bella Clori" (17th century):   3.54120893
compared to Domenico Gallo "Dixit Dominus" (18th century) -0.14140608
compared to Rodrigo's second theme: -0.16697577
compared to Rodrigo's first theme:  -0.16697577
Running MelodyShape with Rodrigo's first theme as the query gave:
compared to itself:  6.55140000
compared to Rodrigo's second theme:  0.34103238
compared to Domenico Gallo "Dixit Dominus" (18th century):   0.17138156
compared to Mahler theme:   -0.16697577
compared to Antonio Cesti "Bella Clori" (17th century):   -0.38888889
Running MelodyShape with Mozart's Requiem Aeternum theme as the query:
compared to Antonio Cesti "Bella Clori" (17th century):  0.87988889
compared to Mahler theme: 0.23808437
compared to Domenico Gallo "Dixit Dominus" (18th century):  -0.02564103
compared to Rodrigo's second theme: -0.04861111
compared to Rodrigo's first theme: -0.04861111
MelodyShape rightly suggests Rodrigo's themes I and II are somewhat similar, agrees with the RISM incipits similarity (Dixit Dominus somewhat similar to Rodrigo themes; Bella Clori very similar to Mahler's theme), suggests Mahler is not very similar to either Rodrigo theme, and Mozart is not similar to any of them.
My work here suggests that we may not conclude that Rodrigo unconsciously (or otherwise) used Mahler's phrase in the composition of his own work, though we see technical reasons why these three melodic segments feel similar, e.g., melody shape/contour, use of same melodic interval motion. It is only possible that Rodrigo had Mahler's work in his mind on the level of musical memory (whatever level that is), a tantalizing hint being Rodrigo's long silence on where he got his inspiration for the Adagio, finally commenting that he heard a voice singing it inside him.
Answer: I love your question and the research you put into.
I am not a lawyer so this is purely my opinion here. In the example you give, I really do not hear enough resemblance to raise the question of copyright infringement.  Some subtle music appropriation, which has been common in the history of music, possibly.
I would guess that to claim a composer infringed on someone else's work, there would need to be at least one element that is distinctive enough from the original piece that finds its way in the "remake".  The distinctive element could be melody, rhythm, texture, etc.
When you mention the Aranjuez concerto, I think people will easily hum the part you pointed us to in the video.  Reversely, you hum that air and many people will identify it as from Rodrigo: it just has a melody and rhythm that stick.  I am pretty sure this wouldn't be the case with Malher's symphony.
It could very well be that Rodrigo wouldn't have composed this piece in this exact way if he had never heard Malher before, we will never know--and from what you quote, it might be that even Rodrigo himself wouldn't know--but I don't see/hear the identity of Malher's piece in what Rodrigo created.
Now, with respect to what legal experts say, I poked around and found some cases that provided some insights into what is or is not acceptable in terms of reusing earlier work.
Here for example, they say

If the said musical composition was borrowed altogether from a former one, or was made up of different parts, copied from older musical compositions, without any material change, and put together into one tune, with only slight and unimportant alterations or additions, then Russell was not the author within the meaning of the law; but the circumstance of its corresponding with older musical compositions, and belonging to the same style of music, does not constitute it a plagiarism, provided the air in question was, in the main design, and in its material and important parts, the effort of his own mind.

To me, that means that "if you worked hard enough on the piece to bring clearly new distinctive elements to it, it's yours".  That's a much stricter definition of infringement than I would have instinctively used.  For example in the lawyers who wrote that decision, I expect that they would find the work from Jacques Loussier like here a new work on its own right and thus not an infringement.  And same would go with Rodrigo's work.
Comment: I found your answer very creative, but you could make a similar argument in favor of Eric Carmen's use of Rachmaninoff's Piano Concerto No. 2 (2nd Movement), i.e., most people would now identify the melody in question as Carmen's though he admits taking it from Rachmaninoff. By analogy, if someone moved into your home while you were away it might be argued that they had been there long enough to displace your ownership. If you consider that the Mahler sequence is not only reproduced melodically but with the critical harmony that makes it so distinctive, it cannot be coincidence by Rodrigo.
Comment: Hard to respond in few words! 1. I do see the law as more lenient to the reuse of material than what my intuition would have been. 2. Whether it is due to my familiarity with the piece or something else, I find Rodrigo far enough from Malher to not even see his work as a make over of Malher's symphony, left alone an infringement. 3. Whereas Carmen's piece is clearly building on Rachmaninov's concerto, keeping enough of the original to leave no ambiguity.
Comment: 4. Back to "personal" position here, which wasn't your question, I have no issue with what Carmen does: he quotes his inspiration (hard to hide anyway!) and uses it to convey something different enough while still touching millions, some likely not overlapping with the Rachmaninov admirers by lack of exposure.  Rather than kicking Rachmaninov out of his house, I think he built him a nice extension.
Comment: There is an excellent resource for looking at the law regarding music copyright infringement sponsored by Colombia Univ. and USC http://mcir.usc.edu/purpose/Pages/default.html. I have been conducting a formal musical analysis and will post that soon. I am leaning towards agreeing that the Mahler segment and Rodrigo are not significantly related, but want to present that in more objective terms. Interestingly, I did find a segment by Domenico Gallo "Dixit Dominus" 18th century that does match Rodrigo in part and Antonio Cesti "Bella Clori" 17th century matches Mahler.
Comment: Please keep us posted when you post your analysis! Is your analysis about classical composers reusing other's work or is it more general?
Comment: I hope to put together an article/answer soon dealing specifically with the music theoretical reasons why the segments under consideration sound similar and how one might quantify that to some extent. That would apply to the general matter of comparing musical phrases for similarity. I am not sure how to assure you see the update when it posts (I am pleased that SE has notified me lately of new comments--had wanted that for some time).
Comment: I finally posted an answer with some effort to look at objective criteria in the analysis of similarity, so wanted to assure that you were aware of it. Hope it is not an anticlimax, grin.


opendkim-testkey: key not secure, but dnssec is ok

Question: I'm trying to setup opendkim, but I get this result:
# opendkim-testkey  -vvvv -d my.example.com -s 201702
opendkim-testkey: using default configfile /etc/opendkim.conf
opendkim-testkey: checking key '201702._domainkey.my.example.com'
opendkim-testkey: key not secure
opendkim-testkey: key OK

That should mean DNSSEC is not working.
But according to https://dnssec-debugger.verisignlabs.com/example.com dnssec is fine.
Should I worry?
Comment: It is obvious that `my.domain.dom` is an example,
Comment: The TLD `dom` doesn't yet exist, so `domain.dom` wouldn't have DNSSEC. Your link doesn't state that DNSSEC is fine on `domain.dom`, rather that DNSSEC on the root zone is fine.
Comment: And we cannot help you diagnose DNSSEC issues on a domain which isn't supplied.
Answer: You have to make sure that OpenDKIM is able to use DNSSEC. key not secure in this context means that OpenDKIM was not able to verify the key using DNSSEC.
For example, you can use dig to see if it reports the AD (authentic data) flag:
$ dig yourselector._domainkey.yourdomain.org TXT +dnssec

; <<>> DiG 9.16.1-Ubuntu <<>> yourselector._domainkey.yourdomain.org TXT +dnssec
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26731
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

...

The important bit here is the flag ad: it means that whatever resolver was used on the host was able to authenticate the response data with DNSSEC.
For OpenDKIM, you also must make sure that it can use DNSSEC. For example, on Debian the setting TrustAnchorFile /usr/share/dns/root.key in the default /etc/opendkim.conf provides the support for DNSSEC capabilities.
Comment: This is the solution. @Lenne you might accept this answer...
Comment: Hi @Lenne , @71GA and @glts I know this answer was a long time ago, but i'm facing the same error as the OP and can't figure out why i'm getting it.
`dig` command did not show me the `ad` flag, I added the `TrustAnchorFile` but things stayed the same, with or without it. Any more ideas ?  Thanks a lot


Localizar dia da semana especifico dentre datas

Question: Tenho o seguinte código para lançar em uma agenda dias e horários disponíveis e para isso uso a seguinte rotina:
    //recebo dados do formulario
    //inclusive o dia da semana ex.: Friday
    $dia_semana = $_POST['dia_semana'];
    $hora = $_POST['hora'];
    $laboratorio = $_POST['laboratorio'];
    $quantidade = $_POST['quantidade']-1;

    //pega a data de hoje
    //para verificar qual a proxima data correspondente ao
    //dia enviado pelo formulario
    // como por exemplo, proxima sexta(Friday)
    $hoje = date('Y-m-d');
    $dia = date("Y-m-d", strtotime("$hoje next $dia_semana"));

        $dados = array(
            'data' => $dia,
            'hora' => $hora,
            'laboratorio' => $laboratorio
        );
        //cadastra no banco a primeira data usando minha funcao
        $cadastrar = DBCreate('nw_vip',$dados);

      //faz um loop para cadastrar as proximas datas
      //com o dia escolhido limitado a quantidade
      //passada pelo formulario
      for($i=0;$i<$quantidade;$i++)
      {
       //se a primeira sexta caiu no dia 10
       //caucula as proximas somando 7 dias e cadastrando
       $dia =  date("Y-m-d", strtotime("$dia +7 day"));
       $dados = array(
         'data' => $dia,
         'hora' => $hora,
         'laboratorio' => $laboratorio
       );
      //cadastra no banco usando e minha função
      $cadastrar = DBCreate('nw_vip',$dados);
}

Meu problema se eu lançar 5 sextas feiras hoje e depois lançar mais 5 sextas, ele vai repetir as datas.
Então eu precisaria que na segunda vez que eu fosse lançar ele pudesse considerar a ultima sexta já cadastrada caso haja alguma e registrar a partir dela.
Exemplo: Lanço 3 Sextas as 8hs:
Sex 24/06 8:00
Sex 01/07 8:00
Sex 08/07 8:00

Se mais tarde eu lançar novamente mais 5 que a próxima continuasse da sexta dia 15/08. Como realizar um consulta para saber a data da ultima sexta feira já cadastrada, conforme meu exemplo. Claro que poderia ser outro dia e até outro horário.
Answer: Você pode fazer uma consulta na sua tabela procurando a última ocorrência de data do dia da semana que está tentando agendar. Para o exemplo da sexta-feira fica assim:
SELECT MAX(data_agenda) AS ultima_data
  FROM minha_agenda
 WHERE WEEKDAY(data_agenda) = 5;
/* semana iniciando em 0 para domingo, então 5 é sexta-feira, ok? */

Você pode mudar a query para o WHERE contemplar mais restrições, como horário, laboratório, ou qualquer outra informação que desejar.
O resultado da consulta será sempre a última data no seu contexto. Se resultar vazio, significa que você ainda não tem registro e pode iniciar com o próprio dia informado pelo usuário.
Informações sobre a função WEEKDAY aqui: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_weekday
Observação: também é possível usar a função DAYOFWEEK, que usa o padrão de semana iniciado em 1 para domingo, 2 para segunda-feira e assim por diante.
Comment: A função MAX nesse contexto me retorna a data 'mais alta', no caso a que esta mais distante no futuro?
Comment: A função te retorna a maior data que encontrar na tabela do banco de dados, para as restrições que você determinou na query. Inclusive datas no futuro já registradas na tabela.


Integrating $\int_{a}^{\infty} \frac{x^4e^x}{(e^x-1)^2}dx$ for large values of $a$

Question: I have to show that $$\int_{0}^{\infty}\frac{x^4e^x}{(e^x-1)^2}dx
 \approx \int_{0}^{a} \frac{x^4e^x}{(e^x-1)^2}dx$$ for large values of $a$. This can be done by showing that $$\int_{a}^{\infty}\frac{x^4e^x}{(e^x-1)^2}dx$$ is exponentially small.
However, I am having trouble finding a way to integrate $$\int_{a}^{\infty}\frac{x^4e^x}{(e^x-1)^2}dx$$ analytically.
I was given a suggestion to think about making an approximation to $x^4$ when integrating over a region where $x$ is large, but I'm completely lost.
Any suggestions is greatly appreciated.
Comment: What about using $x^{4} \le e^{x}$ for $x \ge 0$? Then you can bound your integral from above. It seems to come out pretty nicely.
Comment: What values of $a$ do you consider large?  Do you have access to software like *Mathematica* which can calculate the integral to any arbitrary precision?
Comment: Hi Mattos, thanks for the suggestion, but I'm not exactly sure what you mean by being able to bound the integral from above using the given inequality.
Comment: JimB, I unfortunately do not have access to such software. The question just states "for large values of $a$," so I wouldn't know how to answer your first question.
Comment: I came up with perhaps a foolish attempt at the solution inspired from Mattos' suggestion which would be to say that  $1< x^4 << e^x$ for large values of $x$, so the integral would simplify to

$\int_{a}^{\infty} \frac{e^x}{(e^x-1)^2}dx$

Which comes out to be

$\frac{1}{e^a -1} \approx e^{-a} $

but I can't stand for the legitimacy of this solution...
Answer: We have that for $a>\ln(2)$,
$$\int_{a}^{\infty}\frac{x^4e^x}{(e^x-1)^2}dx=\int_{a}^{\infty}\frac{x^4e^{-x/2}}{e^{x/2}(1-e^{-x})^2}dx< \frac{\int_{0}^{\infty} x^4 e^{-x/2}dx}{e^{a/2}(1-e^{-\ln(2)})^2}=\frac{2^2\cdot 2^5\cdot 4!}{e^{a/2}}$$
which implies that the LHS goes to zero exponentially as $a$ goes to $+\infty$.
Answer: For sufficiently large $x$,
$$\frac{x^4e^x}{(e^x-1)^2}=\frac{x^4}{(e^\frac{x}{2}-e^\frac{-x}{2})^2}$$
$$=\frac{x^4}{(\sum_{n=1}^{\infty} \frac{x^{2n}}{2^{2n}(2n)!})^2} <\frac{x^4}{\sum_{n=1}^{\infty} \frac{x^{4n}}{(2^{2n}(2n)!)^2}}$$
$$<\frac{x^4}{\frac{x^8}{k}}$$
$$=\frac{k}{x^4}$$
where $k$ is some constant. Thus,
$$0<\frac{x^4e^x}{(e^x-1)^2}<\frac{k}{x^4}$$
Integrating both sides gives the required answer.


Detect the entity provided in utterance

Question: I am using the following two utterances in same intent

Book tickets to California from Mumbai

Book tickets from Mumbai to California.
In this case, Microsoft advises to use the Hierarchical entity to identify the source and destination entity. But Hierarchical entity doesn't support predefined list. If I have to use List entity, then I can't identify the source and destination entity because the entity array will contain Mumbai and California and we will not know which source and destination city. Can any help on the approach.

Regards,
Pradeep
Comment: If possible, you could share the details of entities with screenshots that you created in LUIS app so that we can reproduce the issue quickly.
Answer: You could use a composite entity, composed of list entities for the origin / destination portions.
You can check out the tutorial in the official documentation here for guidance of how to implement the solution.

Detect the entity provided in utterance


singluar values unchanged when multiplied with an orthogonal matrix?

Question: revisiting
singular values of "rotated" matrix
Maybe I've since forgotten - or maybe I never bothered to ask myself - but

Since $A^T$ has the same singular values as $A$ and $K$ is orthogonal, conclude that [        $A^\top K$        ] indeed has the same singular values.

Why does this hold?
Why can we say that multiplying by an orthogonal matrix retains the singular values?
Comment: The (nonzero) singular values of $A$ are related to the eigenvalues of $A^TA$ which are in turn related to the eigenvalues of $AA^T$. Now for $B=A^TK$ you have $BB^T=A^TA$.
Answer: We calculate the singular values of $A$ by decomposing it into $A=USV^T$ with diagonal $S$ and orthogonal $U$ and $V$. If we have another orthogonal $K$, we have $AK= USV^TK = U  S (V^TK)$ which is the SVD of $AK$.
Comment: I see, and $V^\top K $ is orthogonal because $V^\top K (V^\top K)^\top = V^\top K K^\top V = I $. Thank you.
Answer: Let $A = UDV^T$ be the singular value decomposition.
If you premultiply it with $K$, $KA=(KU)DV^T$
$KU$ is an orthogonal matrix as well. In fact $(KU)DV^T$ is a singular value decomposition for $KA$. The $D$ matrix is not changed.
Similar reasoning for post-multiplication.


Intermittent Excel issue of "file locked for editing" not showing when it should

Question: Current setup: 3 app servers (2008 r2, terminal services XenApp 6.5), 2 file servers (2008 r2).
Situation: user1 opens up an excel file that is on server1 and starts to work.  user2 goes to open that same file, and does NOT get a message that the file is 'locked for editing' message.  So they go in, make their changes, save out and close the file.  Their work is never saved to the file.  A open file session is never created for user2 on the file server, but they see and work as though all is normal.
The app server doesn't seem to come into the equation, but file server 2 does not exhibit the same issues as file server 1.  And with that, those issues are not happening 100% of the time on file server 1. There are times where user1 will access a file [also happening with random excel files, not limited to just 1], and user2 will wait a few minutes, go in and they do not see an lock message. User2 closes excel, then user3 goes in and gets the lock message.
The common piece to the randomness is file server 1 and why its not registering the excel session as an open session, which will then alert another user that it's already open.
Open to any suggestions.
Answer: There's a possible answer at:
https://helpdesk.yourofficeanywhere.co.uk/kb/a183/excel-loses-file-locked-for-editing-when-accessing-data-on-network-drive-mapped-via-group-policy.aspx
In summary:
If the file is on a drive mapped by group policy, the periodic policy refresh can disconnect and reconnect the drive, causing the lock to vanish. You can change the action setting on the group policy from Replace to Update which should ensure that the connection doesn't get dropped.


android app hangs starting a service

Question: I'm try to create a simple service.
this is the service source
public class UploadService extends IntentService {

    public UploadService(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "handling intent", Toast.LENGTH_SHORT).show();
    }

this is the definition of the service in the manifest
<service
    android:enabled="true"
    android:name="com.sopla.Services.UploadService">
</service>

this is the code I use to start the service in the onCreate method of the main Activity called at the startup of the program
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(this,
            com.sopla.Services.UploadService.class);
    startService(intent);

I can debug all the onCreate method, but after this the program hangs, and I cannot reach the breakpoint in the service source code.
I'm missing something?
thanks,
  Luca
Comment: **"android app hangs starting a service"** : Post your logcat output. Just saying it "hangs" doesn't help anyone help you.
Answer: try this for your onStartCommand:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    TODO do something useful
    return Service.START_NOT_STICKY;
}

Answer: thanks to every one, but checking better the logcat I found the problem.
For some strange reason, asking the Ide to add the missing members of IntentService add a costructor with a string, but at runtime a constructor without is reguired.
Removing the string parameter from the costructor solved the problem.

android app hangs starting a service


Adding an user to the repository with read access for specific directories

Question: I have a repository on the bitbucket website. All of my website is into that repository. Now I want to hire a new programmer for the project. So I have to add him to the repository.
I want to share only few directories of the project with him, not the whole project. In other word, I want to give him read (or maybe write) access to some specific files and folders.
Is doing that possible?
Answer: No, access control can only be done on an entire repository. Which files go where into which directory is all decided inside the repository data.
You could create a new repository, containing only the directories that you would want to share and the use that as a submodule for your main repository though of course.