Tornar o zoom da página padrão

Question: Tem algum script que quando o usuario abrir o sistema o zoom ja fique pré configurado quando abrir a pagina ja fique padrão ?
Comment: Poderia elaborar um [mcve], por favor?
Answer: Sim, e nem precisa de JS. Utilizando HTML5:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

O initial-scale controla o zoom inicial da página. 1.0 é 100%, 0.75 é 75% e assim por diante. Outra opção é utilizar a propriedade zoom do CSS.
body {
    zoom: 2 /* Coloca o zoom em 200% */
}

Comment: vlw jovem nao estava lembrando disso ai
Answer: A meta-tag: <meta name="viewport" content="width=device-width, initial-scale=2.0"> não é para todos ambientes e em desktop talvez isso venha a não funcionar.
A propriedade zoom: ...; não é standard e pro isso não é suportado por todos navegadores, para que corra em todos browser atuais prefira transform, assim:
#content {
    transform: scale(2.0);
    transform-origin: 0 0;
}

html:

... conteudo da sua página ...

Não aplique diretamente no body, isso pode afetar alguns scrollbars.
Se precisar de suporte para navegadores mais antigos use:
#content {
    /*Safari e Chrome antigos*/
    -webkit-transform: scale(2.0);
    -webkit-transform-origin: 0 0;

    /*Firefox mais antigo*/
    -moz-transform: scale(2.0);
    -moz-transform-origin: 0 0;

    /*IE 9*/
    -ms-transform: scale(2.0);
    -ms-transform-origin: 0 0;

    /*navegadores atualizados*/
    transform: scale(2.0);
    transform-origin: 0 0;
}

Tornar o zoom da página padrão


alternative relationship deprecated warning

Question: Cypher query:
MATCH (x) WHERE x.uuid = "41f64ab1-6009-4e95-b22b-c833525f6edb" MATCH p =
(o)-[:CONTAINS|:HAVING*]->(x) WHERE labels(o) IN ['Box', 'Package'] RETURN p

Running it in Neo4j browser results in a warning:
**WARNING: This feature is deprecated and will be removed in future versions.**

The semantics of using colon in the separation of alternative relationship
types in conjunction with the use of variable binding, inlined property
predicates, or variable length will change in a future version.

How can I re-write this query to eliminate this warning?
Thanks in advance.
Answer: This deprecation is not about inability of using relationship type alternatives but about its syntax – see cypher deprecations in version 3.2. Only first type has colon now, i.e. not :R1|:R2 but :R1|R2. Deprecation warning in Neo4j browser suggests that former syntax will have new semantics in the future.
Specifying relationship type in a pattern is actually much more effective than filtering paths ex-post which is the way that the workaround by Tom Geudens is executed.
Answer: This might do it :
MATCH (x) WHERE x.uuid = "41f64ab1-6009-4e95-b22b-c833525f6edb"
MATCH p = (o)-[*]->(x)
WHERE labels(o) IN ['Box', 'Package']
AND ALL (rs IN relationships(p) WHERE type(rs) IN ['CONTAINS','HAVING'])
RETURN p

Hope this helps.


Finding covariance matrix for MLE of correlated outputs

Question: I generate data using the following model:
$\begin{pmatrix}Y_1\\Y_2\end{pmatrix} \sim \mathcal{N}\left( \begin{pmatrix}\mathbf{X}\beta_1\\\mathbf{X}\beta_2\end{pmatrix}, \mathbf{\Sigma} \right)$
I create $N$ test pairs, $Y_1^*, Y_2^*$, I'd like to fit a least-squares model to this data and evaluate its likelihood. So, I set:
$\hat\beta_1 = (\mathbf{X^TX})^{-1}\mathbf{X^T}Y_1^*$ and
$\hat\beta_2 = (\mathbf{X^TX})^{-1}\mathbf{X^T}Y_2^*$
I'm having trouble computing $\mathbf{\hat\Sigma}$.
So far, I've tried
$\hat e_1 = Y_1^* - \mathbf{X}\hat\beta_1; \;\hat e_2 = Y_2^* - \mathbf{X}\hat\beta_2 \; \; (\star)$
$\mathbf{\hat\Sigma} = \frac{1}{N}\left(
  \begin{array}{ c c }
     e_1^Te_1 & e_1^Te_2\\
     e_2^Te_1 & e_2^Te_2
  \end{array} \right) $
But I've found that $\mathbf{\hat\Sigma}$ is pretty far from the true $\mathbf{\Sigma}$ that generated the data.  Do I need to account somehow for the correlation between the two outputs when doing the estimation at step $(\star)$?
Answer: You are almost there.
$$
\begin{align*}
Cov(\hat\beta_1, \hat\beta_2) &= Cov\left((\mathbf{X^TX})^{-1}\mathbf{X^T}Y_1^*, (\mathbf{X^TX})^{-1}\mathbf{X^T}Y_2^*\right) \\
& = (\mathbf{X^TX})^{-1}\mathbf{X^T} Cov(Y_1^*, Y_2^*) \mathbf{X} (\mathbf{X^TX})^{-1} \\
&= (\mathbf{X^TX})^{-1}\mathbf{X^T} \Sigma_{12} \mathbf{X} (\mathbf{X^TX})^{-1}
\end{align*}
$$
And a similar calculation can be used to find $Cov(\hat\beta_1, \hat\beta_1)= Var(\hat\beta_1)$, etc.  (One may use the Kronecker product to write this all more compactly.)
Since in practice you don't know $\mathbf \Sigma$, one may plug in the consistent estimator $\boldsymbol{\hat{\Sigma}}$ (cross product of residuals) noted at the end of your question.
All of this falls under the topic of "generalized estimating equations" if you desire some more background reading.
Comment: Thanks for the solution and the reading material. I'm simulating data and comparing the performance of least-squares and expectation-maximization, so in this case I do know $\mathbf{\Sigma}$, but that's obviously not true in general.


Regex that does NOT match something I matched before

Question: As part of a question I asked earlier today, my goal is to validate all the moves a rook can make in chess notation.
This consists of:

The letter R
An optional disambiguation, the source of the problem (discussed in detail later)
An optional x to indicate a capture was made
The square to which the rook moved (the columns ["files" in chess] are lettered a-h and the rows ["ranks"] are numbered 1-8)

Disregarding disambiguation, we have the simple
/Rx?[a-h][1-8]/

Disambiguation
It often happens that two rooks can move to a square, and one does. When this happens, a disambiguating letter or number is used. So, if two rooks are on d3 and h5, and the one on h5 moves to d5, it is written Rhd5. Similarly, a rook on d8 moving to d3 when another rook is on d1 is written R8d3.
Files take precedence over ranks. In the first example, if the rook on d3 moved to d5, it could be disambiguated as R3d5 or Rdd5. Only the latter is correct.
The limits on rook disambiguation are:

Any letter may be used for file disambiguation, and
Any number may be used for rank disambiguation, but the number of the square moved to must not be 1 or 8 (R3d1 is not valid because of files' precedence over ranks and should be Rdd1), and it must not be the same number as the number of the square (R3d3 is also invalid)

With the above in mind, I constructed this:
/R([a-h]?x?[a-h][1-8]|([1-8])x?[a-h][2-7&&[^\1]])/

The problem lies in the last characters, [2-7&&[^\1]]. Ruby interprets [^\1] literally, that is as all characters other than \ or 1. If I try putting the \1 outside the brackets ([2-7&&[^]\1]), Ruby complains about the character class with no elements. And if I use an arbitrary placeholder that will never occur, say "z" ([2-7&&[^z]\1]), it doesn't work (I can't explain why)
So how can I use grouping to NOT match what I matched before?
Answer: Your question is long and dense, so I will address the core question and let you implement the technique:

How can I use grouping to NOT match what I matched before?

We'll proceed step by step. The following is not an exact chess example, but an illustration of how to accomplish what you want.

Let's say I want a string that matches letters a through h. My regex is ^[a-h]$
Next I want to match a digit and a dash. My regex becomes ^[a-h][0-9]-$
Next I want to match a letter, but not the one we matched before. My regex becomes ^([a-h])[0-9]-(?!\1)[a-h]$, where the ([a-h]) captures the first letter to Group 1, and the negative lookahead (?!\1) asserts that what follows is not the content of what was matched by Group 1 (i.e., it is not that letter).
Let's add a final digit just for balance: ^([a-h])[0-9]-(?!\1)[a-h][0-9]$. This will match a1-b2 but not a1-a2.

Let me know if you have any questions.
Reference

Lookahead and Lookbehind Zero-Length Assertions
Mastering Lookahead and Lookbehind
Comment: While `([1-8])x?[a-h](?!\1)[2-7]` works by itself, the full regex `/R([a-h]?x?[a-h][1-8]|([1-8])x?[a-h](?!\1)[2-7])/` incorrectly matches `R5d5`. Is there a way to make this work with `|`?
Comment: In that regex of yours, for R5d5, Group1 is `5d5` and Group 2 is `5`. Not sure what you're trying to do, but either of these three methods will fix it: (1) change the `\1` to `\2` OR (2) remove the outer parentheses (you're not using them) OR (3) make them non-capturing with `(?:`..... Might get off the computer for while but let me know how you go


Normalization in SVM

Question: I have applied libsvm with a linear kernel to a set of instances and I have obtained a 68 % success:
instance1 : f11, f12, f13, f14
instance2 : f21, f22, f23, f24
instance3 : f31, f32, f33, f34
instance4 : f41, f42, f43, f44
..............................
instanceN : fN1, fN2, fN3, fN4

Taking the same set of instances but multiplying each value (f11*1000 ... fN4*1000) I have obtained a 90% of success.
However, I the multiplied by 1000 is normalized the percentatge of success turn to 68%.
It seems something related with normalization but I don't know which it is the reason.
Answer: Your solution changes because you scale all features but you neglect to rescale the misclassification penalty $C$. The SVM cost function is as follows:
$$
\min \|\mathbf{w}\|^2 + C \sum_i \xi_i
$$
where $\mathbf{w}$ is the separating hyperplane, $\xi$ is a vector of slack variables associated to misclassification of training instances and $C$ is a parameter you must set as a user.
When you multiply all features by $1000$, $\|\mathbf{w}\|^2$ will be $1000^2$ times larger. You forgot to change $C$, which basically means that misclassifications of training instances are no longer penalized appropriately. If you rescale $C$ correctly you will end up with the same model.
If $C$ is far too small, the minimization problem becomes almost identical to minimizing $\|\mathbf{w}\|$ (which is a useless result). The result is a very simple model which isn't informative e.g. $\|\mathbf{w}\|\approx 0$.
If $C$ is far too large, the resulting model will be overly complex (e.g. $\|\mathbf{w}\|$ very large). Such a model overfits the training set and exhibits poor generalization performance. This is symptomized by high training set accuracy and poor test set accuracy (which is also a useless result).
Answer: The normalization in SVM is to subtract mean and divided by standard deviation. If you multiply your data (both training and testing) by the same ratio, after the normalization you should have still exactly the same values as the normalized original data. Are you sure you multiplied both training and testing data?
Comment: Could it be some numerical effect. If your data is highly concentrated around zero for many cases, but then some part of your data is far away, maybe it results on lost of accuracy. By multiplying by 1000, you would mitigate such problem.
Comment: After the normalization I have the same pecentatge of success turn to 68%.
Comment: However, the main question is why is the reason to obtain 68% success with original values and 90% of success with the original data * 1000.
Comment: If you don't do normalization to the original data, what success rate will you get? I suppose it has something to do with the normalization, normalization do not always improve your accuracy given different distributions of the data.
Answer: SVM uses Stochastic Gradeint Descent (SGD) or Gradient Descent (GD) algorithm for optimation.
If we look SGD:
$$
\triangledown (j, i) = w^{(j)} + C \frac{\partial L(x_{i}, y_{i})}{\partial w^{(j)}}
$$
so, it depends on input values.
It you multiply input values some big constant you increase convergence speed of the optimization problem. Therefore, you will get %90 accuracy. If you iterate enough, you will get same accuracy without multiplication of input.

Normalization in SVM


How to refresh my table on a time-out function of 3 seconds

Question: I am having difficulty with refreshing only my table in my index page of the mvc5 application on a time-out of 5 seconds. I have read quite a few posts about it here but my understanding is very basic.
I have an ActionResult called Index that returns a stored procedure to populate a dropdown list when I select a value and submit it I have another controller called Index but it has [HttpPost] above it, this now saves the selected value of the dropdown passes it to another stored proc and returns a model to the view to create a table. I want to refresh this table on a time out of 5 seconds. I have tried to first refresh with a button using the following below.

<input id="butt" type="submit" value="Go" />

Here is my controller:
DBEntities  db = new DBEntites();

public ActionResult Index()
{
    CircuitClass model = new CircuitClass();

    model.MyCircuit = db.GetAllCircuits(DateTime.Today);
    return View(model);
}

[HttpPost]
public ActionResult Index(CircuitClass model)
{
    string circuit = model.SelectedCircuit.ToString();
    int raceNo = model.SelectedRaceNo;
    if (model.SelectedRaceNo == 0 || (model.SelectedCircuit == null))
    {
      return View("~/Views/Shared/Error.cshtml");
    }
    else
        model.MyResults = db.GetCircuitResults(circuit, raceNo, DateTime.Today).ToList();
    model.MyCircuit = db.GetAllCircuits(DateTime.Today);

    return View(model);
}

In debug, I press the button which takes me to the Index controller that doesn't have [HttpPost] above it which is where I need to refresh the table. I was expecting it to load the controller with [HttpPost].
My approach may be completely wrong, can anyone help?
Answer: Use setInterval function from  js to call display function every 5 seconds
$("#butt").on('click', display());

function display()
{
    $.ajax({
        url: '/Home/Index',
        success: function (data) {
            $("#refresh").html(data);
        }
    })
}

setInterval(function(){ display(); }, 5000); //Refreshes every 5 sec

(Or) trigger the button click every 5 sec
$("#butt").click(function () {
    $.ajax({
        url: '/Home/Index',
        success: function (data) {
            $("#refresh").html(data);
        }
    })
})

setInterval(function(){  $("#butt").trigger('click') }, 5000);

Comment: Add `[HttpPost]` data annotation above given method in given controller and add `method: post` to your [ajax](http://api.jquery.com/jquery.ajax/#entry-examples) call. @KidKoder
Comment: Hi Deepak, Thank you for your response, I would like it to be without a button if possible, I was trying with a button to learn how it works - my goal is to have it refresh on a timer alone. Also, the big issue is the controller part of my question, how do i have it go to the index controller with [HttpPost] above it? Thank you
Comment: @Barrosy Thank you for the response, putting the method: post, it worked.


Continued fraction estimation of error in Leibniz series for $\pi$.

Question: The following arctan formula for $\pi$ is quite well known
$$\frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \cdots\tag{1}$$ and bears the name of Madhava-Gregory-Leibniz series after its discoverers. The formula has an easy proof via integration. While reading a paper by Ranjan Roy titled "The Discovery of the Series Formula for $\pi$ by Leibniz, Gregory and Nilakantha" I was surprised to find that error in approximation via $n$ terms of series $(1)$ can be expressed in terms of a continued fraction studied by both Rogers and Ramanujan.
Let $$f(x) = \cfrac{1}{x +\cfrac{1^{2}}{x +\cfrac{2^{2}}{x +\cfrac{3^{2}}{x + \cdots}}}}\tag{2}$$ for $x > 0$ and let $n$ be a positive integer. Let us define $S_{n}$ by $$S_{n} = \sum_{i = 1}^{n}(-1)^{i - 1}\cdot\frac{1}{2i - 1}$$ so that $S_{n}$ is the $n^{\text{th}}$ partial sum of series $(1)$. Then we have the formula $$\frac{\pi}{4} = S_{n} + (-1)^{n}\cdot\frac{f(2n)}{2}\tag{3}$$ The formula above is so marvelous that first 2-3 convergents of the continued fraction $(2)$ are sufficient to give a very good approximation of $\pi$ for small values of $n$. For example if $n = 4$ so that $$S_{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} = \frac{2}{3} + \frac{2}{35} = \frac{76}{105}$$ and taking 3rd convergent of $f(8)$ we see that $$f(8) \approx \cfrac{1}{8 +\cfrac{1^{2}}{8 +\cfrac{2^{2}}{8}}} = \frac{17}{138}$$ and hence $$\frac{\pi}{4} = S_{4} + \frac{f(8)}{2} \approx \frac{76}{105} + \frac{17}{276} = 0.78540372670807$$ which is greater than $\pi/4$ by approximately $5.5 \times 10^{-6}$ so that the approximation is really great.

I would like to know the proof of identity $(3)$. Any reference for the proof would also be helpful.

Update: Sorry people! I found the answer myself when I used the information in related link about the continued fraction $f(x)$. See my answer below.

On the other hand I would be more than happy if we can obtain a proof of $(3)$ without using Rogers proof mentioned in my answer. Perhaps there was some simpler proof available with Nilkantha.
Comment: Concerning the error in Gregory's series I found this $1989$ article by the Borweins and Dilcher rather neat ["Pi, Euler Numbers, and Asymptotic Expansions"](http://www.cecm.sfu.ca/personal/pborwein/PAPERS/P45.pdf) (if you didn't know it...). Cheers,
Comment: Thanks @RaymondManzoni for the nice paper.
Answer: We have
\begin{align}
\frac{\pi}{4} &= \int_{0}^{1}\frac{dt}{1 + t^{2}}\notag\\
&= \int_{0}^{1}\left(1 - t^{2} + \cdots + (-1)^{n - 1}t^{2n - 2} + (-1)^{n}\frac{t^{2n}}{1 + t^{2}}\right)\,dt\notag\\
&= 1 - \frac{1}{3} + \cdots + (-1)^{n - 1}\frac{1}{2n - 1} + (-1)^{n}\int_{0}^{1}\frac{t^{2n}}{1 + t^{2}}\,dt\notag\\
&= S_{n} + (-1)^{n}g(n)\text{ (say)}\notag
\end{align}
Then we have
\begin{align}
g(n) &= \int_{0}^{1}\frac{t^{2n}}{1 + t^{2}}\,dt\notag\\
&= \int_{0}^{\infty}\frac{e^{-2nz}}{1 + e^{-2z}}\frac{dz}{e^{z}}\text{ (by putting }t = e^{-z})\notag\\
&= \frac{1}{2}\int_{0}^{\infty}\frac{e^{-2nz}}{\cosh z}\,dz\notag\\
&= \frac{f(2n)}{2}\notag
\end{align}
We have $$f(x) = \int_{0}^{\infty}\frac{e^{-zx}}{\cosh z}\,dz$$ from here.
Note: While the only proof of the link between continued fraction $f(x)$ and the corresponding integral which I have is the one by Rogers (see linked question for more details on Rogers paper), I strongly believe that the continued fraction $f(x)$ was also known to Nilkantha. In fact Ranjan Roy mentions in his paper (referred in my question) that Nilkantha used "some procedure" which gave successive convergents to the continued fraction $f(x)$. I therefore believe that Nilkantha did have a proof of the link between continued fraction $f(x)$ and its integral representation well before Rogers (say in 15th-16th century).


What does the standard say about unaligned memory access?

Question: I've searched through the standard about unaligned access, but didn't find anything (maybe I was inadvertent).
Is it undefined behavior? Is it implementation defined?
As a lot of current CPUs support unaligned access, it would be sensible that unaligned memory access is implementation defined. Is it the case?
By unaligned access, I mean for example:
alignas(int) char buffer[sizeof(int)+1];
int &x = *new(buffer+1) int;
x = 42;

Comment: I think the relevant section is **[basic.align]**. Implementation-defined.
Comment: @RaymondChen: all I found is that alignment value is implementation defined. But nothing about unaligned access. Do you see something else there?
Comment: How do we know that this is an unaligned access? `sizeof(int)` and the required alignment are both implementation defined. Could be the same as for `char`.
Answer: No, it is UB. You cannot start the lifetime of an object at unaligned memory. From [basic.life]p1

The lifetime of an object of type T begins when:

storage with the proper alignment and size for type T is obtained, and

if the object has non-vacuous initialization, its initialization is complete,

[...]

So in your example, the lifetime of the object referenced by x doesn't even begin, so any other usage of it other than mentioned in [basic.life]p6 is UB.
But what your implementation is allowed to do is say that unaligned memory (as specified by the underlying architecture used) is actually aligned, thus making your code valid under the C++ abstract machine. I'm not sure whether any compiler does this however.
Comment: @MaximEgorushkin Whatever compiler developers decide it should return. It could return `1`, or it could (as on my GCC) return `4`. If hardware allows misaligned access with a performance overhead, the implementation can still return `4` to make (most) integers aligned, improving performance.
Comment: @MaximEgorushkin It's probably the alignment that `alignof` returns.
Comment: @geza It is explicit. The abstract machine doesn't care about alignement of the underlying HW. If the compiler says that the memory is unaligned, then you get UB no matter the HW.
Comment: @geza I understand proper as "right", which is what alignof returns. It could be improved, I agree.
Comment: @MaximEgorushkin: that's true, but does it matter? Suppose that the requirement is 4. Does my example's behaviour implementation defined, or UB? Reading the quoted part, I think that Rakete1111 is right, and it is UB indeed, because `new int` is called on an unaligned pointer.
Comment: @MaximEgorushkin Here by compiler I mean an entire tool that makes object files from C++ source code.
Comment: You only need to provide a definition of _proper alignment_ now.
Comment: @HolyBlackCat Quote the standard please.
Comment: @MaximEgorushkin Are you trying to say that there is a possibility that `alignof` returns optimal rather than required alignment? The standard doesn't mention 'proper alignment' anywhere else, the closest thing I was able to find is [`[basic.align]/2`](http://eel.is/c++draft/basic.align#2) *"The result of the alignof operator reflects the alignment requirement ..."*.
Comment: @HolyBlackCat: but according to the standard, alignof means required alignment (3.11.6 of C++14). So, implementations with `alignof(int)==4` give us a more strict alignment than necessary.
Comment: @Rakete1111: my only problem is that it says "proper alignment", not "required aligment" (which equals to `alignof`). Not a big deal, I agree with your conclusion, all I'm saying is that sentence can be improved a little bit
Comment: The alignment requirement is, however, an implementation defined property.
Comment: @MaximEgorushkin Yes it is implementation defined. But that doesn't change the fact that if that requirement is violated, no matter what it is, then you get UB, which is AFAIK exactly what OP does by adding 1.
Comment: @geza Suppose the implementation has best performance if 4-byte integers are alinged by 4-byte boundary. But it can handle unaligned access just fine. What should `alignof(uint32_t)` return?
Comment: @HolyBlackCat You don't have to develop a compiler to return that `1`. Just a back-end https://llvm.org/docs/WritingAnLLVMBackend.html
Comment: @Rakete1111 Actually, [basic.align]/2 has an interesting part in it: *"The alignment required for a type might be different when it is used as the type of a complete object and when it is used as the type of a subobject. ... The result of the alignof operator reflects the alignment requirement of the type in the complete-object case."* So one could say that you're allowed to access misaligned compound types under certain conditions.
Comment: @HolyBlackCat: in the case of x86, it certainly returns optimal alignment, as there is no required alignment on x86 (except a few special cases). Almost all variables could use an alignment of 1, and even, there would be no significant speed loss.
Comment: @geza At the risk of stating the obvious, an implementation is free to impose a stricter alignment requirement than the underlying hardware. Also, hardware-unaligned access has obvious issues with `volatile` semantics on x86 (apart from "real" hardware access, this is very relevant for [`sig_atomic_t`](https://en.cppreference.com/w/c/program/sig_atomic_t)).
Comment: @ArneVogel: the question is then, is a memory access is UB, when the memory access is aligned from the perspective of the HW, but unaligned from the perspective of the C++ abstract machine? It seems that the answer is yes, but it is not 100% explicit in the standard.


Expressão regular para extrair números de "200#5;300#10"

Question: Qual seria a melhor expressão regular para a seguinte entrada "200#5;300#10" ?
Comment: Depende do que queres selecionar... Podes explicar melhor o que queres fazer?
Comment: O 200 significa o total de encomenda e 5 o desconto, o # é só o separador, ou seja primeiro total, depois # e depois desconto, e por fim ponto e virgula para separar de outra condição.
Answer: Vai precisar de dois grupos de captura. Partindo do princípio que só tem digitos, podes usar assim:
/(\d+)#(\d+)/

O \d representa "dígito", e o + quer dizer "um ou mais". Os parenteses indicam grupos de captura, e o # indica exatamente o caracter #.
Um exemplo seria: http://ideone.com/wl3Q77
$string = "200#5;300#10";
preg_match_all('/(\d+)#(\d+)/', $string, $matches);
var_dump($matches);

// resultado:
array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "200#5"
    [1]=>
    string(6) "300#10"
  }
  [1]=>
  array(2) {
    [0]=>
    string(3) "200"
    [1]=>
    string(3) "300"
  }
  [2]=>
  array(2) {
    [0]=>
    string(1) "5"
    [1]=>
    string(2) "10"
  }
}

Comment: Valeu Sérgio! Obrigado pela explicação!


Show that single-tape TMs that cannot write on the portion of the tape containing the input string recognizes only regular languages.

Question: The question and its answer is given in the following pictures:

But I do not know why he named the function he used as a characteristic function?and the intuition behind the definition the author gave to it is not clear for me?  could anyone explain this for me please?
Answer: I agree that this can be a puzzling way to explain the situation. The point of this proof is to say:

Because of the read-only restriction, it turns out a TM with a read-only tape has a finite list of features it can learn about its input.  (I'll explain what these features are later.)
Once you know those features, you know everything the TM can know about the input.
Evidently, $M$ treats strings with the same feature-list in the same way. It can't tell them apart. If $x$ and $y$ are two strings with the same features, and $z$ is any other string, then $M$ treats $xz$ and $yz$ the same way (both accept or both reject).
In fact, both $xz$ and $yz$ have the same feature-list.
So, the corresponding DFA looks like this: the states correspond to the different feature-lists that words can have. The transition rule is like this: if you're on state $q$, that's a particular feature-list. Let $w$ be a word with that feature-list. On input $a$, go to the feature list for word $wa$. Because of the property in the previous bullet-point, this feature-list is well-defined.

Details follow.

The main point is that a TM with a read-only input is "very forgetful". A Turing Machine has two ways to remember: the state of its deterministic control, and whatever information it writes onto the tape.

Let's ask: when the TM moves from the input region into the writeable region, what information does it retain about the input string $x$?  Because the TM can't write anything down, the only information it retains is whatever state it's currently in as it exits the read-only region. $M$ can write down that state onto the tape. $M$ doesn't remember anything else about the input (!).

Later, $M$ might go back into the read-only region. As before, whatever it does in that region, its only memory upon exiting will be whatever state $q^\prime$ it's finally in. (Note that it can't even reference its notes while it's in the read-only region.) $M$ doesn't remember anything else about the input.

This is the way that $M$ can extract information about the input: it dives into the read-only region, changes its state purely based on the input characters (it can't reference its written notes), then emerges in a particular state. It can write down that state; that state is the only memory it has about the input.

Because $M$ can't reference its written notes, there's an unchanging functional relationship $f(x,q)=q^\prime$: If $M$ enters the read-only region while in state $q$, and the read-only region has input $x$ in it, then $M$ will always exit the read-only region (or terminate within the read-only region) in state $q^\prime$.  This function never changes because $M$ can never change the input, and its only instruction for what to do there comes from $x$ and $q$. This function doesn't care what $M$ has written on the tape because $M$ can't reference it when on the read-only section.

Hence for each input $x$, you can fill out a table like this:
$$\begin{array}{r|l}\text{state when entering read-only} & \text{state when exiting} \\\hline q_1\\q_2\\q_3\\\vdots\\q_n\end{array}$$

Fill out the right-hand column by listing different states. If $M$ never exits the region, what should you write? Because the machine never leaves, it either accepts or halts. As a default answer, put $q_{accept}$ or $q_{reject}$ accordingly.
Add a final row for what happens at the very beginning when the TM starts in the read-only region (see point 2 above). Now the table contains all of the information about the string that $M$ is able to remember. It contains all of the information about the string that $M$ can write down on its writeable tape.

This table characterizes the complete behavior of $M$ on the input $x$. This table contains everything $M$ can ever learn about its input. Even what $M$ writes down on the writeable tape is fully determined by this table. Whether $M$ accepts or rejects is also determined by this table.

In particular, we have the following extension property: if $x$ and $y$ have the same table, then for any string $z$, $xz$ and $yz$ have the same table. ($M$ has no way to tell $x$ and $y$ apart, so it has no further way to tell $xz$ and $yz$ apart, so it behaves identically on both.) By the Myhill-Nerode theorem, the language of $M$ must be regular.

More concretely, if $M$'s behavior on $x$ is completely determined by the table for $x$, and if $xz$ and $yz$ always have the same table whenever $x$ and $y$ do, we can make a DFA for $M$ like this:

Let the states of the DFA correspond to these different possible tables (there are $|Q|^{|Q|+1}$ different possible tables. This is because there are $|Q|+1$ rows in the table, and any state in $Q$ can be an entry in the right column.) The starting state is the table for the empty word. The transition rule is well-defined because extensions $xz=yz$ of words with the same table have the same table. The accept and reject states are well-defined because you can tell whether $M$ will accept or reject the word $x$ based on the table for $x$.
Comment: point 5 you mentioned "If M enters the read-only region while in state q, and the read-only region has input x in it, then M will always **exit the read-only region** in state q′". but i could be the case that head of turing machine do not leave read-only region and and $f(x,q) $be either $q_{acc}$ or $q_{rej}$.
Comment: @mike Thank you. I've rewritten it to clarify.


Cannot get GeoJSON to Render

Question: I'm a novice with both javascript and leaflet. I have recently been trying to create an interactive map using leaflet, using the map located here as a template:
http://palewi.re/posts/2012/03/26/leaflet-recipe-hover-events-features-and-polygons/
While I am successfully able to import tiling, I am continually running into problems in importing geojson layers into the map, and cannot get them to render.I have posted both scripts below:
HTML:
<!DOCTYPE html>`enter code here`

    <title>Leaflet GeoJSON example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4/leaflet.css" />

>

geoJSON:
var aidpoints = {
"type": "FeatureCollection",

"features": [
{ "type": "Feature", "properties": { "OJD": 1, "KRCS-MNCH": "Kopro", "ACTED": "Kokwotendwo", "Proposed": "Kopro ", "Partner": "ACTED\/ KRCS", "N": 1.37851, "E": 35.41787, "Elevation": 1410, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.41787, 1.37851 ] } },
{ "type": "Feature", "properties": { "OJD": 2, "KRCS-MNCH": "Nyangaita", "ACTED": "Nyangaita", "Proposed": "Nyangaita", "Partner": "ACTED\/ KRCS", "N": 1.48371, "E": 35.67432, "Elevation": 957, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.67432, 1.48371 ] } },
{ "type": "Feature", "properties": { "OJD": 3, "KRCS-MNCH": "Akiriamet", "ACTED": "Akiriamet", "Proposed": "Akiriamet", "Partner": "KRCS", "N": 1.60502, "E": 35.4913, "Elevation": 8178, "ACTED Community groups": "None ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.4913, 1.60502 ] } },
{ "type": "Feature", "properties": { "OJD": 4, "KRCS-MNCH": "Mbara", "ACTED": "Mbara", "Proposed": "Mbara", "Partner": "ACTED\/ KRCS", "N": 1.59418, "E": 35.3976, "Elevation": 2054, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.3976, 1.59418 ] } },
{ "type": "Feature", "properties": { "OJD": 5, "KRCS-MNCH": "Chepkpndol", "ACTED": "Chepkondol", "Proposed": "Chepkondol", "Partner": "ACTED\/ KRCS", "N": 1.67887, "E": 35.42537, "Elevation": 1814, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.42537, 1.67887 ] } },
{ "type": "Feature", "properties": { "OJD": 6, "KRCS-MNCH": "Sostin", "ACTED": "Sostin", "Proposed": "Sostin", "Partner": "ACTED\/ KRCS", "N": 1.59189, "E": 35.40917, "Elevation": 1967, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.40917, 1.59189 ] } },
{ "type": "Feature", "properties": { "OJD": 7, "KRCS-MNCH": "Orwa", "ACTED": "Orwa", "Proposed": "Orwa", "Partner": "ACTED\/ KRCS", "N": 1.65612, "E": 35.48684, "Elevation": 883, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.48684, 1.65612 ] } },
{ "type": "Feature", "properties": { "OJD": 8, "KRCS-MNCH": "Porkoyu", "ACTED": "Parek", "Proposed": "Porkoyu ( KRCS)", "Partner": "KRCS", "N": 1.80412, "E": 35.420852, "Elevation": null, "ACTED Community groups": "None ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.420852, 1.80412 ] } },
{ "type": "Feature", "properties": { "OJD": 9, "KRCS-MNCH": "Mosop", "ACTED": "Kokwoptorir", "Proposed": "Kokwoptorir \/Mosop", "Partner": "ACTED\/ KRCS", "N": 1.38609, "E": 35.52468, "Elevation": 1588, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.52468, 1.38609 ] } },
{ "type": "Feature", "properties": { "OJD": 10, "KRCS-MNCH": "Cheptulel", "ACTED": "Kokwositot &Lebei", "Proposed": "Kokwositot \/Cheptulel", "Partner": "ACTED\/ KRCS", "N": 1.33488, "E": 35.62769, "Elevation": 999, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.62769, 1.33488 ] } },
{ "type": "Feature", "properties": { "OJD": 11, "KRCS-MNCH": "Ptokou", "ACTED": "Ptokou", "Proposed": "Ptokou", "Partner": "ACTED\/ KRCS", "N": 1.4544, "E": 35.47972, "Elevation": 997, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.47972, 1.4544 ] } },
{ "type": "Feature", "properties": { "OJD": 12, "KRCS-MNCH": "Sangat", "ACTED": "Sangat", "Proposed": "Sangat", "Partner": "ACTED\/ KRCS", "N": 1.44543, "E": 35.4677, "Elevation": 1011, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.4677, 1.44543 ] } },
{ "type": "Feature", "properties": { "OJD": 13, "KRCS-MNCH": "Takar", "ACTED": "Takar", "Proposed": "Takar", "Partner": "ACTED\/ KRCS", "N": 1.4312, "E": 35.62, "Elevation": 1046, "ACTED Community groups": "VPCs, APFS & VICOBA ", "KRCS Community groups": "Health facility " }, "geometry": { "type": "Point", "coordinates": [ 35.62, 1.4312 ] } }

I have tried reformatting the file to a .js. In addition, I have tried to load the geoson file using different methods here: http://leafletjs.com/examples/geojson.html. I have also tried switching the positions of latitude and longitude in the geojson file.
However, I just can't seem to figure out what is wrong.Does anyone have any ideas of what I'm doing wrong?
`
Answer: Your GeoJSON is missing two brackets at the end.
Add ]} and it should work.
I suggest to check with http://jsonlint.com/ and http://geojsonlint.com/ the geojson validity.

Cannot get GeoJSON to Render


How to determine moving window size?

Question: I am using moving window technique for data analysis...
For example I compute the mean,  the standard deviation and etc. for a given window.
And I wonder if there's any good criterion to determine window size...
I thought of computing multivariate variance of mean, sd, and etc. and
select the window size that minimize the variance...
But for the most of cases, the longer the window size, the smaller the variance...
So I am stuck... Is there any criterion that can solve the problem of determine the
window size or I have to go with my eyes and pick one that best entertain my eyes?
Comment: What kind of "data analysis" are you performing? What are you estimating, predicting, or deciding? (The answer depends on that context.)
Answer: I agree with whuber. You should have some methodology, for example bootstrapping and stability criterion (that is perturb your data a little bit and check that your estimates do not change too much), or better sharp theoretical results, to help you decide if you have enough samples to compute your estimates correctly.
Then, you should use the minimum amount of data that provides you strong guarantee (theoretical or empirical) on the relevance of your results, but no more as you will smooth the signal (or violate even more the stationary hypothesis).
As long as you stay with estimating mean, variance, and so on, you should be able to find theoretical results and guidelines. If you want to determine the minimum length of the window for a complex processing (say machine learning algorithms), you should go for an empirical study, cf. this study for an example on the clustering of correlated random variables.
Comment: This is probably a good answer for some but ignores the context clues that point to what a useful answer would look like to the asker. The question is asked by someone who is relatively new. They know how to calculate a rolling window with code and may even know how to do the math on paper. However, they likely not equipped to understand a lot of technical terminologies found in research papers, or the deeper aspects of statistics. This sort of answer is prohibitive to those who may deeply desire to learn more rather than being bombarded with resources they can't use.  I.e: Me, and the OP.
Answer: Generally one picks the size of a sliding window that captures enough of information. Pick it too big, you will get more irrelevant information (loss of resolution). Pick too small, you will loose details.
You can see this following way. Suppose you have some real-valued function as a mixture of sinusoids with different periods. Picking a window size of length L will restrict you to a subset of functions that you will be able to extract.
Comment: After running a moving median, SD, mean, etc. it improves estimates to run the result through a _loess_ or "super" smoother (e.g. `supsmu` function in R).  So the window size can be fairly small.  We still need guidance for how large a window and how much post-moving smoothing is optimal.
Answer: I've done some thinking about this in a different context and came up with an approach that seemed reasonable intuitively, although I have a compsci rather than stats background.
The motivation for a smaller window size is increased sensitivity to changes in the underlying process from which you are sampling.  I'll call this "predictive value".
Let's say they are both expressed in units of the predictive value or predictive error we expect due to the bias or variance respectively.
The motivation for a larger window size is decreased noise due to small sample size.  This is the sample standard deviation:
standard_deviation(samples_in_window) / sqrt(size(samples_in_window))
On the predictive value side, this is the difference between the mean of all samples and the mean of samples within the window.
So, our task is to select the window size that maximizes predictive accuracy, which is the predictive value minus the predictive error.
This can be implemented quite efficiently with a little thought, and if so the window size could be re-computed every time we receive a new sample - allowing it to dynamically adapt the window size over time.
Note that this entire approach is nonparametric, so it doesn't just substitute one parameter, window size, for another parameter or parameters.

How to determine moving window size?


Spring MVC REST JSON

Question: To tendo um problema, no meu controller quando tenho alguma entidade com relacionamento ele não me devolve o JSON, já tente colocar o @JsonIgnore nos get das entidade referências mas nada, segue o código.
@Entity
@Table(name="tb_consumer")
public class Consumer implements Serializable{

    private static final long serialVersionUID = 3474427923296664130L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    private String address;

    private String city;

    @Column(name="city_uf")
    private String cityUf;

    @Column(name="code_postal")
    private int codePostal;

    private String complement;

    private int cpf;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="date_created")
    private Date dateCreated;

    private String name;

    @Column(name="phone_cell")
    private String phoneCell;

    @Column(name="phone_home")
    private String phoneHome;

    @Column(name="phone_work")
    private String phoneWork;

    @ManyToMany(mappedBy="consumers")
    private Set<Buy> buys = new HashSet<Buy>();

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="tb_status_id")
    private Status status;

//getters e setters

Meu Controller:
@Controller
@RequestMapping(value = "/protected/users/consumers")
public class ConsumersController {

    private static final String DEFAULT_PAGE_DISPLAYED_TO_USER = "0";

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private MessageSource messageSource;

    @Value("5")
    private int maxResults;

    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<?> listAll(@RequestParam int page, Locale locale) {
        return createListAllResponse(page, locale);
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView welcome() {
        return new ModelAndView("consumersList");
    }

    @RequestMapping(method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<?> create(@ModelAttribute("consumer") Consumer consumer,
                                    @RequestParam(required = false) String searchFor,
                                    @RequestParam(required = false, defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page,
                                    Locale locale) {
        consumerService.save(consumer);

        if (isSearchActivated(searchFor)) {
            return search(searchFor, page, locale, "message.create.success");
        }

        return createListAllResponse(page, locale, "message.create.success");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = "application/json")
    public ResponseEntity<?> update(@PathVariable("id") int consumerId,
                                    @RequestBody Consumer consumer,
                                    @RequestParam(required = false) String searchFor,
                                    @RequestParam(required = false, defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page,
                                    Locale locale) {
        if (consumerId != consumer.getId()) {
            return new ResponseEntity<String>("Bad Request", HttpStatus.BAD_REQUEST);
        }

        consumerService.save(consumer);

        if (isSearchActivated(searchFor)) {
            return search(searchFor, page, locale, "message.update.success");
        }

        return createListAllResponse(page, locale, "message.update.success");
    }

    @RequestMapping(value = "/{consumerId}", method = RequestMethod.DELETE, produces = "application/json")
    public ResponseEntity<?> delete(@PathVariable("consumerId") int consumerId,
                                    @RequestParam(required = false) String searchFor,
                                    @RequestParam(required = false, defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page,
                                    Locale locale) {

        try {
            consumerService.delete(consumerId);
        } catch (AccessDeniedException e) {
            return new ResponseEntity<Object>(HttpStatus.FORBIDDEN);
        }

        if (isSearchActivated(searchFor)) {
            return search(searchFor, page, locale, "message.delete.success");
        }

        return createListAllResponse(page, locale, "message.delete.success");
    }

    @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<?> search(@PathVariable("name") String name,
                                    @RequestParam(required = false, defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page,
                                    Locale locale) {
        return search(name, page, locale, null);
    }

    private ResponseEntity<?> search(String name, int page, Locale locale, String actionMessageKey) {
        ConsumerListVO consumerListVO = consumerService.findByNameLike(page, maxResults, name);

        if (!StringUtils.isEmpty(actionMessageKey)) {
            addActionMessageToVO(consumerListVO, locale, actionMessageKey, null);
        }

        Object[] args = {name};

        addSearchMessageToVO(consumerListVO, locale, "message.search.for.active", args);

        return new ResponseEntity<ConsumerListVO>(consumerListVO, HttpStatus.OK);
    }

    private ConsumerListVO listAll(int page) {
        return consumerService.findAll(page, maxResults);
    }

    private ResponseEntity<ConsumerListVO> returnListToUser(ConsumerListVO consumerList) {
        return new ResponseEntity<ConsumerListVO>(consumerList, HttpStatus.OK);
    }

    private ResponseEntity<?> createListAllResponse(int page, Locale locale) {
        return createListAllResponse(page, locale, null);
    }

    private ResponseEntity<?> createListAllResponse(int page, Locale locale, String messageKey) {
        ConsumerListVO consumerListVO = listAll(page);

        addActionMessageToVO(consumerListVO, locale, messageKey, null);

        return returnListToUser(consumerListVO);
    }

    private ConsumerListVO addActionMessageToVO(ConsumerListVO consumerListVO, Locale locale, String actionMessageKey, Object[] args) {
        if (StringUtils.isEmpty(actionMessageKey)) {
            return consumerListVO;
        }

        consumerListVO.setActionMessage(messageSource.getMessage(actionMessageKey, args, null, locale));

        return consumerListVO;
    }

    private ConsumerListVO addSearchMessageToVO(ConsumerListVO consumerListVO, Locale locale, String actionMessageKey, Object[] args) {
        if (StringUtils.isEmpty(actionMessageKey)) {
            return consumerListVO;
        }

        consumerListVO.setSearchMessage(messageSource.getMessage(actionMessageKey, args, null, locale));

        return consumerListVO;
    }

    private boolean isSearchActivated(String searchFor) {
        return !StringUtils.isEmpty(searchFor);
    }
}

Meu Vo
public class ConsumerListVO {

    private int pageCount;
    private long totalConsumers;
    private String actionMessage;
    private String searchMessage;
    private List<Consumer> consumers;
    private String systemUser;
    private String status;

    public ConsumerListVO(int pageCount, long totalConsumers, List<Consumer> consumers) {
        this.pageCount = pageCount;
        this.totalConsumers = totalConsumers;
        this.consumers = consumers;

    }

    public String getSystemUser() {
        return systemUser;
    }

    public void setSystemUser(String systemUser) {
        this.systemUser = systemUser;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setConsumers(List<Consumer> consumers) {
        this.consumers = consumers;
    }

    public ConsumerListVO() {

    }

Answer: Pessoal resolvi o problema,
Crie um vo para cada entidade minha
public class ConsumerVo{

    private int id;
    private String address;
    private String city;
    private String cityUf;
    private int codePostal;
    private String complement;
    private int cpf;
    private Date dateCreated;
    private String name;
    private String phoneCell;
    private String phoneHome;
    private String phoneWork;
    private Status status;

...getters e setters

Meu ListVo
public class ConsumerListVO {

    private int pageCount;
    private long totalConsumers;
    private String actionMessage;
    private String searchMessage;
    private List<ConsumerVo> consumers;
...getters e setters

Flw

Spring MVC REST JSON


Convert Multiple fields to DateTimeStamp

Question: Hi I have a MySql table that contains the following columns;
Year Month Day Time Temp
------------------------
2014 12    30  23.5  15.9
2014 12    31  00.0  13.2
2014 12    31  00.5  11.5

Data above is in 30 Min (Half hourly records).
Structure:
----------
Year   = int(4)
Month  = int(2)
Day    = int(2)
Time   = decimal(3,1)  "decimal 24hrs"
Temp   = decimal(3,1)

I need to query the table to return;
Timestamp Date/Time and Temp;e.g.
---------------------------------
2014-12-30 23:30:00   15.9
2014-12-31 00:00:00   13.2
2014-12-31 00:30:00   11.5

I can return the Date portion (and temp), however unable to convert/include the Time.
I am currently using;
SELECT concat(`Year`,'-',`Month`,'-',`Day`) AS `MyDateTimeStamp`, `Temp`
FROM `MyTable'

I've searched the threads and can not find similar example.
Thank you in advance,
regards
Tony
Comment: why don't you try `sec_to_time()`? (check answer below)
Answer: Try to use IF() function and probably FLOOR() function, like:
SELECT concat(`Year`,'-',`Month`,'-',`Day`,' ',
FLOOR(`Time`), IF((`Time`/FLOOR(`Time`))>1,' :30:00',' :00:00')) AS `MyDateTimeStamp`, `Temp`
FROM `myTable`

See Demo.
Comment: Hi Edper greatly appreciated, both yours and Barranka's work. Thank you.
Comment: Unbelievable, that works perfect, you are a legend greatly appreciated.
I tried using Floor, however could not fully understand it's use, this explains it - thank you.
Comment: Oops spoke too early, all that's being returned is 00:00 or 30:00 alternating every second row ?
Answer: To convert the time, use sec_to_time(). You'll need to convert that time to seconds.
Example: 23.5 is equivalent to 23:30:00, so, 23.5 / 24 is the fraction of day equivalent to that time. So: (23.5 / 24) * 24 * 60 * 60 = 23.5 * 60 * 60 is the number of seconds. Finally:
select sec_to_time(23.5 * 60 * 60);
-- Result: 23:30:00

So, to get the date/time:
select concat(concat_ws('-', `year`, `month`, `day`), ' ', sec_to_time(`time` * 60 * 60));

Comment: @TonyDow the best way to thank anybody else here is: 1. to upvote the useful posts (and downvote / flag those posts that are not good or require moderator attention), and 2. (even better) contribute with this site: ask good questions and post good answers. That way, this place will remain a "win-win" spot
Comment: Hi Barranka, first time I've used this site , not sure how to vote and thank you both Edper and Barranka.
Comment: Accept his answer. His answer admittedly is much better and efficient than mine. GOD bless.
Comment: @TonyDow Welcome to StackOverflow! Please take some time to [read the tour](http://stackoverflow.com/tour). As for the up/down voting: Use the triangle buttons at the left of each post. If an answer to a question you've made works and solves your problem, click on the check mark at the left of the answer to mark it as accepted. This is a "everybody is welcome" place, as long as you follow the simple rules stated in the tour and in the [help center](http://stackoverflow.com/help).


Looping variables or array

Question: I am creating some charts using chart.js with the context looking like this:
var ctx = document.getElementById('myChart');
var ctx2 = document.getElementById('myChart2');
var ctx3 = document.getElementById('myChart3');
var ctx4 = document.getElementById('myChart4');
var ctx5 = document.getElementById('myChart5');
var ctx6 = document.getElementById('myChart6');

is there a way I can write some form of loop instead of manually writing every single of them?
Comment: If you add a class to all of them, you can just do `var ctxArray = Array.from(document.querySelectorAll('.chart'));` The first one will be accessible with `ctxArray[0]`, the second one with `ctxArray[1]`, etc. and you can loop over them easily
Comment: `Element.getElementsByTagName()` => method returns a live HTMLCollection of elements with the given tag name.  Then you can use a for loop on the array.
Comment: What are the elements these ids represent?
Comment: Could you possibly share the representative html? Your question seems to be about efficient selectors, there may be an easier way to select the elements if we can see your html.
Answer: You could store each id selector in an array before looping over the array and making a selection to operate on...

const selectors = [
 '#myChart', '#myChart2', '#myChart3', '#myChart4', '#myChart5', '#myChart6'
]

selectors.forEach(selector => {
  const chart = document.querySelector(selector)
  console.log(chart)
  // do something
})

However, this is what css classes and querySelectorAll do very efficiently.

const myCharts = document.querySelectorAll('.chart')

myCharts.forEach(chart => {
  console.log(chart)
  // do something
})

Answer: You could compress the document.getElementById function which is a peeve for me too
const gEBID = document.getElementById;
var ctx = gEBID('myChart');
var ctx2 = gEBID('myChart2');
var ctx3 = gEBID('myChart3');
var ctx4 = gEBID('myChart4');
var ctx5 = gEBID('myChart5');
var ctx6 = gEBID('myChart6');

Looping variables or array


how to change the arrow direction of UIMenuController just before shown in an UIWebView

Question: I am trying to change arrow direction to be up so that when it appears it does not block a top bar I set for the application. Here is the code I used to change direction:
UIMenuController *menuController = [UIMenuController sharedMenuController];
[menuController setArrowDirection:UIMenuControllerArrowUp];

and here is the result, honestly say, it is pretty stressful:
It appears to be the same  issue on my iphone as well.
Can anyone look into this? Thanks
Answer: After days of researching, I finally find this way to change arrow direction of the menu controller in webview.
First, please do this in your view controller's viewDidLoad method.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerWillShow:) name:UIMenuControllerWillShowMenuNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerWillHide:) name:UIMenuControllerWillHideMenuNotification object:nil];

Then, add these two functions, then the arrow direction will always be pointing up, in which case the menubar will always appear below your text. (Same way, you can change UIMenuControllerArrowUp; to any other direction if you want your menubar to appear in other position)
-(void)menuControllerWillShow:(NSNotification *)notification{
    //Remove Will Show Notification to prevent
    // "menuControllerWillShow" function to be called multiple times
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIMenuControllerWillShowMenuNotification object:nil];

    //Hide the Original Menu View
    UIMenuController* menuController = [UIMenuController sharedMenuController];
    CGPoint origin = menuController.menuFrame.origin;
    CGSize size = menuController.menuFrame.size;
    CGRect menuFrame;
    menuFrame.origin = origin;
    menuFrame.size = size;
    [menuController setMenuVisible:NO animated:NO];

    //Modify its target rect and show it again to prevent glitchy appearance
    menuController.arrowDirection = UIMenuControllerArrowUp;
    [menuController setTargetRect:menuFrame inView:self.view];
    [menuController setMenuVisible:YES animated:YES];

}

-(void)menuControllerWillHide:(NSNotification *)notification{
    //re-register menuControllerWillShow
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerWillShow:) name:UIMenuControllerWillShowMenuNotification object:nil];
}

Comment: Great answer! There were oddly some edge cases where this did not work....I ran into instances where this would correctly move the arrow, and iOS would redraw it in the "correct" orientation almost-instantaneously.
Answer: According to the Apple Doc, arrowDirection sets the direction the arrow points; it has nothing to do with the location of the menu relative to its target area. It also looks like they don't give you any control over the positioning of the menu beyond setTargetRect:inView.
If you really want to put the menu below the text, you might be able to set a "fake" target area and change the arrow direction to point to the "real" area of interest.
However, there's probably a reason Apple does it this way. My guess? If you select some text with your finger, your hand is probably obscuring the part of the screen below the text... so it's not very helpful if the menu appears there. Going out of your way to break consistency with standard UI conventions isn't usually worth the effort.
once check this one
Comment: Is there any way I can override UIMenuController's update function so that I just set the arrow direction to up whenever it is showing? Cause here is the snippet from the description of Update function:    By default, UIMenuController calls this method just before the editing menu is made visible and when touches occur in the menu.


Making a window UI scroll down and deleting labels from frame

Question: I am making a random generator for my friends and I'm stuck trying to make a scroll down option. So if you generate more the window can show, a scroll down window should be possible. But I can't seem to get any to work. I've tried many online tutorials.
And my second issue with my code is that I can't clear the generated labels from the window. I got it working that it expands the window.
from cProfile import label
from pickle import FRAME
import random
import tkinter  as tk
from tkinter import BOTH, DISABLED, LEFT, RIGHT, VERTICAL, Y, Frame, Label, filedialog, Text
import os
from tkinter import ttk
from tkinter.font import NORMAL
from tkinter.messagebox import YES

root = tk.Tk()
root.title('guesser')

#Pelin arvonta ohjelma !

def delete():
   for child in root.children.values():
    info = child.grid_info()
    if info['column'] == 0:
        child.grid_forget()

def arvonta():
    global label
    list1 = []
    lista = ["Valorant","Rainbow","Vampire: The masquerade","Playerunknown's battlegrounds","Fortnite","Left 4 Dead 2","Counter strike Global offensive","Realm roayale","Black ops 1 zombies/multiplayer","Black ops 2 zombies/multiplayer","Black ops 3 zombies/multiplayer"]
    numero = random.randint(0, 10)
    hahmo  = (lista[numero])
    list1.append(hahmo)
    for app in list1:
        label = tk.Label(frame, text=app, bg="red",font=('Helvetica',20))
        label.pack()

def valorant():
    list2 = []
    lista2 = ["Brimstone","Viper","Omen","Killjoy","Cypher","Sova","Sage","phoenix","Jett","Reyna","Raze","Raze","Breach","Skye","Yoru","Astra","Kay/o","Chamber","Neon","Fade"]
    numero = random.randint(0, 19)
    randomValorantagent=(lista2[numero])
    list2.append(randomValorantagent)
    for app in list2:
        label = tk.Label(frame, text=app, bg="red",font=('Helvetica',20))
        label.pack()

def quitter():
    quit()

canvas = tk.Canvas(root,height=700,width=700,bg="#263D42")
canvas.pack(side=LEFT,fill=BOTH,expand=1)

frame = tk.Frame(root,bg="green")
frame.place(relwidth=0.8,relheight=0.8,relx=0.1,rely=0.1)
frame.pack(fill=BOTH,expand=1)

my_scrollbar = ttk.Scrollbar(frame, orient=VERTICAL, command=canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)

# Configure The Canvas
canvas.configure(yscrollcommand=my_scrollbar.set)
canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion = canvas.bbox("all")))

# Create ANOTHER Frame INSIDE the Canvas
second_frame = Frame(canvas)

# Add that New frame To a Window In The Canvas
canvas.create_window((0,0), window=second_frame, anchor="nw")

#rlls the game
openfile = tk.Button(second_frame,text="Roll a game",padx=10,pady=5,fg="white",bg="#263D42", command=arvonta)

openfile.pack()

#rolls a valorant agent
valorantA = tk.Button(second_frame,text='Roll valorant agent',padx=10,pady=5,fg="white",bg="#263D42",command=valorant)

valorantA.pack()

# stops program
stop = tk.Button(second_frame,text="Quit",padx=10,pady=5,fg="white",bg="#263D42",command=quitter)

stop.pack()

# deletes all info from screen.
deletor = tk.Button(second_frame,text="delete info",padx=10,pady=5,fg="white",bg="#263D42",command=delete)

deletor.pack()

root.mainloop()```

Comment: Right now the only thing that is scrollable is `second_frame`, not `frame` and you are putting all of the `Label`s in `frame`.
Answer: The following does most of what you want.  I wrote it some time ago to test Scrollbars because they are wonky IMHO
from tkinter import *
from functools import partial

class ButtonsTest:
   def __init__(self):
      self.top = Tk()
      self.top.title("Click a button to remove")
      self.top.geometry("425x200+50+50")
      Label(self.top, text=" Click a button to remove it ",
            bg="lightyellow", font=('DejaVuSansMono', 12)
            ).grid(row=0, sticky="nsew")

      Button(self.top, text='Exit', bg="orange", width=9,
             command=self.top.quit).grid(row=1,column=0,
             sticky="nsew")

      self.add_scrollbar()
      self.button_dic = {}
      self.buttons()

      self.top.mainloop()
   ##-------------------------------------------------------------------
   def add_scrollbar(self):
        self.canv = Canvas(self.top, relief=SUNKEN)
        self.canv.config(width=400, height=200)
        self.top_frame = Frame(self.canv, height=100)

        ##---------- scrollregion has to be larger than canvas size
        ##           otherwise it just stays in the visible canvas
        self.canv.config(scrollregion=(0,0, 400, 500))
        self.canv.config(highlightthickness=0)

        ybar = Scrollbar(self.top, width=15, troughcolor="lightblue")
        ybar.config(command=self.canv.yview)
        ## connect the two widgets together
        self.canv.config(yscrollcommand=ybar.set)
        ybar.grid(row=3, column=2, sticky="ns")
        self.canv.grid(row=3, column=0)
        self.canv.create_window(1,0, anchor=NW,
               window=self.top_frame)

##-------------------------------------------------------------------
   def buttons(self):
      b_row=1
      b_col=0
      for but_num in range(1, 51):
         ## create a button and send the button's number to
         ## self.cb_handler when the button is pressed
         b = Button(self.top_frame, text = str(but_num), width=5,
                    command=partial(self.cb_handler, but_num))
         b.grid(row=b_row, column=b_col)
         ## dictionary key=button number --> button instance
         self.button_dic[but_num] = b

         b_col += 1
         if b_col > 4:
            b_col = 0
            b_row += 1

   ##----------------------------------------------------------------
   def cb_handler( self, cb_number ):
      print("\ncb_handler", cb_number)
      self.button_dic[cb_number].grid_forget()

##===================================================================
BT=ButtonsTest()


Series of autocovariances is nonnegative

Question: Define the autocovariance function $\gamma_X$ of a stationary time series $X$ by $\gamma_X(k) = L_\gamma(k) \vert k \vert^{-\theta}$, $k \in \mathbb{Z}$, where $L_\gamma$ is slowly varying at infinity and $\theta \in (0, 2)$.
Is it true that
$$
\sum_{k \in \mathbb{Z}} \gamma_X(k) \geq 0
$$
I suspect that this is true and can be shown by using the semi-positive definiteness of any covariance function but I cannot get the LHS of the inequality into the bilinear form such that I can use the semi-positive definiteness.
EDIT: Note that $\gamma(0)$ is equal to the variance $\sigma$ of $X(1)$ and therefore $L(0)$ is known. Therefore, the question is whether the remaining covariances can sum up to something smaller than $-\sigma$. I suspect that the semipositive definiteness of $\gamma$ implies that they can't.
Comment: I think the statement could very much be true and it definitely is linked to positive-definiteness of $\gamma$. In fact the sum in OP is the zero-frequency term of the power spectral density, a term which is intuitively nonnegative.
Comment: This is obviously false as stated. For example, $L$ could be negative.
Comment: As $\gamma$ is a covariance function it is implicitly known that at least for $k = 0$ the slowly varying function has to be positive. In fact, $\gamma(0)$ is the variance $\sigma$ of $X(1)$ and therefore $L(0)$ is known. Therefore, the question is whether the remaining covariances can sum up to something smaller than $-\sigma$. I suspect that the semipositive definiteness of $\gamma$ implies that they can't.
Answer: As you probably know, the sum does not even converge unless $\theta>1$.
But it turns out that $\sum_n \gamma(n)\ge 0$ for any positive definite $\gamma$, assuming that $\sum_n e^{2\pi i nx}\gamma(n)$ is a continuous function for $x\in [0,1]$ (I believe this is the case for your $\gamma$s, assuming that $\theta>1$).
Why? According to Bochner's Representation Theorem,the Fourier transform $\hat{\gamma}(x)=\sum_n e^{2\pi i nx}\gamma(n)$ is a nonnegative function of $x$ (here is where we use the nonnegative-definiteness). In particular, $\sum_n \gamma(n)=\hat{\gamma}(0)$.


Which notes to play over a certain chord in a progression?

Question: I know the notes that constitute the given chord sound well simultaneous to the chord, but which other notes can you play over a certain chord to create a melody and a meaning with good sound? Are these notes that are also in the next chord?
Comment: If there was a rule, then there would only be one tune. Many notes can be used, depending on what has come before and where you go next, the mood of the composer, style of music etc. The question jj linked to should answer this for you.
Comment: I don't think this is a duplicate of the other question.  This question can relate to harmonies, colour tones or even doubling whereas the other one is more of a question about why to learn the individual notes.
Comment: This is a broad scoped question, but the answer I have in mind Is a completely appropriate to this question but inappropriate to the other.
Comment: This question is similar and might be of help: [Comfortable notes in a key](http://music.stackexchange.com/questions/10730/comfortable-notes-in-a-key)
Comment: For starters see the wikipedia page on "avoid notes": http://en.wikipedia.org/wiki/Avoid_note
Answer: This is a hugely complicated question based on the style, the instrument, and voicing among other things.
Generally chords that have more common tones with the chord in the progression makes for a more harmonious sound.  For example C major = CEG, E min = EGB, and Amin = ACE, so the shared notes make a harmonious sound happen if you play notes of E minor over C major.
This is of course generalising massively but it might be a good starting point.
For a better answer I suggest you specify style, instrument, and an example of the type of progression that you want to work over and that'll give us a better grounding on which to give advice!
Jazz books will give you a very thorough analysis of chords, substitutions, and chord tones.
If you're a guitarist, you can do worse than Ted Greene's Chord Chemistry.  There's an entire chapter on chord substitution and enough chord knowledge to last you a lifetime.  For example, one guideline is that any basic triad can theoretically be substituted for an extension, though some work better than others.  So over the C major example you could use the notes of C6, Cadd9, or C13 etc.
Ultimately your best advisers are the ones on each side of your head.  If they like the notes you play, work out why and repeat in other places :)


Why not return state and child together in react?

Question: This code seems to work. Nobody does this. What exactly is wrong with it? Under what conditions will it produce bugs?
function App(){
    const [b1, n1] = button()
    const [b2, n2] = button()
    const [input1, text] = input()
    return

Total: {n1}+{n2}={n1+n2}. That's {text}.

{b1} {b2} {input1}

;
}

function button() {
  const [n, setN] = React.useState(0)
  const b = <button onClick={()=>setN(n=>n+1)}>Increment</button>
  return [b, n]
}

function input() {
  const [t, setT] = React.useState("okay")
  const i = <input type="text" value={t} onChange={e=>setT(e.target.value)}/>
  return [i, t]
}

https://jscomplete.com/playground/s752284
It's tidy, so I would like to use it if it's fine.
Edit to clarify: Suppose you need to elevate state from child component to parent. There are many ways. Pass down a ref, pass down setState, pass down dispatch, etc. This method doesn't require any passing down, just passing up. Custom hooks typically don't return JSX for some reason. Is there some hidden problem with this pattern?
Edit 2: Extended example
Comment: Related: https://stackoverflow.com/questions/62186513/confusion-about-this-react-custom-hook-usage.  Difference is what kind of JSX you return.
Comment: to clarify the point above: basically be aware of the difference between returning a react element (jsx), which is fine, and returning a react component, which isn't. In the example provided by the OP, they are returning an element, and that's acceptable.
Comment: Thanks. My understanding is that you basically never want to define a component (i.e. a function returning JSX) in the body of any component or effect.
Answer: None. It's totally fine. It has even a name, custom hooks: https://reactjs.org/docs/hooks-custom.html
One of the convention is to give it a name that starts with use. That also mean that you need to follow all the rules associated with hooks. Documentation here: https://reactjs.org/docs/hooks-intro.html
Comment: Why not? A JSX is just an object. In fact, I bet you already use a library that does that.  https://github.com/remix-run/react-router/blob/dev/packages/react-router/index.tsx#L321
It's fine, really.
Comment: I've never seen a custom hook return a JSX element though. I can't think of any problems with it so I imagined there was some reason, because it is of great use with things like text fields and checkboxes.
Comment: They're still technically still returning just the element! I'll go ahead and use this pattern though. Thank you!
Answer: Instead of using state directly, why you trying to get it from a function call ? Why can't you create it directly inside your component which is really more readable. And keep this complete part <button onClick={()=>setN(n=>n+1)}>Increment</button> inside the component instead of the way it's given. It's better to write your code in a more readable manner. Otherwise, it becomes too complicated when it comes to much bigger components.
Comment: Suppose a form has ten inputs and buttons in it. Keeping the entire form in the parent and passing down setters seems messier to me than having children return their own state. See my edits above.


php split number and plus them

Question: With PHP I need to add all the digits in a number.
Example : if I have 142 it will be 1+4+2 = 7
its should be 1 to 9 if not its should plus again 11 will be 1+1 = 2
Comment: did you try something or..?
Answer: Here is a function, based on Dave Chen's answer :
function sumDigits($input) {
    $sum = array_sum(str_split($input));
    if($sum > 9) {
        $sum = sumDigits($sum);
    }

    return $sum;
}

This code :
echo sumDigits("1239");

Outputs: 6
1 + 2 + 3 + 9 = 15 = 1 + 5 = 6

Comment: My answer is wrong, congrats on getting the whole thing correct +1.
Comment: @DaveChen Your answer is not wrong. It is the path!
Comment: Thanks to you, You gave me the tricks !

php split number and plus them


Zoom G1XON noise issue

Question: I am a beginner and playing acoustic for last 2 and 1/2 year. After this i grew interest in Electric, so i bought a Squier Strat and as per suggestion of my music teacher a Zoom G1Xon. When i connect the processor directly to the home theater/ P.A. system, it sounds awesome, but when i connect it to my PC for recording the tracks (Using Adobe Audition 2015 or Nuendo 6.5) it catches a plenty of noise. I initially replaced the cables and the batteries also tried various tones but all in vain. As a result the tracks recorded by me have a plenty of noise. Is there any problem with the processor? or everyone has the same issue? Please suggest.
Regards,
Kunal
Comment: Is the PC a laptop or desktop? Have you tried using a ground loop isolator between the G1Xon and the PC?
Comment: Are you using the USB or Jack to connect to computer?
Comment: I had another multi effects processor and it was noisy as hell when connected directly to my laptop. You need something between them to prepare signal.
Comment: Dear David, I connect the processor to my laptop using 1/4-1/8" cables..
Comment: Dear Topo, I use a Dell Inspiron 5520 laptop. I have not tried Ground Loop Islolater, even i don't know whats it? I will google it now.. If you know, please elaborate. Regards
Comment: Dear Teodozjan, are you referring a Focusrite Scarlett like device?
Comment: Connect using UPS. If problem still exists run processor using battery power. If noise still there the problem is with your computer.
Comment: Quick question - what type of noise? Are we talking mains hum (50 or 60Hz) or interference from other devices?
Answer: I realise this is a year too late but I thought I would answer for future viewers with the same problem.
This is exactly as 'teodozjan' says in the comments above, the noise is being generated from the on-board sound card in the laptop. What you need is an audio interface such as the Focusrite Scarlett, M-Audio M-Track, etc. These devices have much better analog to digital conversion than on-board sound cards hence far better signal to noise ratio.
Even a really cheap audio interface such as the Behringer UM2 U-Phoria Audiophile (£45 on Amazon at time of writing) will be considerably better than being plugged straight into the laptop.
Some multi-fx pedals can now be used as an audio interface themselves, check out the Zoom G3. You can plug this pedal into your laptop/PC via USB and all the analog to digital conversion is then done by the pedal.

Zoom G1XON noise issue


ODEs: determining dependence of solution on force

Question: I am pretty sure this problem has a quite simple solution, but it seems I cannot find it.
Assume I have the following one dimensional IVP:
\begin{equation}
\frac{d^2 x}{dt^2}+f(x) = g(w,t) \\ x(0) = x_0 \\ \frac{dx}{dt}(0) = x_1
\end{equation}
where $x_0$ and $x_1$ are constants.
I would like to know how $x_w(w,t) \equiv\dfrac{\partial x }{\partial w}(w,t)$ evolves in time. (Assuming $x(w,t)$ is differentiable once in $w$).
Normally, I would say that computing:
\begin{equation}
\frac{d^2 x_w}{dt^2}+f_x(x) x_w = g_w(w,t) \\ x_w(0) = 0 \\ \frac{dx_w}{dt}(0) = 0
\end{equation}
will do the job. However, when I use the same technique for $\ddot{x}+x = \cos(wt)$ with arbitrary intial conditions, it does not seem to work (for $|w| \neq 1$):
\begin{equation}
\ddot{x} + x = \cos(wt) \\
x(0) = 1, \dot{x}(0) = 0.
\end{equation}
The solution to this is:
\begin{equation}
x(w,t) = \cos(t)+\dfrac{1}{1-w^2}(\cos(wt)-\cos(t)) \\
\frac{\partial x}{\partial w} = \frac{2w}{(1-w^2)^2}(\cos(wt)-\cos(t))+\frac{1}{(1-w^2)}(-t\sin(wt))
\end{equation}
This is the accurate solution. However, using:
\begin{equation}
\ddot{x}_w + x_w = -w\sin(wt) \\
x(0) = 0, \dot{x}(0) = 0
\end{equation}
gives:
\begin{equation}
x_w(w,t) = \dfrac{-w}{1-w^2}(\sin(wt)-\sin(t)) \\
\end{equation}
which is different than $\frac{\partial x}{\partial w}$.
What am I missing?
Answer: From differentiating the d.e. with respect to $w$,
$$  \dfrac{\partial^3 x_w}{\partial t^2\; \partial w} + f'(x_w(t)) \dfrac{\partial x_w}{\partial w} = \dfrac{\partial g_w}{\partial w} $$
So (assuming $x_0$ and $x_1$ don't depend on $w$) $p_w = \dfrac{\partial x_w}{\partial w}$ and $x_w$ satisfy the system
$$ \eqalign{\dfrac{d^2 x_w}{dt^2} + f(x_w) &= g_w\cr
            \dfrac{d^2 p_w}{dt^2} + f'(x_w) p_w &= \dfrac{\partial g_w}{\partial w}\cr
x_w(0) &= x_0\cr
\dfrac{d x_w}{dt}(0) &= x_1\cr
p_w(0) &= 0\cr
\dfrac{d p_w}{dt}(0) &= 0}$$
Comment: Thank you for your comment, I have fixed the formulation (forgot to mention that: f'(x)). Besides my mistake, I dont think your formulation is different than mine. Nonetheless, this does not seem to work (I have added the particular case where it does not).
Answer: You've made an algebra error:
$$
\frac{\partial}{\partial w}\left[\cos(wt)\right] = -t\sin(wt)
$$
whereas you have $-w\sin(wt)$. Fix this and it all works.
Comment: My life, that was a stupid mistake. Thanks a lot!


Notify all @SessionScoped-Beans-Instances from all Users

Question: My Problem
I have a @SessionScoped sessionInformationBean, which holds a Person-Entity from a logged in user. So, if a User logs in, I am looking up the corresponding Entity and put in in the @SessionScoped CDI Bean. This Bean is used to retrieve the current user (a Person-Entity) at any position in code, so that you can check, if it is a Admin or things like that.
@Inject
private PersonFacade personFacade;

private Person currentUser;

public Person getCurrentUser() {
    if (currentUser == null) {
        String loginname = FacesContext.
        getCurrentInstance().
        getExternalContext().getRemoteUser();
        currentUser = personFacade.findByLoginname(loginname);
    }

    return currentUser;
}

But set the case, an Admin is giving this logged in user ( the Person-Entity) some Admin-Rights and saves him to the database. In this case, the Person at the @SessionScoped Bean is not updated, therefore the already logged in user is not seeing his Admin-Rights after a refresh of his page. Thats the problem. To avoid this problem I am fetching the user new from the database every access (There is no cache activated) to the @SessionScoped bean.
What I want
But I want to cache him and avoid a database access every time.  So, I thought, if anyone saves a user, I will simply notice all sessionInformationBean-Instances and set the currentUser-Attribute to null. So, the next call, they fetch it again from database and cache it till its set to null again from my Person.save()-Operation.
What I tried
But that seems to be a little bit tricky. I thought I can handle it with CDI-Events, but they only will be pushed to the sessionInformationBean of the user, that is editing the other user.
Maybe something to do with my problem: CDI Events observed across sessions
Then I thought.. okay.. lets do it with Primefaces-Push. But the same thing.. the Events are just coming to my own sessionInformationBean.
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("/session", "test");

I thought the purpose of push and WebSockets is to notify all users or sessions.
What should I do?
So, the question is: How to access all instances of a specific @SessionScopedBean? I just want to access the sessionInformationBean from every logged in user and set the currentUserto null.
Answer: There's no built in way I can think of to do this.  What I would recommend is to add an ApplicationScoped bean.  Whenever your SessionScoped bean is created, register it with this app scoped bean.  When you want to process this event iterate through all of these objects.
I'm curious though, what happens when you have multiple servers?


Get the top n rows of each day from same table in Django

Question: I am sure this is not a novel/new problem. I really tried to look into other solutions. However, I could not find how to solve this.
I have a model like
class Deal(models.Model):
    title = models.CharField(max_length=1500)
    viewCounter = models.SmallIntegerField(default=0)
    thumbsUpCounter = models.SmallIntegerField(default=0)
    createDateTime = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, related_name='deal_owner',
                          editable=False)

Now I want to get top 10 (or less) deals ordering by thumbsUpCounter and viewCounter  of every day. I tried to look into the Subquery and Outerref. However, I could not figure out how can I get the right results.
** I am using MySQL.
Thanks in advance.
Comment: are you trying to group by date, and find top 10 hits?
Comment: @ha-neul yes. that is what I was looking for. Thanks
Answer: try
from django.db.models.functions import TruncDate

query = Deal.objects.annotate(date=TruncDate('createDateTime'))\ # extract date
        .values('date')\                                        # group by date
        .order_by('-thumbsUpCounter')\                          # order by
         [:10]                                                  # slice first 10

Comment: could you please check the syntax? there are some syntax issues for braces.
Comment: yes, I missed one ```)``` in the first line. updated
Comment: really thanks for your answer. But I am getting an error 'dict' object has no attribute 'owner', owner is a another model of Deal model. Do you have any idea of this.
Comment: ? I don't see owner anywhere in your q?
Comment: I did not realize that the foreign key would give any error. I added the owner.
Comment: First of all, if you print out the query, does it show top 10 that you want? Second, you have something like q.owner in your template?
Comment: It does not show the rows, it gives an error. I am using django rest, there is no template.
Comment: just to let you know.. your solution actually doesn't work.
Comment: thanks for letting me know. were you able to print out ```print(query)``` in the terminal?
Comment: There is no grouping , how would that work anyway?
Comment: in django ORM, values is for grouping. we grouped by the date. when you say no grouping, could you be more specific?
Comment: I reposted the question https://stackoverflow.com/questions/65324003/get-top-n-records-for-each-group-with-django-queryset


Is 'indirect effect' the same as 'mediation'?

Question: Is it correct to use 'indirect effect' and 'mediation' interchangeably in all situations? I mean if we know that A influences B and B influences C. Can we conclude that the effect is mediated by B without performing a mediation test?
Answer: No, "mediation" and "indirect effect" are not synonymous. For example, when analyzing complex causal systems in which any variable in the system at time $t$ contributes causally to every variable in the system at times $>t$, the term "mediator" is largely meaningless, whereas indirect effects may or may not exist due both to the qualitative structure of the system, and due to the quantitative magnitude of direct causal effects withing that structure (see, for example, Levins, R. (1974). The qualitative analysis of partially specified systems. Annals of the New York Academy of Sciences, 231:123–138.)
gung's answer assumes a terminal causal model, where the analysis attempts to explain or predict a final causal outcome, typically in a limited set of variables. By contrast complex causal models attempt to explain system behaviors.
Answer: There seem to be two distinct aspects to this question:

Are the terms 'indirect effect' and 'mediation' synonymous?
I would say largely yes (edit: assuming--cf. @Alexis' answer--that you are referring to a terminal causal model).  Bear in mind that you can have full or partial mediation.  That is, the effect of A on C can flow only through B, or partly through B but also partly directly.  It is less clear to me how one would use 'indirect effect' in the latter case.  To my ear it sounds more like full mediation.

If we know a-priori that A causes B, and B in turn causes C, do we need a mediation test?
No.  If you know that this is the case a-priori, then testing is silly and redundant.  This has to do with the nature of statistical testing; there is nothing special about mediation here:  We can also say that there is no need to do a $t$-test (for example), to determine if the mean of a variable differs by grouping after having done a median split.
Answer: The word mediation is inappropriate when the influence from A to C is not significant. However, you can say that A influences C indirectly through B, i.e. indirect effect.


importing from an external souce where source filename changes

Question: Forgive me if this is an easy problem,  Im still learning..
I have an excel file, that takes data and performs analytics to compose graphs. right now method to update is manual copying and pasting from 2 other data sources.  I can easily create a macro to import the first source as the data location/file name is always the same. The second source is trickier, as the file has some standardized naming convention,  but a date is added, as it is refreshed once a week, every Monday or tuesday. is there a way to automate pulling the data from the external source (sharepoint library) and telling it to find the most current version? either by understanding the date convention added in the file name,  or by another means of modified date or other criteria? the file is kept with previous archived copies. I do not own the report, sharepoint site, or library it is kept in, so I cant influence those factors :(.  any help appreciated, and I can provide better details and explanation.
Comment: What is the naming convention for the dates?
Comment: You may also want to look at `FileDateTime(filepath)`, which you can use to find the latest file in the folder. Example: http://www.xl-central.com/open-the-latest-file-in-a-folder.html
Answer: There are two basic approaches that I know of, either allow the user to choose the file through a dialog box, or use the "Dir" function to find the file with the most recent date.
First approach (code I use frequently):
Public Function ChooseOpenFile() As String

Dim strSlash As String

If InStr(1, ActiveWorkbook.Path, "/") > 0 Then
    strSlash = "/"
Else
    strSlash = "\"
End If

With Application.FileDialog(msoFileDialogOpen)
        .Title = "Select the first file to open in series:"
        .InitialFileName = Replace(ActiveWorkbook.Path, "http:", "", 1) & strSlash
        Call .Filters.Clear
        Call .Filters.Add("Excel Files Only", "*.xls, *.xlsx, *.xlsb")

        'only allow the user to select one file
        .AllowMultiSelect = False
        'make the file dialog visible to the user
        intChoice = .Show
        'determine what choice the user made
            If intChoice <> 0 Then
                'get the file path selected by the user
                ChooseOpenFile = .SelectedItems(1)
            End If
End With

End Function

As for the second approach, as long as you can already access the folder programmatically, you build a loop to cycle through the files, extract the date from each file, test for being more recent than previous versions and store the filename of the most recent version to pass out of the loop.
Function MostRecentFile() As String

Dim dateTest As Date
Dim dateRecent As Date

Dim strMyFile As String
Dim strMyFolder As String
Dim strCurrentFile As String
Dim strSlash As String

strMyFolder = ThisWorkbook.Path
    If InStr(1, strMyFolder, "/") > 0 Then
        strSlash = "/"
    Else
        strSlash = "\"
    End If

strMyFile = Dir(Replace(strMyFolder, "http:", "") & strSlash & "*.xls*")

Do While strMyFile <> ""
    'Modify this line (number of characters and extension to replace) as needed.
    dateTest = CDate(Replace(Right(strMyFile, 15), ".xls*", ""))
    If dateTest > dateRecent Then
        dateRecent = dateTest
        strCurrentFile = strMyFile
    End If
    Stop
    Dir
Loop

MostRecentFile = strCurrentFile

End Function

Answer: You can browse to the file.
Sub GetOpenFile()
Dim fileStr As String
fileStr = Application.GetOpenFilename()
If fileStr = "False" Then Exit Sub
Workbooks.Open fileStr
End Sub

If you want some kind of automated solution, based on your system date, like the next Monday ot Tuesday, you can get the machine to figure it out, and pass the result to the appropriate string in the file path.
Sub NameAsNextMon()
Dim K As Integer
Dim dteMon As Date
Dim tempName As Variant

K = Weekday(Now)
dteMon = Now() + (9 - K)
tempName = Year(dteMon) & "-" & Month(dteMon) & "-" & Day(dteMon) & ".xls"
Do
fName = Application.GetSaveAsFilename(tempName)
Loop Until fName <> False
ActiveWorkbook.SaveAs Filename:=fName
End Sub


Add tuple to a list of tuples

Question: How can I sum a tuple to a list of tuples such as:
>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)

the result being:
>>> c
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

I know this can be easily solved with numpy:
>>> import numpy
>>> c = numpy.add(a, b).tolist()
>>> c
[[10, 21, 32], [13, 24, 35], [16, 27, 38]]

but I'd rather avoid numpy.
Answer: one-liner using nested list comprehensions and the magic zip to interleave the fixed b triplet to add to the iterating element of a, no numpy needed:
a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)

c = [tuple([i+j for i,j in zip(e,b)]) for e in a]
print(c)

result:
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

EDIT: you could drop the tuple conversion if not needed:
c = [[i+j for i,j in zip(e,b)] for e in a]

Comment: a variation of this using `map` and `sum` is `[tuple(map(sum,zip(x,b))) for x in a ]`
Answer: You can do this with list comprehension:
a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)
c = [[x + b[i] for i, x in enumerate(y)] for y in a]

c will be a list of lists, rather than a list of tuples. If that matters, you can do this instead:
c = [tuple(x + b[i] for i, x in enumerate(y)) for y in a]

Comment: Oops, looks like someone already beat me to it. I'll keep this here to show a way of doing it with `enumerate` rather than `zip` though.
Comment: your solution is faster in python 2 because `zip` builds a list. `enumerate` doesn't. Anyway: good answer.
Answer: Define a function to sum two vectors:
def sum_vectors(a, b):
    return tuple(sum(z) for z in zip(a, b))

Use it to define a function for adding a vector to a list of vectors:
def add_vector_to_vectors(v, ws):
    return [sum_vectors(v, w) for w in ws]

Example usage:
>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)
>>> add_vector_to_vectors(b, a)
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

Comment: You already got some correct answers but I'll keep mine since I find it more readable to break it down in steps.

Add tuple to a list of tuples


Is there any real statistics behind "the Pythagorean theorem of baseball"?

Question: I'm reading a book about sabermetrics, specifically Mathletics by Wayne Winston, and in the first chapter he introduces a quantity that can be used to predict the win rate of teams:
$$\frac{\text{Points Scored}^2 }{\text{Points Scored}^2 + \text{Points Against}^2} \approx \text{% Games Won},$$
and he seems to hint that, halfway through the season, it can be used to predict the win rate better than the win rate of the first half of the season. He generalizes the formula to
$$ \frac{R^{\text{exp}}}{R^{\text{exp}} + 1}, $$
where $R$ is the ratio of points scored to points against. He then finds the best fit exponent to predict % of games won, for 3 sports, and finds for
$$ \text{Baseball: exp} \approx 2 ,$$
$$ \text{Football: exp} \approx 2.7, $$
$$ \text{Basketball: exp} \approx 14. $$
But I've realized you can express % of games won in terms of points scored and points against for each game $i$, specifically % of games won is exactly the fraction of games where the points scored $PS_i$, is greater than the points against $PA_i$:
$$ \frac{1}{n} \sum_{i=1}^n I\left (PS_i > PA_i\right ),$$
where $I$ is the indicator function.
Therefore my question is:
$$ \frac{ \left (  \sum_{i=1}^n PS_i \right )^x  }{ \left ( \sum_{i=1}^nPS_i \right )^x  + \left ( \sum_{i = 1}^n PA_i \right )^x } \approx \frac{1}{n} \sum_{i=1}^n I\left (PS_i > PA_i \right )$$
Is there an analytical way to find the MLE for $x$? Forgive me if I've made any naive mistakes, I'm mostly self-teaching myself statistics.
Answer: The mathematical/statistical foundations for the "Pythagorean rule" was examined in Miller (2007).  This paper showed that if the number of runs scored by each team in each game follows a Weibull distribution with common shape parameter $\gamma$ but different scale parameters, then the generalised form of the Pythagorean rule (with generalised power $\gamma$) emerges as the predicted win probability.
That paper also fits the posited Weibull model to baseball data from 14 teams playing in the 2004 American League.  The results show a reasonable model fit, with $\hat{\gamma} \approx 1.74 \text{-} 1.82$ using various estimation techniques.  This suggests that the generalised Pythagorean rule may be a reasonable prediction technique for prediction wins-losses, but the power parameter should be a bit less than the squared value that appears in the book by Winston.

Miller, S. (2007) A derivation of the Pythagorean won-loss formula in baseball. Chance 20(1), pp. 40-48.


Find probability from uniform distribution

Question: Let $X$, $Y$ be two independent random variables from $U(0,1)$. Then find $P[Y>(X-1/2)^2]$.
I initially  tried drawing the figure but that seemed complicated. I then took expectation on both sides and got $P[E(Y)>V(X)]$. Am I right?
Comment: Also, why are you doing anything with expectation?  You are simply asked to find the **probability**, not the expectation.
Comment: @Analyst1 Probabilities *are* expectations (of indicator variables).  Often they can readily be found using techniques to find expectations.  The mistake made here is to suppose that $E[Y\gt (X-\mu_X)^2] = E[Y \gt E[(X-\mu_X)^2]]$: this is rarely true and there are no generally applicable rules of expectation, probability, or integration that would justify such an equation.
Comment: What did you attempt to draw?  The drawing is very simple so the area of integration should be quite simple to figure out once you sketch the x-y plane.
Comment: Good point @whuber, but I don't see where the OP was headed with regard to his/her approach by finding an expectation.  The most straightforward approach to solving this problem seemed to be simply integrating the area bounded below by 0 and 1 and above the parabola $Y = (X-1/2)^2$.
Answer: This ends up being the area above the curve
\begin{equation}
Y=(X−\frac{1}{2})^2
\end{equation}

This can be found by integration
\begin{equation}
P[Y>(X−\frac{1}{2})^2] = \int_{0}^{1}\int_{(X−\frac{1}{2})^2}^{1} 1\times1 \,dydx
\end{equation}
\begin{equation}
= \int_{0}^{1}{1-(X−\frac{1}{2})^2} \,dx
\end{equation}
\begin{equation}
=  \Big[X-\frac{1}{3}\times(X−\frac{1}{2})^3\Big]_0^1
\end{equation}
\begin{equation}
=  \Big(1-\frac{1}{3}\times(1−\frac{1}{2})^3\Big) - \Big(0-\frac{1}{3}\times(0−\frac{1}{2})^3\Big)
\end{equation}
\begin{equation}
=  \frac{23}{24}-\frac{1}{24}
\end{equation}
\begin{equation}
=  \frac{22}{24}
\end{equation}


Can a non-linear polynomial have integers values at only integer points?

Question: P(x) be a polynomial with real co-efficient s,deg(P) greater than or equal to 2.Prove that it is not possible that whenever P(x) is an integer,x is also an integer.
I tried it in various way and I think I have to show that there exists an real number for which P(x) is an integer.
Answer: Hint: Find an interval $[n,n+1]$ for which $\left|P(n+1) - P(n)\right| > 1$ where $n$ is an integer (why is this possibile?).  Use the intermediate value theorem.


Is uniform convergence of a function sequence equivalent to uniform equicontinuity of the set of members of the sequence?

Question: There is a plethora of questions on this topic on Math.stackexchnge.
Can the above question be answered for $C(\mathbb R ,\mathbb R)$ with an unambiguous "yes"?
Comment: Of course not. Take the sequence fn(x)=(-1)^n
Comment: But the set of functions {f(x)=1, f(x)=-1} is uniformly equicontinuous, is it not?
Comment: Ah, I see now. Well, yeah, suggesting equivalence is a bit weird because you can't quite recover the sequence from its support, unless the set has exactly one cluster point.
Comment: (-1)^n does not converge uniformly to anything.
Answer: No, but it can be answered with an unambiguous "no". Take, for instance, $f_n(x)=x+n$, for each $n\in\Bbb N$.
Comment: @Siddhartha I have already edited my answer.
Comment: You mean $\mathbb{N}$?