Which function do we want to minimize?

Question: A ray of light travels from the point $A$ to the point $B$ across the border between two materials. At the first material the speed is $v_1$ and at the second it is $v_2$. Show that the journey is achieved at the least possible time when Snell's law: $$\frac{\sin \theta_1}{\sin \theta_2}=\frac{v_1}{v_2}$$ holds.
To show that do we have to use Lagrange multipliers method??
But which function do we want to minimize??
Comment: You can look here (in the middle of the site):http://www.maa.org/publications/periodicals/convergence/historical-activities-for-calculus-module-3-optimization-snells-law-and-the-principle-of-least-time
Comment: Typo in statement of law: RHS should be $v_1/v_2$
Comment: See the edit of my answer for a solution using Lagrange multipliers.
Comment: Yes, you're right... I edited my post... @grand_chat
Answer: Without Lagrange multipliers
You don't need to use Lagrange multipliers. Snell's law can be derived directly from Fermat's principle of least time, which consists in minimizing the time taken by the ray of light to travel from one point to another. Take a look at the diagram below:

In the first medium, with refractive index $n_1$, light will travel at velocity $v_1=\dfrac{c}{n_1}$. In the second medium, at $v_2=\dfrac{c}{n_2}$. Therefore, the total time from point $P$ to $Q$ is $T(x)=\dfrac{d_1}{v_1}+\dfrac{d_2}{v_2}$.
To find $d_1$ and $d_2$, the distances traveled in media $1$ and $2$ respectively, you can simply use the Pythagorean theorem:
$$d_1=\sqrt{x^2+a^2},\quad d_2=\sqrt{(l-x)^2+b^2}$$
Thus:
$$T(x)=\dfrac{\sqrt{x^2+a^2}}{v_1}+\dfrac{\sqrt{(l-x)^2+b^2}}{v_2}$$
Applying Fermat's principle, you then take minimize $T(x)$:
$$\dfrac{dT}{dx}=\dfrac{x}{v_1\sqrt{x^2+a^2}}+\dfrac{x-l}{\sqrt{(l-x)^2+b^2}}=0$$
Using trigonometry:
$$\dfrac{x}{\sqrt{x^2+a^2}}=\sin\theta_1,\quad \dfrac{l-x}{\sqrt{(1-x)^2+b^2}}=\sin\theta_2$$
Therefore:
$$\dfrac{dT}{dx}=0\Longleftrightarrow \dfrac{\sin\theta_1}{v_1}=\dfrac{\sin\theta_2}{v_2}$$
Using the aforementioned relation between the speed of light in a given medium and the corresponding refractive index, we recover Snell's law:
$$\dfrac{\sin\theta_1}{\sin\theta_2}=\dfrac{n_2}{n_1}$$

With Lagrange multipliers
We try to minimize the time taken by the ray of light to travel from $P$ to $Q$, which we can express as:
$$c\cdot T(\theta_1,\theta_2)=\dfrac{an_1}{\cos\theta_1}+\dfrac{bn_2}{\cos\theta_2}$$
(You can check that this is equivalent to $T(x)$ in the previous part). We also derive the following constraint, from the fixed horizontal distance between $P$ and $Q$:
$$l=x+(l-x)=a\tan\theta_1+b\tan\theta_2$$
We can therefore write down the Lagrangian:
$$L(\theta_1,\theta_2,\lambda)=\dfrac{an_1}{\cos\theta_1}+\dfrac{bn_2}{\cos\theta_2}+\lambda(a\tan\theta_1+b\tan\theta_2-l)$$
And we solve the Lagrange equations for $\lambda$:
$$\dfrac{\partial L}{\partial\theta_1}=0\Longrightarrow\dfrac{an_1\sin\theta_1+a\lambda}{\cos^2\theta_1}=0\Longrightarrow -\lambda=n_1\sin\theta_1$$
$$\dfrac{\partial L}{\partial\theta_2}=0\Longrightarrow\dfrac{bn_2\sin\theta_2+b\lambda}{\cos^2\theta_2}=0\Longrightarrow -\lambda=n_2\sin\theta_2$$
And indeed, combining the two results above yields Snell's law:
$$\dfrac{\sin\theta_1}{\sin\theta_2}=\dfrac{n_2}{n_1}$$
Comment: Could you explain to me how you found the relation $$c\cdot T(\theta_1,\theta_2)=\dfrac{an_1}{\cos\theta_1}+\dfrac{bn_2}{\cos\theta_2}$$ ??
Comment: @MaryStar This is equivalent to the expression of $T(x)$ I gave at the beginning, with $\dfrac{a}{\cos\theta_1}=a\cdot\dfrac{\sqrt{x^2+a^2}}{a}=\sqrt{x^2+a^2}$. Just a bit of trigonometry. And the $c$ on the LHS is the speed of light, with $v_i=\dfrac{n_i}{c}$. I factored it out, because it does not impact our minimization of $T$. If you kept it on the RHS, you'd find Snell's law in terms of $v_1$ and $v_2$, instead of $n_1$ and $n_2$ - still, they're equivalent.
Answer: The total travel time, which is the sum of travel times from $A$ to the surface and fromthe surface to $B$. The two part times are obtained as length divided by speed, the two lengths depend on the angles.
Answer: Hint:
Use Fermat's principle.

the path taken between two points by a ray of light is the path that
  can be traversed in the least time.

And you don't need Lagrange multipliers.
Answer: Let the total horizontal distance travelled be $a$. The light travels in the first medium a distance $d_{1}$ at an angle $\theta _{1}$ to the vertical. Then if the horizontal distance traveled in this step is $x$ and the vertical distance traveled is $h$, the time it takes to reach the border is
$t_{1}=\frac{\left ( x^{2}+h^{2} \right )^{1/2}}{v_{1}}$.
From there, the light enters the second medium has velocity $v_{2}$, makes an angle $\theta _{2}$ to the vertical, and travels a distance $d_{2}$. The horizontal distance travelled is $a-x$ and the vertical distance travelled is $y$, so that
$t_{2}=\frac{\left ( (a-x)^{2}+y^{2} \right )^{1/2}}{v_{2}}$.
The trick here is to observe that we may assume that only $x$ varies. i.e. that $h$ and $y$ are constant.
Then, put $t=t_{1}+t_{2}$ and minimize this function as a function of the single variable $x$. There is some messy algebra involved and you will use the relations
$\sin \theta _{1}=\frac{x}{d_{1}}$
and
$\sin \theta _{2}=\frac{a-x}{d_{2}}$.

Which function do we want to minimize?


Gradient descent vs. Newton's method -- which one requires more computation?

Question: Broadly speaking, when numerically minimizing a d-dimensional objective function:

Gradient descent generally requires more iterations, but each iteration is fast
(we only need to compute 1st derivatives)

Newton's method generally requires fewer iterations, but each iteration is slow
(we need to compute 2nd dervatives too)

My question is: in terms of the total amount of computation required, which one generally ends up being faster -- Newton's method or gradient-descent? Does this depend on $d$? How?
If this is a better question for another site please let me know.
Minor update
If it matters for the sake of comparison, let's assume the function is convex and "typical" (i.e. I'm not going to explicitly choose a function that exhibits the worst-case behavior of either algorithm). I'm just trying to understand what the rule of thumb is regarding the performance of each method.
Comment: Newton-type methods will usually win by far, if done properly. A good reference for the state-of-the-art methods for numerical optimization is Nocedal and Wright's book.
Comment: What precisely do you mean by total amount of computation? Usually for nonlinear programming algorithms, one compares methods in terms of convergence rates.
Comment: @wonko: It's a pretty clear question -- I mean if I run it on a computer, which one will finish faster (perhaps up to a constant factor)?
Comment: @NickAlger: Thanks for the tip, I'll take a look at the book.
Answer: I think this depends a lot on the structure of the function you are optimizing (duh). In general non-convex cases, both algorithms have the same worst-case complexity for the number of iterations taken to drive the norm of the gradient below some given tolerance. Not sure what this means in terms of actual computation time for instances because the constant factors come into play.
You can look at this paper by Gould et al and references therein for more details.
I think a good thumbrule is - if your problem is convex and you have a reasonably good initial guess, Newton's (or Quasi-Newton) is usually much faster in practice.
Comment: @Mehrdad Surprisingly it tends to be quite the opposite - Newton type methods tend to do way better for large $d$. The reason is that it turns out you don't actually need to compute the full $d$-by-$d$ Hessian to apply it's inverse (or an approximation of its inverse) to a vector. The key methods to look into are "inexact Newton-Krylov" and "L-BFGS".
Comment: Are you sure it doesn't strongly depend on d? Intuitively I would expect Newton to become worse than gradient descent as d increases (since it needs second derivatives), but not sure... (and good point about the structure of the function, I think it's safe to assume it's a typical convex function for the sake of the question)
Comment: You're right in the sense that the actual number of computations would depend on $d$ since obviously you are computing more derivative terms as the dimension increases. But I'm not sure there is a general statement you can make about what the tradeoff looks like between iterations and computations per iteration between the two algorithms.
Comment: @NickAlger: Very interesting, thanks for the pointers!
Answer: In general a function one is trying to find a zero of is given by an explicit formula so the calculation of the derivative is a single-occurrence event and need not to be incorporated into the iteration. For the advantages of Newton's method see http://en.wikipedia.org/wiki/Newton%27s_method
Comment: I meant when this is done numerically -- I'll update the question.
Comment: The OP asks about optimization not equation solving, I guess.
Comment: @Claude, I don't see how this could be answered without some kind of information about the regularity of the function. Does this question make sense?
Comment: It makes a lot of sense to me. I confess that I implicitly admit the regularity of the function. To me, the main question is : what means "compute the derivatives" ? Are they analytical or numerical ? The problem is very interesting (at least, to me !). Cheers :-)
Comment: @Claude, computing the derivative only increases each iteration by a constant factor, whereas if you assume regularity, doesn't Newton's method provide an exponential improvement on other methods?
Comment: I must go now but I shall be delighted to continue this discussion with you tomorrow. Cheers :-)
Comment: @user72694: If you have to compute the derivative at each step (at the same cost as computing the function) then Newton's method is suboptimal and the secant method does better. If you get the derivative calculation for free -- perhaps as a side-effect of computing the function -- then Newton is faster than secant.


Notation that means "same as previous four?"

Question: I am playing "Sonate Pathetique," whose time signature is 4/4. I came across a bar with four notes that looked like half notes. I asked my friend, and he said it meant "the same as the previous four notes." What is the name of this note?
Additionally, I now came across a bar with three of these notes and one quarter note. What do I do now?
Edit: Here's a photo of the part I'm stuck on:

Edit 2:
Right, I know I must be causing everyone a massive headache right now (sorry...) Looking back, the photo I sent is definitely not what I encountered before. What I saw before was, indeed, a tremolo, and what I show here is just a very simple 3 half notes with a quarter note. I don't know why I also thought that was a tremolo. Sorry for the confusion.
Comment: For everyone's sake, please  post a pic. of the first part of the question. Otherwise I'll vtc as question is rather unclear.
Comment: @Tim  I was aiming that comment **at** the OP.,  Sorry, thought that was obvious.
Comment: Thank you. So now, what exactly is the question?
Comment: A suggestion: when in doubt,  try to find a recording and listen to how the measures in question are performed.
Comment: Could you poste also a picture of the other notes from which your friend says they are played in the same way as the previous bar?
Comment: We have a community answer collecting multi-voice notation questions on [meta](https://music.meta.stackexchange.com/a/3504/2600).
Comment: @CarlWitthoft - it's an option, but why should we have to go to the trouble of listening through till we get to that part? And which part is it anyway? There's no bar numbers. The onus should be on OP, not those giving their time ane effort trying to enligten OP.
Answer: Now the music's arrived, your friend isn't right concerning the 3rd bar in the pic. (which is all we have to go on). The notes may be the same but the way they're played isn't.
Notice the stems. Some up, some down. We have a lot of questions appertaining to this sort of writing, so this may well be a dupe.
Treat the l.h. as two separate parts, which would be easier played on two separate instruments. Here, the l.h. gets to play both. Unlike the previous bars, the notes are held loger, and effectively overlap. The pedal helps, but while the low G(?) is held, the higher G is played, and that is held while the low B is played, and that is held while the laast note in the bar is played. Very different from the previous bar!
Comment: As I suggest in [my answer](https://music.stackexchange.com/a/101041/2197), I think you have half the answer here.  What you say is certainly correct for the passage shown in the photograph and described in the second paragraph of the question; but I suspect the friend was also correct in explaining the passage described in the OP's first paragraph as tremolo, the OP is just mistaken in thinking that the two passages are the same notation.
Comment: +1 even you don't mention the tremolo as it isn't posted in the question. So you edit maybe *your friend isn't right.*?
Comment: I think the friend may have been referring to the 4 quarter-note chords on the *right* hand  in the previous measure being rhythmicly the same as the overlapping half-notes on the *left* hand in question.  This would be correct, although not complete as it doesn't take the overlapping into account.  But the notes should indeed be struck at the same rhythm but be held twice as long.
Answer: Do you mean this?   The first left hand bar is written out in full.  The next bar is notated as a tremolo.  Another way of writing the same thing.  (It means 'play an 8th note tremolo', not 'repeat the previous bar'. The writer didn't HAVE to write it out in full the first time. And note that from bar 5 we DON'T repeat the previous bar.)
I can't see your second example in the score.  Perhaps you could add a scan of it to your question?

(Later) OK, here's the illustration of the second part of the question, just added by the OP.  Two bars of the LH octaves figure - which for some reason the composer (or editor) decided to notate in full this time not with the tremolo notation.  Then something quite different.  The half notes AREN'T connected by an 8th-note beam.  This is simple 2-voice writing.  Like in bar 7 of the first example, though rather more widely separated.   (I'm surprised that a pianist capable of this piece hasn't encountered this sort of notation before!)
Comment: Can't see any trem. in the music.
Comment: Thanks! I don't have a scanner with me, so I added a photo of my sheet.
Comment: @Tim https://en.wikipedia.org/wiki/Tremolo#Notation  Perhaps you're thinking of another kind of tremolo: the type a mandolinist plays.
Comment: @OldBrixtonian - yes, but neither your or Laurence's pic show dots joined like they are in OP's pic. That's clearly three part writing. The stems don't join and the notes aren't the same, as they would be in trem. Trem will have two notes which alternate. In OP's pic they keep changing, (3rd bar in). Sorry, can't see how either answer is correct.
Comment: You  all are right. When I've read the question without seeing the picture (and not checking the score) my first assumption was OP is confusing with this kind of tremolo notation.
Comment: This thread has become massively confused.  Now we have sight of BOTH examples, might I suggest that answers referring to only one of them are either expanded to include both or withdrawn?
Comment: Is *your* 1st pic. the actual sample in question, 'cos it's not clear from your text, otherwise I'm still waiting for the sample in question.
Comment: The OP initially offered no samples.  The first one in my answer is my assumption of what he was referring to in the first part of his question - an assumption that seems to have been accepted.  The second one is what the OP then added to his question, referring to the second half of his question.
Answer: Like at bar 11 you mean? Your friend's right.

They're called tremolos.
You say,

I now came across a bar with three of these notes and one quarter note. What do I do now?

You tell us the bar number! I can't find what you're talking about. Or you could look up tremolo on Wikipedia: maybe that'll solve it.
Comment: Can't see any trem in the music.
Comment: @Old - they're saving paper ;) They literally may have had to do it to fit it all in a given number of pages.
Comment: Thanks for your answer! I added a picture (I don't have a scanner with me right now), I hope that should clear things up.
Comment: Oh OK. The notes in the bass clef are written in two 'voices'. The ones with their stems up are one voice and those with their stems down the other. Try covering up all but the low minims: G Bb C F# etc. You play those with fingers 5, 4, 3, 5. Now cover THOSE up to leave just the crotchet rest and the G's on the bottom line. You play those with your thumb. Get it? So the order of fingers goes: 5 1 4 1 3 1 5 1 etc., the thumb playing on the offbeats. So in fact the left hand has a note on each beat of the bar. Got it? It's fun to play this bit.
Comment: Btw, that edition looks awful. What are the pedal-markings doing up THERE?!
Comment: I've never seen such a notation before. How common is it?
Comment: @curiousdannii You mean the pedal-marks or the tremolos or the use of two voices?
Answer: There's a core confusion here: the two passages you describe are not actually the same notation.
The notation you describe in your first paragraph seems to be tremolo, correctly explained by your friend and illustrated in the answers by Laurence Payne and Old Brixtonian.  The way to recognise this notation is that it has stems joined by bars like eighth-notes/quavers, but note-heads like half-notes/minims.
The notation you describe in your second paragraph, "I now came across a bar with three of these notes and one quarter note", and illustrated in your photograph, is not tremolo, since it doesn't have barred stems.  This one really is half-notes, and as explained in Tim's answer and a comment by Old Brixtonian, they are in two different voices.
Comment: @OldBrixtonian: Thanks, I'll add an acknowledgement of that.  The point of my answer is to collate the earlier answers into a single answer, and clear up the confusion/contradictions that have arisen.  The previous answers are good, but each only answers part of the question; none had explicitly addressed the OP's conflation of the two notations; and some have confounded the confusion by taking the OP's misunderstanding at face value (eg in Tim's otherwise excellent answer, "Now the music's arrived, your friend isn't right").
Comment: The *key confusion* could lead to a new confusion as the term key is a little bit overused in music terminology ;)
Comment: I explained the notation described by the OP in his/her second paragraph six hours ago, in my comment.

Notation that means “same as previous four?”


camada DAO com duas tabelas

Question: A minha dúvida ao trabalhar com a camada DAO segua a seguinte:
Até onde me informei, cada tabela seria referente a um objeto DAO. Mas suponhamos que seja necessário fazer uma consulta com select / JOIN ou seja, que a mesma retorne dados de mais de uma tabela em uma única consulta.
Para este caso, o objeto DAO de uma tabela poderia buscar dados de outra tabela?
Answer: Mantenha-se simples, é a melhor coisa para manutenções futuras de uma aplicação!
Se você precisar fazer um join com outra tabela, escolha em que DAO tem mais sentido efetuar este relacionamento.
Por exemplo, eu tenho uma classe chamada ClientDAO e a outra chamada AddressDAO, e quero relacionar o cliente aos seus endereços, que podem ser vários, não fara sentido algum efetuar este relacionamento na classe ClientDAO, porque quem faz a abstração de endereços e a AddressDAO.
Sendo assim só passar as propriedades da camada Client para o AddressDAO.
related(Client $Client)

camada DAO com duas tabelas


Problema com checkbox

Question: Quando tento verificar pela base de dados se algum registo existe, marcar a checkbox como checada, sempre me retorna como não checado.
 <?php

    $result_cat = $conexao->prepare("SELECT * FROM colecoes WHERE activo = :activo");
    $result_cat->bindValue(':activo', 1, PDO::PARAM_INT);
    $result_cat->execute();
    $row_cat_l = $result_cat->fetchAll(PDO::FETCH_OBJ);

     $qtd = count($_REQUEST['categorias_estabelecimentos']);

     for ( $i = 0; $i < $qtd ; $i++ ) {

        $cat = $_REQUEST['categorias_estabelecimentos'];

     }

    foreach ($row_cat_l as $row_cat) {

?>

            <input type="checkbox" <?=(in_array($row_cat->slug, $cat)?'checked="checked"':NULL)?> name="categoria[]" value="<? $row_cat->slug; ?>" />
            <?= $row_cat->titulo; ?>

<?php

    }

?>

Answer: Você precisa de um array, mas está sobrescrevendo a variável $cat em vez de fazer ela ser um array de valores. Segue sugestão.
<?php

    $result_cat = $conexao->prepare("SELECT * FROM colecoes WHERE activo = :activo");
    $result_cat->bindValue(':activo', 1, PDO::PARAM_INT);
    $result_cat->execute();
    $row_cat_l = $result_cat->fetchAll(PDO::FETCH_OBJ);

     $qtd = count($_REQUEST['categorias_estabelecimentos']);

     // PHP 5. Se o seu for mais antigo use $cat = array();
     $cat = [];

     for ( $i = 0; $i < $qtd ; $i++ ) {

        $cat[] = $_REQUEST['categorias_estabelecimentos'][$i]['slug'];

     }

    foreach ($row_cat_l as $row_cat) {

?>

            <input type="checkbox" <?=(in_array($row_cat->slug, $cat)?'checked="checked"':NULL)?> name="categoria[]" value="<? $row_cat->slug; ?>" />
            <?= $row_cat->titulo; ?>

<?php

    }

?>

Comment: Tentei mas continua sem marcar nenhuma
Comment: Já esta já funcionou nao tinha visto a sua alteração

Problema com checkbox


Checkboxes in JavaScript

Question: I've got a problem. I must create a form with five check-boxes.

The user must select exactly three of the five check-boxes.
At the time of change check-box updates the marker at check-box
When the user presses a fourth element should light up at the red light.

3. When you deselect any item marker when it disappears (is white) and the rest are green.
Here is what I'm done: http://jsfiddle.net/epredator/98TfU/
and some of my code, because I can't post a JSfiddle link without some code in text ;):
 function checkGreen() {
        if (this.checked && counter >= 3) {
            console.log("if test in checkGreen()");
        }
    }

I've got a problem with point 3, because i don't know how to change red light to green after uncheck one of check-boxes with green light. I spend a lot of time on it. As you can see I am not the master of Javascript and ask you for help, pleas help me :) ... and for the end i must use pure JavaScript (no jQuery). Thanks a lot for help ...
Comment: If the user can select only three checkboxes, why are they allowed/able to check four, or five? Why not prevent their interacting with more than three of them?
Comment: when they check more then free check-boxes then light will be red. This is concept of that project and i can't change this.
Comment: Okay, so how does that affect whatever happens next? Checkboxes with a 'red light' aren't submitted to the database somehow? It may be a restriction of the project, but it seems a poor UI choice.
Answer: Here is how I would do it. It is cleaner than how you were doing it before. FIDDLE. Keep an array of the checked boxes, and use it to determine which ones should be what color.
(function() {
  var checked = [];

  document.getElementById("Checkbox1").addEventListener("click",toggle);
  document.getElementById("Checkbox2").addEventListener("click",toggle);
  document.getElementById("Checkbox3").addEventListener("click",toggle);
  document.getElementById("Checkbox4").addEventListener("click",toggle);
  document.getElementById("Checkbox5").addEventListener("click",toggle);

  function toggle() {
    if (this.checked) {
        checked.push(this);
    } else {
        var index = checked.indexOf(this);
        var box = checked.splice(index,1)[0];
        box.nextElementSibling.className = "white";
    }
    refresh();
  }

  function refresh() {
    for (var i = 0; i < checked.length; i++) {
        if (i < 3) {
            checked[i].nextElementSibling.className = "green";
        } else {
            checked[i].nextElementSibling.className = "red";
        }
    }

  }

}());

Answer: For Javascript, you can use below code

and HTML used as: (note only 'name' property from input element)

        <input type="checkbox" name="choice" id="Checkbox1" />1

        <input type="checkbox" name="choice" id="Checkbox2" />2

        <input type="checkbox" name="choice" id="Checkbox3" />3

        <input type="checkbox" name="choice" id="Checkbox4" />4

        <input type="checkbox" name="choice" id="Checkbox5" />5

You can get all the checked elements and if the count is 3, mark every body with interested color.

Checkboxes in JavaScript


About Baire's Category Theorem(BCT)

Question: Consider the following theorem known as Baire's Category Theorem (BCT).
Theorem.[BCT] A non-empty complete metric space $X$ is not a countable union of nowhere dense sets.
I am interested on how to prove the following using BCT.
The intersection of every countable collection of dense open subsets of a complete metric space is dense.
My draft: Let $(A_k)$ be a sequence of dense open sets in $X$. Then for each $k$, we get
$$
A_k \mbox{ is dense }\Leftrightarrow \overline{A_k}=X \Leftrightarrow \mbox{int }A_{k}^c=\varnothing.
$$
Since $A_k$ is also open, we get
$$
\mbox{int }\overline{A_{k}^c}=\mbox{int }A_{k}^c=\varnothing
$$
and so $A_{k}^c$ is nowhere dense. We now consider the set $$\bigcup_{k=1}^{\infty}A_{k}^c.\qquad \qquad \qquad(*)$$
I am convinced that upon taking the complement of (*), the resulting set must be dense. But I don't know how to verify that step. Any tips?
Answer: Let me give you some extra tools to use, here. Some details are left to you to verify.

Definitions: A subset $A$ of a topological space $X$ is said to be nowhere-dense (in $X$) if for every non-empty open subset $U$ of $X$ there is a non-empty open subset $V$ of $X$ such that $V\subseteq U$ and $V\cap A=\emptyset$. (You should be able to prove that this is equivalent to your definition of nowhere-dense.) A topological space $X$ is said to be a Baire space if every countable union of nowhere-dense subsets of $X$ has empty interior.
Lemma 1: $X$ is a Baire space if and only if every countable intersection of open dense subsets of $X$ is dense in $X$.
Proof: Suppose $X$ is a Baire space and $\{G_n\}_{n=1}^\infty$ is a countable collection of open dense sets, so each $X\setminus G_n$ is nowhere dense. (Why?) Thus, for any non-empty open set $U$, we have that $$U\nsubseteq\bigcup_{n=1}^\infty (X\setminus G_n)=X\setminus\left(\bigcap_{n=1}^\infty G_n\right),$$ so there must be some point of $\bigcap_{n=1}^\infty G_n$ in $U$. Thus, $\bigcap_{n=1}^\infty G_n$ is dense.
Suppose countable unions of open dense sets are dense, and let $A_n$ be nowhere dense for each $n$, so each $X\setminus\overline{A_n}$ is open and dense. (Why?) Take any non-empty open $U$, so that $U$ intersects $$\bigcap_{n=1}^\infty\left(X\setminus\overline{A_n}\right)=X\setminus\left(\bigcup_{n=1}^\infty\overline{A_n}\right)\subseteq X\setminus\left(\bigcup_{n=1}^\infty A_n\right),$$ so cannot be a subset of $\bigcup_{n=1}^\infty A_n$. Thus, $X$ is a Baire space. $\Box$
Lemma 2: $X$ is a Baire space if and only if every countable union of closed nowhere-dense subsets of $X$ has empty interior. (I leave the proof to you. Lemma 1 and DeMorgan's Laws should help.)
Lemma 3: If $X$ is a non-empty complete metric space with metric $d:X\times X\to\Bbb R$, and $F$ is a non-empty closed subset of $X$, then $F$ is a complete metric space with metric $d_F$ defined by $d_F(x,y)=d(x,y)$ for all $x,y\in F$. (I leave the proof of this to you.)

Proposition: Assuming BCT holds, every non-empty complete metric space is a Baire space.
Proof: Suppose by way of contradiction that $X$ is a non-empty complete metric space, but isn't a Baire space. Then by Lemma 2, there is some countable collection $\{A_n\}_{n=1}^\infty$ of closed nowhere-dense subsets of $X$ whose union doesn't have empty interior--meaning there is some non-empty open $U$ such that $$U\subseteq\bigcup_{n=1}^\infty A_n.$$ Now, in particular, we can take a non-empty open set $V$ such that $\overline V\subseteq U.$ (Why?) Then $$\overline V\subseteq\bigcup_{n=1}^\infty A_n,$$ so $$\overline V=\overline V\cap\left(\bigcup_{n=1}^\infty A_n\right)=\bigcup_{n=1}^\infty(\overline V\cap A_n).\tag{#}$$ But $\overline V$ is a non-empty complete metric space by Lemma 3, so by BCT, $\overline V$ is not a countable union of closed nowhere-dense subsets of $\overline V$. But each $\overline V\cap A_n$ is closed and nowhere-dense in $\overline V$ (why?), so $(\#)$ gives us the desired contradiction. $\Box$
Comment: I prefer the statement of BCT as "every completely metrisable space and every locally compact Hausdorff space is a Baire space". Of course that forces a rather large change in how the results are presented.
Comment: @kahen: As it turns out, "every completely metrizable space is a Baire space" is equivalent (in ZF, at least) to the Principle of Dependent Choices. This, in turn implies the Principle of Dependent Multiple Choices, which is equivalent (in ZF) to "every locally compact Hausdorff space is Baire." In ZF, then, the bit about locally compact Hausdorff spaces is redundant to the statement of BCT. Still, those equivalence results take a good bit of finagling to prove, so it's nicer to just include the locally compact Hausdorff bit for good measure.
Comment: @CameronBuie, thank you very much.:)Your answer is more than I expected.
Answer: Hint #1. The following three properties of a set $E\subset X$ are equivalent:

$E^c$ is not dense
$E$ contains an open ball (of positive radius)
$E$ contains a closed ball (of positive radius)

Hint #2. A closed subset of a complete metric space is also a complete metric space.
Comment: @5pm, thanks for pointing out the summary. Its nice.:)

About Baire's Category Theorem(BCT)


Cant create a taxonamy menu block

Question: Steps i followed

Created a vocabulary (V) and added 5 taxonomy terms to it.
Created a new menu (M).
In edit vocabulary (created before), selected Menu M as Menu location from Taxonomy menu
settings.
Hit Save button.

Getting this error
The Taxonomy Menu rebuild process encountered an error.
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=688&op=do StatusText: OK ResponseText:
Answer: I don't think this can be answered here. It seems to be a call to Drupals Batch API that fails. But why can't be answered without some debugging and is not in the scope of your question.
Basically you are doing it right. You can try the otherway round and add menu items to you desired menu and than let them point to taxonomy/term/123. This should give you the same result.
Comment: Thanks for your replay. if i made taxonomy items as a separate menu, there should be a rework to update the items to menu. Need to create taxonomy first then to create menu item for it. If its a taxonomy, single update will be enough. Can you point out some possibilities for  Drupals Batch API fail. It will be useful for me to fix the bug.

Cant create a taxonamy menu block


Mybatis mapping getTimeInMillis

Question: I would like to say something to the effect of getCurrentTimeInMilliseconds
<code><insert id="insertToMyTable" parameterType="MyStuff">
    insert into my_table ( name, id, amount, modified_time )
    values (
        #{item.bondId},
        #{item.clientId},
        #{item.amount},
        $$-getCurrentTimeInMilliseconds-$$
     )
</insert>
</code>
I am currently implementing getCurrentTimeInMilliseconds as a java-method on the MyStuff object and it is an ugly workaround (it's not part of the MyStuff object data and is there purely as a hack-method to record database information)
if it was written in SQL I'd want to be as close to ANSI-SQL as possible - i.e. not running differently on every vendor
Answer: I didn't find any answer better than using substituing with UNIX_TIMESTAMP() - which works for MySQL. You can do 0+CURRENT_TIMESTAMP() which is Ansi SQL compatible but leaves your result as 20130303434332221 style int, not 13069293487 style (i.e. milisecond count). If that makes sense

Mybatis mapping getTimeInMillis


Drupal console set site:mode

Question: I installed a site use composer with command
composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction

I would like to set site mode to dev. If site install drupal from drupal.org, I can run command
drupal smo dev

But with composer I run
vender/bin/drupal list

and don't saw any command about setting site mode. How can do that with Drupal site install by composer. I would like to run command line, don't want config file service.yml.
Note: I ready run composer update.
Answer: The correct command for setting site in development mode is
drupal site:mode dev

Check here for more details - Debugging compiled Twig templates
Answer: drupal site:mode dev is disabled in current version (RC 17) of Drupal Console.
See here: https://github.com/hechoendrupal/drupal-console/issues/3079
and in code: https://github.com/hechoendrupal/drupal-console/blob/master/config/services/drupal-console/site.yml
Answer: I recently ran into this issue. The error message I got was:
[ERROR] Command "site:mode", is not a valid command name.

My Drupal Console version was 1.8.0.
I had to specify the URI parameter to get it to work like this as I did not have a default site:
drupal --uri="example.org" site:mode dev

Drupal console set site:mode


How can I update a TextBox from a class using events?

Question: I would like to update a form's textbox in winforms with data that is being processed from a class file.
Example:
Class.RunProcess();

Inside of RunProcess I would like to fire an event that will update the textbox with the text that I pass in on the win form.
I know you can do this with events so I don't have to make the textbox public or pass it into the many methods I have, I am just not quite sure how to start.
Edit:
Maybe I am just not clear.
I have a windows form with a text box on it.
I have a button that runs a process.
The process is in a class file outside of the form class.
Inside this process method I would like to be able to update the text box on the main form without having to pass the TextBox as a parameter to all the methods that I will have (I currently have 6 and will be more).
I thought I could subscribe to an event that would allow me to display a message in the text box while the processes ran in my class.
Comment: I'm fairly certain you could also expose your UI through an interface.
Comment: Why down votes? If I am not clear on something ask for an explanation before giving me a down vote.
Comment: I didn't downvote you before. However, you should have written the info in your EDIT first. I just upvote your question.
Comment: Sorry, I thought I was clear before :(
Answer: It's probably time to consider:

Databinding your textbox to your class
Model/View/Presenter (MVP)

For #1 (Databinding), you can use the INotifyPropertyChanged interface on your class and raise the event for changed properties.
public class BusinessModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int _quantity;
    public int Quantity
    {
        get { return _quantity; }
        set
        {
            _quantity = value;
            this.OnPropertyChanged("Quantity");
        }
    }

    void OnPropertyChanged(string PropertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }
 }

And in your form, youcan bind the .Text property of the textBox to the object in several ways.  Through the UI or in code.
Links:

Bind Better with INotifyPropertyChanged
How to: Implement the INotifyPropertyChanged Interface

Now, if you need to add to text that already exists such as in your example, you can either track the full text in the class or raise events from your class and respond in the form code.  Tracking it in the class would be better - you really don't want any logic in the form at all, which brings us back to binding and/or some form of MVP/MVC.
Answer: If you're wanting Class.RunProcess to run when an event from an external class is fired then you can do it like this
public delegate void MyDelegate();

public class MyClass
{
    public event MyDelegate Myevent;

    public void DoSomething()
    {
        this.Myevent();
    }
}
public static class Class
{
    public static void RunProcess()
    {
        txtData.Text += "Message";
    }
}
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MyClass myClass = new MyClass();
        myClass.Myevent += Class.RunProcess;
    }
}

Answer: You could add a parameter to your constructor that is a TextBox and save the reference in the class as a private variable and call that in each method.


MySQL Error 1415

Question: I'm currently coding somewhat on MySQL and got a FUNCTION.
For me the code looks fine, but MySQL throws a
Error Code: 1415
Not allowed to return a result set from a function
Error.
Function:
Cick here, pastebin.com
As i said, i dont see any syntax error in it and simply cant understand why its throwing an Error. Only on execution though, creates without any problems.
I googled already, and haven't found anything helping my on this, so i hope you can.
Thanks in advice.
Answer: I replaced all the other functions referenced in your new function with ROUND(RAND()) and it ran fine; Could it be that one of those functions might be trying to return a result set?
Comment: The functions run fine if i try them out one per one.. And i checked them and they don't try to return a result set :<
Comment: well it, if i remove the MacAllowed-statement it works. If i try the MacAllowed function in a simple select query, it works too...  >.>
Comment: well i found it but it was in a procedure o,o

MySQL Error 1415


Apache server one IP one PORT different services based on url

Question: I have one httpd server running on CentOS 7, it is listening to port 443.
I want to run two things from this server:

A normal website - https://example.com/normal/website.html
An API Endpoint running on Python (or similar language) - https://example.com/api/***

The 2nd part should redirect my request to Python API endpoint.
Please advise if this is possible or not.
Answer: Yes it is possible. Use a reverse proxy to proxy /api to your backend.
Another option would be to use api.example.com and apache vhosts. Apache is perfectly capable of running multiple vhosts on the same IP.
Comment: Thanks Lain, let me try this, will get back to you


Problema em implementação de Arvore Binaria

Question: Boa noite, pessoal. Estou tentando fazer a implementação de uma arvore binaria com metodos para inserir(insert,insertLeft e insertRight) e imprimir
(print).
Tudo vai bem ate eu tentar inserir um nó na arvore atraves do metodo insert,
eu consigo criar o no e atribuir um valor a variavel value dele, porem ao tentar imprimir a arvore nada aparece, o ponteiro root acaba sempre apontando para NULL.
Agradeço desde já
Segue o codigo:
class NodeTree {

public:

   int value;
   NodeTree * left;
   NodeTree * right;

   NodeTree() {
     value = 0;
   }

};

#include "NodeTree.h"
#include <iostream>
using namespace std;

class BinaryTree {

public:

NodeTree * root;

BinaryTree() {
    root = NULL;
}

bool isEmpty() {
    return root == NULL;
}

void makeEmpty() {
    root = NULL;
}

void insert(int opcao,int num) {

    NodeTree * node = new NodeTree;
    node->value = num;

    if (opcao == 1) {
        insertRigth(node,root);
    }

    if (opcao == 2) {
        insertLeft(node,root);
    }

}

void insertRigth(NodeTree * node1,NodeTree * root1) {

    if (root1 == NULL) {
        node1->right = NULL;
        node1->left = NULL;
        root1 = node1;
    }
    else {
        insertRigth(node1,root1->right);
    }

}

void insertLeft(NodeTree * node1,NodeTree * root1) {

    if (root1 == NULL) {
        node1->right = NULL;
        node1->left = NULL;
        root1 = node1;
    }
    else {
        insertLeft(node1,root1->left);
    }

}

void print(NodeTree * obj) {

    if (obj == NULL) {
        cout << "A arvore esta vazia, nao e possivel imprimir\n";
        return;
    }

    print(obj->left);

    cout << obj->value << endl;

    print(obj->right);

  }

};

#include "BinaryTree.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

int main(){

BinaryTree arvore;
int sentinela = 0;
int opcao;
int numero;

while (sentinela != 3) {

    system("cls");
    cout << "Opcoes da Arvore Binaria:\n\n1-Inserir\n2-Exibir em Ordem\n3-Sair\n\nOpcao desejada:";
    cin >> sentinela;

    if (sentinela == 1) {
        system("cls");
        cout << "Deseja inserir o elemento em qual lado ? 1-Direita / 2-Esquerda: ";
        cin >> opcao;
        cout << "Digite um numero:";
        cin >> numero;
        arvore.insert(opcao, numero);
    }

    if (sentinela == 2) {
        system("cls");
        arvore.print(arvore.root);
        system("PAUSE");
    }

}

return 0;

}
Answer:
eu consigo criar o no e atribuir um valor a variavel value dele, porem ao tentar imprimir a arvore nada aparece, o ponteiro root acaba sempre apontando para NULL.

O problema é que essa parte da função:
root1 = node1;

Não altera pra onde root está apontando. Pra conseguir fazer isso, você pode 1) passar o endereço do root:
void insertRigth(NodeTree *node1, NodeTree **root1)
{
    if (*root1 == NULL)
    {
        node1->right = NULL;
        node1->left = NULL;
        *root1 = node1;
    }
    else
    {
        insertRigth(node1, &(*root1)->right);
    }
}

Ou 2) receber o root1 como referência (pois assim você conseguirá alterar o endereço do ponteiro original), não precisando mudar o corpo da função antiga, apenas o protótipo da função:
// Corpo continua igual.
void insertRigth(NodeTree *node1, NodeTree *&root1)

Comment: Muito obg pela ajuda Mário ! Utilizei a segunda opcao que voce passou e deu certo !


Form $_POST data missing value of submit button

Question: I have a complex form API managed form that has several fieldsets with nested fieldsets and table elements (defined with webform component editor) with AJAX-controlled 'Add another' and 'Remove Last' buttons. There is also a form submit button at the end of the form, external to all fieldsets.
After a certain (of the order of 100) number of element groups (containing 4 or 5 fields each) are added and the form is submitted, the $_POST data generated after submitting the form does not include the value of the input element, so at a later stage the form API cannot determine the correct triggering element in function _form_button_was_clicked of form.inc.
The $form_state['input'][$element['#name']] element does not exist.
I've doubled the post_max_data and explicitly named the input element (by setting $element['#name']), all to no avail. I'd appreciate any thought on what else to try...
Comment: Have you checked the max_input_vars issue? See http://drupal.stackexchange.com/questions/90638/what-is-the-maximum-number-of-elements-allowed-in-a-form
Comment: Yes, that did the trick. Thank you! It would have been nice if php emitted some sort of error or warning under such conditions.
Comment: Usually a warning is emitted in the PHP error log. May be your Drupa isntallation is not configured to whow those PHP warnings, but it should be in the PHP error log.
Answer: As sanzante suggested, the solution is to increase php's max_input_vars setting. I did it in the site's .htaccess file.


AWS Cloud formation plus auto scaling

Question: I have created a cloud formation script to launch two instances, attach a volume on startup, and setup a load balancer. Now I am looking at setting up auto scaling and I am confused by the launch config. Does that need to basically include everything dealing with instance creation that my cloud formation script does?
Or is it possible to have the as-create-auto-scaling-group --launch-configuration tie into the cloudformation?
Answer: I found the answer.
When you use a cloud formation script by default it in fact does create a launch configuration.  I just didn't notice it because I didn't see as-describe-launch-configs in the docs.
So after running that I found the created launch config and then went on with my as-create-auto-scaling-group commands using the existing launch config.
All seems to be good to go now. Sorry it was something so simple I overlooked and hopefully this will help the next person with this question. :-)

AWS Cloud formation plus auto scaling


image overlap on the text while scale onscroll using TweenMax

Question: I'm new in HTML programming and my main idea is to make text move out of the way while TweenMax animate(scale image)
I Have a function to enlarge and reverse image in position, but then scroll image are overlaping text.
This is a default image and text position :

But then i scroll on start(like green thing on screenshot bellow) screenshot are overlaping the text:

I want to make it so when the picture is enlarged it would push the text down and not overlap over it. What should I use in this case? I can give an example of my current code if needed. I did some research and either this is so easy with something like CSS that there are no examples or it is impossible to do.
Answer: Just give that text's main parent div below css, and don't use scale for that, just use width:100%; you can achieve it.
<code>div {
    float:left;
    width:100%;
}
</code>


Minimum Number of Drinks required to Satisfy all Customomer

Question: I have found this Question in Online Coding Comp . And I was not able to solve it Efficiently .
Question :
In bar there are N customers and they can like at most M Drinks. And a customer is satisfied, If he gets at least one drink of his choice.  We need to find the Minimum no of drink to be prepared to satisfy all the Customers . Below Is an Example
N = 3 # No of Customer
M = 3 (Maximum Drinks available )
customer 1 : [ 2,1,3]
customer 2 : [1,1]
customer 3 : [2,2,3]

Note : A customer can like same drink multiple times also .
Answer : Minimum No of Drinks Required is 2
Explanation : If we prepare Drink Number 1 and 2 then All three customer can be satisfied .
My Solutions :
I created a hashMap of drinks as key and Customer value
Drink  : Customer
 1 : [1 ,2]
 2 : [1,3]
 3 : [1,3]

And the I would pick up the largest List of values (Since all the customers will be unique) from Hashmap.

All are equal in this case, so I will pick Drink 1's values [1,2]
globalList = [1,2]
noOfDrinksRequired = 1

And now I will find Inter Section with All other list , whichever intersection is largest I will add it to Global List (globalList) and  increment the no of drinks required (noOfDrinksRequired) By 1 . And also keep track of number of element in List (" Number of Customer "). If the list length is equals to number of customer, then I quit .
globalList = globalList ∩ [1,3] # Drink 2's or 3's value
  Now the golbalList = [1,2,3]
  And noOfDrinksRequired += 1
  Since the golbalList.length == N # no of Customer 3
  If not repeat step 2

I know this is not very optimize solution ( Space complexity m*n and time complexity not sure of ) . Can any one tell me the Optimize solution to this problem . Also I am not sure if my solution will work 100% .
Comment: Please read on NP-complete problems. Yours is a set-cover problem. In particular this means that if you think you have an O(n^2) algorithm you probably need to think again.
Comment: Well I did not calculated it mathematically . it was approximate guess , and could be wrong also .
Comment: Well it is wrong. If you want an approximate solution then I guess your solution is the same as the [greedy algorithm](https://en.wikipedia.org/wiki/Set_cover_problem#Greedy_algorithm) though it's hard to tell for sure.
Answer: This is a classic Set cover problem -- https://en.m.wikipedia.org/wiki/Set_cover_problem
It is in fact one of Karp's 21 NP-complete problems. There are approximate and greedy solutions to this.
Comment: It would be nice to mention that the formulation of this problem as a set cover is to take the sets of customers who like a particular drink and the universe the set of all customers. If you apply set cover literally to the sets given in the question you'll get a set of customers who between them like all the drinks.


Get the URL generated from a form on submit with JavaScript

Question: Is it possible to catch the URL generated from a form when firing its 'submit' event?
I know I can generate the URL from data
I'm not talking about form's action URL
I mean the ?field=value&other-input-name=value& ... part
Scenario:
We have a form and a JavaScript script which sends an Ajax request to a PHP script.
I usually do like this:

Register for the form's submit event
Prevent the default behavior
Construct a URL from data
Open an HTTP request with the constructed URL

Now, I was wondering, when firing 'submit' normally (on non-Ajax requests) the URL gets constructed by the form, which then uses that URL to send data to the PHP counterpart.
How can I 'catch' that URL? There aren't any clues from the event itself which doesn't seem to store it, or at least I haven't been able to find it.
It must be somewhere!
Comment: You can get the form's action attribute. If no action attribute is defined, then the current page is the target.
Answer: This is possible and easy with the objects URLSearchParams and FormData.
FormData is an object representation of a form, for using with the fetch API. It can be constructed from an existing  element like this:
let form = document.forms[0];
let formData = new FormData(form);

Then comes the URLSearchParams object, which can be used to build up query strings:
let search = new URLSearchParams(formData);

and now all you need to do is call the toString function on the search object:
let queryString = search.toString();

Done!
Comment: Some browser compat issues with URLSearchParams, lovely solution though!
Comment: Perfect, the more you use JavaScript the more you learn that there are still lots of things you need to learn.
Answer: If you mean getting the form's action URL, that URL can be retrieved like this:
document.getElementById("form-id").action

If you are using jQuery and assuming you are doing an Ajax request, it would be like this:
var el = $('#form-id');
$.ajax({
    type: el.attr('method'),
    url: el.attr('action'),
    data: el.serialize(),
    context: this
}).done(callback);

Comment: Nope, I'm talking about the generated serialized URL data which gets constructed on submission, the
`?firstname.lastname@example.com&name=myname ...` part!
Comment: sorry buddy, don't yet have the privileges to comment and seek clarification, so posted this as an answer, thought that might've been what you are asking.
Answer: To put it simply, you can't. The best you can do is to collect the form field values yourself, or using jQuery's .serialize() function, which returns those values exactly as you'd expect:
name=value&name2=value2

Comment: I don't want it simple, I know I can get them from field as usual, please elaborate sir
Comment: You can not intercept the request that form will send to the server.
Comment: Hello from the future, where it is possible to intercept HTTP requests in JavaScript.
Comment: @Greg the only way I can think of for regular pages is via service workers - a very convoluted way at that. But thank you!
Answer: As already stated, you cannot get the generated URL containing the form values that the browser generates, but it is very easy to construct it yourself.
If you are using jQuery then use serialize(). If not, refer to the post Getting all form values by JavaScript.

var targetForm = $('#myForm');
var urlWithParams = targetForm.attr('action') + "?" + targetForm.serialize();
alert(urlWithParams);

<form action="/search/"  id="myForm" method="get">
  <input name="param1" type="hidden" value="1">
  <input name="param2" type="hidden" value="some text">
</form>
Answer: You can use javascript to generate it:

<form onsubmit='return test(this);'>
<input name=field1 value='123'>
<input type=checkbox name=field2 checked>

<input type=submit>
</form>


Solution of the differential equation $(1+y^2-x^2)y'=\frac{1}{x}, y(1)=1$

Question: Solution of the differential equation $(1+y^2-x^2)y'=\frac{1}{x}, y(1)=1$ is the differential equation have solution ? and is this solution is exist?
I am trying to prove by using picard's theorem
here given ODE is $(1+y^2-x^2)y'=\frac{1}{x}$
then $f(x,y)=\frac{1}{(1+y^2-x^2)x}\Rightarrow |f(x,y)|=|\frac{1}{(1+y^2-x^2)x}|$  from here how to processed
Answer: $(1+y^2-x^2)y'=\dfrac{1}{x}$ with $y(1)=1$
$(1+y^2-x^2)\dfrac{dy}{dx}=\dfrac{1}{x}$ with $y(1)=1$
$\dfrac{1}{x}\dfrac{dx}{dy}=1+y^2-x^2$ with $x(1)=1$
Let $u=\dfrac{1}{x^2}$ ,
Then $\dfrac{du}{dy}=-\dfrac{2}{x^3}\dfrac{dx}{dy}$
$\therefore-\dfrac{x^2}{2}\dfrac{du}{dy}=1+y^2-x^2$ with $u(1)=1$
$\dfrac{du}{dy}=2-\dfrac{2(y^2+1)}{x^2}$ with $u(1)=1$
$\dfrac{du}{dy}=2-2(y^2+1)u$ with $u(1)=1$
$\dfrac{du}{dy}+2(y^2+1)u=2$ with $u(1)=1$
I.F. $=e^{\int2(y^2+1)~dy}=e^{\frac{2y^3}{3}+2y}$
$\therefore\dfrac{d\left(ue^{\frac{2y^3}{3}+2y}\right)}{dy}=2e^{\frac{2y^3}{3}+2y}$ with $u(1)=1$
$u=2e^{-\frac{2y^3}{3}-2y}\int e^{\frac{2y^3}{3}+2y}~dy+Ce^{-\frac{2y^3}{3}-2y}$ with $u(1)=1$
$Ce^{-\frac{2}{3}-2}=1$
$C=e^\frac{8}{3}$
$\therefore u=2e^{-\frac{2y^3}{3}-2y}\int_1^ye^{\frac{2y^3}{3}+2y}~dy+e^{\frac{8}{3}-2y-\frac{2y^3}{3}}$
$\dfrac{1}{x^2}=2e^{-\frac{2y^3}{3}-2y}\int_1^ye^{\frac{2y^3}{3}+2y}~dy+e^{\frac{8}{3}-2y-\frac{2y^3}{3}}$
$x^2=\dfrac{1}{2e^{-\frac{2y^3}{3}-2y}\int_1^ye^{\frac{2y^3}{3}+2y}~dy+e^{\frac{8}{3}-2y-\frac{2y^3}{3}}}$


Variance of the Sum of Correlated Variables in R

Question: I'm looking to compute $n\text{Var}\left(\frac{1}{n}\sum_{i=1}^nX^{(i)}\right) = \frac{1}{n}\sum_{i=1}^n\sum_{j=1}^n\text{Cov}\left(X^{(i)},X^{(j)}\right)$ in R. Assuming the X's not to be iid, we get
$$ n\text{Var}\left(\frac{1}{n}\sum_{i=1}^nX^{(i)}\right) = \text{Var}\left(X^{(1)}\right) + 2\sum_{k=1}^{n-1}\left(1-\frac{k}{n}\right)\text{Cov}\left(X^{(i)},X^{(i+k)}\right).$$
But as far as I can see, $\text{Cov}\left(X^{(i)},X^{(i+k)}\right)$ is the auto-covariance $C_{XX}(k)$, i.e.
$$ n\text{Var}\left(\frac{1}{n}\sum_{i=1}^nX^{(i)}\right) = \text{Var}\left(X^{(i)}\right) + 2\sum_{k=1}^{n-1}\left(1-\frac{k}{n}\right)C_{XX}(k).$$
However, when I try to compute this value for a simple Markov chain I get very inconsistent results. So I'm just wondering if anyone could help me figure out where this has gone wrong? Or is this method jut infeasible and I should rather compute several Markov chains and compute the empirical variance?
I must add that I'd like to use this on a MCMC method on a multivariate distribution where I'd like to compute $n\text{Cov}\left(\frac{1}{n}\sum_{i=1}^nX^{(i)}\right)$.
# Generates MC with transition probability matri K
MC <- function(x0, K, nsim) {
  X <- array(dim=nsim)
  X[1] <- x0
  for (i in 2:nsim) {
    X[i] <- sample(c(1,2), 1, prob = K[X[i-1],])
  }
  I <- as.numeric(X == y)
}

# Computes nCov(1/n sum X)
ncov <- function(x) {
  n <- dim(x)[1]
  a <- acf(x, plot=FALSE, type='covariance', lag.max=Inf)$acf
  c <- sum(c(1,2*(1-seq(1,n-1)/n))*a)
  return(c)
}

K = matrix(c(0.9,0.2,0.1,0.8),nrow=2)
x <- matrix(MC(x0, K, 100000))
ncov(x)

Comment: What does $X^{(i)}$ denote?
Comment: If your samples are multivariate, i.e. $X = (X_1, \dots, X_n)$, $X^{(i)}$ is sometimes used denote sample number $(i)$ to not confuse with variable indexing. With this notation, $X_j^{(i)}$ can be seen as variable $j$ of sample $i$.
Answer: What you're doing, although theoretically valid, is not computationally stable.  This is because although your estimator is a consistent estimator, for large $k$ there are very few samples available to estimate the lag covariance, leading to bad estimates of this value.
There has been a rich study of estimating this variance term in the MCMC literature. There are estimators that weight and truncate the lag $k$, and these estimators are called spectral variance estimators. They have been shown to be strongly consistent estimators in same Flegal et.al (2010) paper, however, they are a tad bit slow to compute.
There is also the faster batch means estimator, mentioned in the same paper as above. They have also been shown to be consistent (in the same paper).
However, the above paper is only meant for univariate quantities, so these do not assess the covariance for a Markov chain from a multivariate distribution. You can find details of this covariance matrix in the post here. There has recently been work done in estimating the variance-covariance matrix for Markov chains from multivariate distributions. Extensions of the spectral variance estimators are in Vats et.al (2018) and extensions of the batch means estimator are in Vats et. al. (2017). Note that for this multivariate setting the spectral variance estimators are often too computationally expensive.
You can implement all these estimators using the R package mcmcse. This post has some more information about the implementation.
Comment: Thank you so so much! Exactly what I was looking for. And also thank you for the references, I really appreciate it


Unir variáveis e incluir 0 a um campo de 11 dígitos php

Question: Estou gerando um código de barras,ele terá uma base que será da seguinte forma:

Numero da loja:     $v_ficha_loja = $row['ficha_loja'];   = (1)ou (2)etc..
Numero do ambiente: $v_ficha_ambiente = $row['ficha_ambiente']; (1)ou (2)etc..
E um numero sequencial: 1,2,3,4,5,6,7, .... 100.

Pois estou gerando um relatório e cada relatório terá seu código de barras, duvida:
  Com base acima o código de barras terá 11 números,da seguinte forma:

x1x2xxxxxx1
x1x1xxxxxx2
x1x2xxxxxx3
x1x2xxxxxx4
x1x2xxxxx10
x1x2xxxxx11
x1x2xxxxx12
x1x2xxxx100

Onde coloquei x quero seja incluso o 0 como posso fazer isso ?
Já tenho o código do sistema e do código de barras todo pronto,só preciso gerar esse numero.
Resultado final pretendido:

01010000001
Comment: `0(Numero da loja)0(Numero do ambiente)0000(numero sequencial)`, seria essa a sequência de números? Os 2 primeiros zeros são mutáveis, ou *todo* `x` será sempre zero?
Comment: O que já tentaste fazer?
Answer: Caso o numero da loja e o numero do ambiente sejam SEMPRE precedidos de zero, pode-se usar str_pad para criar a repetição de zeros.
str_pad( 1   , 11 , '0' , STR_PAD_LEFT ) // 00000000001
str_pad( 10  , 11 , '0' , STR_PAD_LEFT ) // 00000000010
str_pad( 100 , 11 , '0' , STR_PAD_LEFT ) // 00000000100

echo '0102' . str_pad( 100 , 11 , '0' , STR_PAD_LEFT ) // 010200000000100

Exemplo com printf
printf( '%s1%s2%011s' , 0 , 0 , 1   ); // 010200000000001
printf( '%s1%s2%011s' , 0 , 0 , 10  ); // 010200000000010
printf( '%s1%s2%011s' , 0 , 0 , 50  ); // 010200000000050
printf( '%s1%s2%011s' , 0 , 0 , 100 ); // 010200000000100

Answer: sprintf()
O sprintf é uma alternativa bem prática para formatar sua string:
$barra = sprintf( "%'02d%'02d%'07d", $v_ficha_loja, $v_ficha_loja, $v_sequencia );

Veja funcionando no IDEONE.

% para indicar substituição.
' para indicar qual caractere de preenchimento (por isso usamos '0)
em seguida, o número de dígitos
finalmente d para indicar que é um inteiro

A sintaxe é a mesma do printf mencionado pelo Papa Charlie, mas como você vai gerar barras, e não o valor na tela, faz mais sentido armazenar em string.
Mais detalhes no manual do PHP.
str_pad()
Com str_pad você diz qual é o valor, seguido do número de casas, do caractere de preenchimento e em qual lado ele deve ser adicionado:
$barra = str_pad( $v_ficha_loja    , 2, '0', STR_PAD_LEFT )
        .str_pad( $v_ficha_ambiente, 2, '0', STR_PAD_LEFT )
        .str_pad( $v_sequencia     , 7, '0', STR_PAD_LEFT );

Veja funcionando no IDEONE.
Mais detalhes no manual do PHP.
substr()
Esta alternativa é só pra mostrar maneiras de se trabalhar com strings em PHP. Postei mais para ilustrar e pensar fora da caixa:
    $barra = substr(      '00'.$v_ficha_loja    , -2 )
            .substr(      '00'.$v_ficha_ambiente, -2 )
            .substr( '0000000'.$v_sequencia     , -7 );

Veja funcionando no IDEONE.
Mais detalhes no manual do PHP.


General procedure for determining the name of an interval given a major key / diatonic collection

Question: I'm attempting to program a library that lets one make use of concepts from Peter Westergaard's tonal theory.
The current problem I'm trying to solve is to determine the specific name of an interval given two notes (including octave, so something like B#4 and Cb5) AND a diatonic collection (which you can just think of as a major key, if you are unfamiliar with tonal theory).
Tonal theory states that the name of the interval between two notes is based on the number of major and minor seconds that comprise the interval. Here's the definition for every interval up to an octave:

minor 3rd - 1 minor 2nd, 1 major 2nd
major 3rd - 0 minor 2nds, 2 major 2nds
diminished 4th - 2 minor 2nds, 1 major 2nd
perfect 4th - 1 minor 2nd, 2 major 2nds
augmented 4th - 0 minor 2nds, 3 major 2nds
diminished 5th - 2 minor 2nds, 2 major 2nds
perfect 5th - 1 minor 2nd, 3 major 2nds
augmented 5th - 0 minor 2nd, 4 major 2nds
minor 6th - 2 minor 2nds, 3 major 2nds
major 6th - 1 minor 2nd, 4 major 2nds
diminished 7th - 3 minor 2nds, 3 major 2nds
augmented 6th - 0 minor 2nds, 5 major 2nds
minor 7th - 2 minor 2nds, 4 major 2nds
major 7th - 1 minor 2nd, 5 major 2nds
perfect octave - 2 minor 2nds, 5 major 2nds
imperfect octave - 1 minor 2nds, 6 major 2nds
or 3 minor 2nds, 4 major 2nds

Let me make sure my assumptions are correct, first. I'm assuming that you cannot always determine the specific name of an interval without knowing the key/diatonic collection that the notes are present in. For example, take the interval C to E. If we are in the key of C major (diatonic collection starting on C), you would go C->D->E which is 2 major 2nds - a major 3rd. But, if you are in the key of D major, you would be starting on a note that isn't in the scale. I'm not sure of the process for naming the interval, given this situation (this is part of the question), but you could go C->C#->D->E, which would be 2 minor 2nds and one major 2nd - a diminished 4th. Given that, I assume you can't just say that C to E is a major 3rd regardless of the context those notes appear in.
My other assumptions is that counting 2nds is a valid way to determine the interval name.
With that in mind, my question is this: How do you determine how many major and minor 2nds are in an interval, given a major key (with the goal of naming the interval)?
I would guess that, if the interval notes are in the scale, you simply walk up through the scale and count the intervals.
But I don't know how to handle the case for when the interval notes are not on the scale. Here's what I've tried to do to solve this:

You can think of any off-key note as being a deviation above or below
  an on-key note. You determine whether it is above or below using the
  note name. For example, in D major, let's consider the off-key note C.
  The only time the letter C appears in the major scale is as C#. So we
  think of C as being a half-step below C#. Similarly, we think of D# as
  being a half-step above D in that key.
Given that, when given an interval and a key, determine how the
  interval notes deviate from the notes in the key. For the bottom note,
  if the deviation is above (like D# in the previous example), then,
  when counting up, use a 2nd to get up to the closest on-key note (in
  the D# example, this would be using a half-step to get up to E). Then
  count as normal. If the deviation of the bottom note is below (like C
  in our example), then count as normal, but start from the note it is
  below (so C#). If there were any minor 2nds, remove one and add a
  major 2nd. If there weren't any, add a minor 2nd to the count.

I'm honestly not sure how to handle "top note deviations", but at this point you can at least see what I tried. Based on how hacked-together and complicated it seems, I believe it's unlikely it's right, anyway, so it's not worth continuing to try to flesh it out.
So, does anyone have a method that actually works to determine the number of seconds in an interval, given a major key? Or, for that matter, just a method for determining the name of an interval, given a major key? I assume there is a method, but I haven't been able to find a good resource through Google.
EDIT:
I did find some potential resources for this, going to take a look through them. It seems my assumptions may be wrong:
http://www.eartrainingmastery.com/en/blog-and-music-theory/blog-en/299-enharmonically-equivalent-intervals-augmented-second-or-minor-third
https://www.musicgoals.com/webhelp/interval_naming.htm
Comment: Welcome to the Site! It sounds like you need to be acquainted with **interval vectors** and **set theory**. Try looking them up and see if they help.
Comment: Interval vectors do not have the ability to distinguish between a major third and a diminished fourth (and other enharmonically equivalent intervals). The concept of a diminished fourth doesn't even exist in interval vectors. I need a tool that is able to distinguish between enharmonically equivalent intervals, but it seem interval vectors just assume that a given semitone distance always has a specific interval name (i.e. it assumes 4 semitones is always a major 3rd). But that is NOT the case in music - 4 semitones is sometimes called a diminished 4th.
Comment: You are correct about interval vectors, though I wonder why you are speaking about them negatively. Not distinguishing between enharmonic spellings is *kind of the point* - in music most theoretical constructs are developed to describe *how music sounds* not *how it looks* - which by-and-large is the less important of the two. AFAIK, I directly answered your question. I am also puzzled *why* it is important for you to name intervals via their enharmonic spelling? Lastly, I really don't appreciate your patronizing tone; it is unnecessary and unwelcome.
Comment: Oh, I have to honestly apologize, then! Sorry, I wasn't intending to be patronizing (I'm not sure how it came off as patronizing, but I can understand how that wouldn't carry over in text). I never intended to communicate that interval vectors weren't useful or anything negative, I just wanted to try to be clear about why they didn't solve my problem - and I tried to be very clear about it because I think it's a potentially confusing question. Sorry if my overly-wordy response came off as patronizing!
Comment: If the solution to your problem is not clear to you from the above question and answer, the only piece of the puzzle that is not explicitly named in that Q&A is that diatonic collections are completely irrelevant to naming intervals. C-Fb is a diminished fourth in any key, C-E is a major third in any key.
Answer:
"So, the real way to figure out an interval name, given 2 pitch classes"

I think this is the wrong starting point. Pitch class is just the collection of sounds (tones) that are 1 octave apart. In a well-tempered 12 tone system, 0, 1, 2, ... 11 are pitch classes.

"First, count the distance between the letters of the pitch classes, then add one."

Going by this I'd say your starting point is not pitch class, but note names. So I'd reword your step to:
"count the difference between the numerical value of the letters of the note names (ignoring the postfix that might be added due to flattening or sharpening)"
More formally to calculate from note N1 to note N2 you'd do:
<code>(((N2.numVal - N1.numVal) + 7) mod 7) + 1
</code>

"Subtract the Semitone Count (from the last step) from the actual half step count and use the Interval Type to figure out the interval quality using the table"

I think the operation is ok, but I don't really agree about your use of terms "interval type" and "interval quality". I'd say, "third" is an interval type, "minor" and "major" is a quality. You don't say, "I have a majord 3rd with the minor quality" - that doesn't make sense: minor third and major third are separate entities and both first class citizens.

"...and there you have your interval!"

Final word: I think i'd add "harmonic" to interval. If you're talking about "melodic intervals", the operation would start the same but would also have to reflect "descending" and "ascending" as properties, and you'd probably care about the octave. I mean, in melody it is a huge difference whether you repeat a note (prime interval) or take a leap of an octave. That is not to say octaves don't matter at all in harmonic sense: It makes a big difference in sound whether you're hearing a 2nd as compared to a 9th;
Comment: Thanks for the corrections! I updated my answer to use more accurate terminology. I did mean to say "note" instead of pitch class.
Comment: I agree with everything here except that the minor and major 3rds are *always* separate entities. Set Theory proves that minor and major triads are actually *the same* chord.
Comment: @jjmusicnotes Interesting. I'd have to admit that I don't know enough about set theory to oversee it. First thing that comes to mind is that major and minor triads are inversions (mirrors) of each other. Is that how the are "the same" according to set theory? Even if that is the case, it seems to this still does not invalidate my remark that the *intervals* minor and major third aren't completely separate entities.
Comment: @dfhwze, uh, indeed. We could just remove the +7 if we're doing mod. I think I wrote it and then modified the calc to make it work regardless of which one is lower.
Answer: As noted, the term "Pitch Class" (PC) assumes enharmonic equivalence, and there are only 12 of them. Rather than calling them "note names" I have also seen the term "Tonal Pitch Class" (TPC) used to represent the non-enharmonic version of this concept. IOW, F# and Gb have the same PC, but a different TPC. This terminology, for example, is used by the open source notation editor Muse Score.
http://musescore.org/en/plugin-development/tonal-pitch-class-enum
If the 12 PCs can be arranged via the well-known "Circle of Fifths", the TPCs can be arranged using its lesser-known cousin, the "Line of Fifths". This can be formed by taking the circle, and disconnecting it at the point where the sharps become flats, and then stretching it out infinitely in both directions. One direction constantly becomes more sharp, the other direction, more flat. The following PDF is the first Google result for "line of fifths" and introduces the concept nicely.
http://theory.esm.rochester.edu/temperley/papers/temperley-ma00.pdf
Once you have this line of fifths, determining the proper interval name is just a matter of counting the distance between the two TPCs on this line. In the diagram below, the left column is the line of fifths, and the right column is the name of the interval from D to that note (I chose D because it lies exactly between the flats and the sharps). To start from another note besides D, you could just shift the right column up or down until PU (perfect unison) is next to the desired starting note.

  …     …
  F♭    d3
  C♭    d7
  G♭    d4
  D♭    dU
  A♭    d5
  E♭    m2
  B♭    m6
  F     m3
  C     m7
  G     P4
  D     PU
  A     P5
  E     M2
  B     M6
  F♯    M3
  C♯    M7
  G♯    A4
  D♯    AU
  A♯    A5
  E♯    A2
  B♯    A6
  …     …

You'll notice that the interval names fall into a nice pattern. The numeric part of the name follows a repeating pattern of {U, 5th, 2nd, 6th, 3rd, 7th, 4th} while the qualitative descriptors are arranged with 3 perfects in the center, 4 minors/majors on each side, followed by 7 diminished/augmented, and then 7 doubly-diminished/doubly-augmented, and so forth. These later aren't shown here, but they can be found by a simple extension of the chart.
Comment: @CalebHines I just formatted your post with pre tags. Is this better for you?
Answer: Well, it seems like the answer to the question is that my assumptions are wrong. (Note to self for the future: I should've just looked up intervals on wikipedia as a starting point and I could've easily answered my question.)
My first assumption was that you cannot determine the name of an interval without knowing the key it exists in. That seems to be wrong given the new sources I discovered. You don't need to know anything other than the notes.
My second assumption was that using seconds is a valid way to name an interval. I got this from reading Introduction to Tonal Theory, where Westergaard describes each interval in terms of the major and minor seconds they are composed of. I don't really know why he does this.
So, the real way to figure out an interval name, given 2 notes, is this (I'm only handling intervals up to a major 10th. Any larger interval is generally referred to as a compound of some number of octaves + an interval less than an octave):
First, count the difference between the numerical value of the letters of the note names (ignoring the postfix that might be added due to flattening or sharpening).
Next, figure out the interval naming scheme and semitone count. Use this table:

    |-----------------|--------------------------|
    | Interval Number | Scheme  | Semitone Count |
    |-----------------|---------|----------------|
    | 1               | Perfect | 0              |
    | 2               | Major   | 2              |
    | 3               | Major   | 4              |
    | 4               | Perfect | 5              |
    | 5               | Perfect | 7              |
    | 6               | Major   | 9              |
    | 7               | Major   | 11             |
    | 8 (octave)      | Perfect | 12             |
    | 9               | Major   | 14             |
    | 10              | Major   | 16             |
    |-----------------|---------|----------------|

Now count the half steps between the actual interval. Subtract the Semitone Count (from the last step) from the actual half step count and use the Interval Naming Scheme to figure out the interval quality using the table:

    |-------------------|------------|---------------|-----------|------------------|
    | -2                | -1         | Scheme        | +1        | +2               |
    |-------------------|------------|---------------|-----------|------------------|
    | diminished        | minor      | Major         | augmented | doubly augmented |
    | doubly diminished | diminished | Perfect       | augmented | doubly augmented |
    |-------------------|------------|---------------|-----------|------------------|

For example, if the interval number is 5 but you count 6 half steps, you would do 6-5 = +1 and look at the Perfect row, giving you augmented.
...and there you have your melodic interval (a harmonic interval would need to also describe which note came first)!
Comment: It's occasionally useful to refer to the 9th, 11th, and 13th intervals because they turn up in extended chords, where they function a bit differently from 2nds, 4ths, and 6ths.
Comment: I see, thanks for the clarification.  Why go through the trouble of programming a library that makes use of a tonal theory that was never accepted and that no one uses?
Comment: "You don't need to know anything other than the names of the pitch classes." I think I understand, but I think technically, there is no such thing. Or rather PC0 could have multiple names: C, B♯ D. I'm not sure though what the proper name is for that whing we denote by "c". "note name" sounds wrong since we can talk about that think without talking about an actual note.
Comment: Actually, "A-C" is a minor 3rd. I don't understand how you are arriving at "2" for a distance between Ab and C. Also, it is pointless to do anything more than 12 semitones (an octave) as every theorist would immediately just displace the pitch class at the octave and bring it down to a manageable size. I still don't understand why the enharmonic nomenclature is so important? Regardless of key, the names you're using are applied *with respect to* the lower pitch of the interval. Therefore, Ab-C# would be an augmented 3rd. It's as simple as that. Lastly, no one uses the Westergaard text.
Comment: Oops, accidentally switched the intervals in my first comment. The number "2" is the distance between the letters A and C in an ordered alphabet. I care about the nomenclature because I actually care about the notational aspect, and also because I think it's interesting.
Comment: RolandBouman - yeah, that should've said "note" instead of "pitch class". I updated my answer.
@jjmusicnotes I'm just using it to practice writing code in a programming language I'm learning. Also, personally, I'm interested in seeing how useful it might be. Besides, the stuff I've developed so far isn't really specific to tonal theory, so I can use that code as a building block to also implement a more relevant and accepted theory if I want. What would you recommend as a theory that is accepted and that many people use?
Comment: @chairbender - since the focus of your class is learning a programming language and *not* music theory, why give yourself extra, unnecessary work? I think you'd have a heck of an easier time using **Set Theory** for your project. It was pioneered by a composer / mathematician (Milton Babbitt) and has been used by tens of thousands of people over the past 50 years to create music. **Interval Vectors** are a part of Set Theory, and I think would help unify and simplify the musical aspect of it so you can focus on learning the programming part of the course.
Comment: @BraddSZonye - I agree that they function differently, but I would still say that theorists would bring them down an octave to gain a better understanding of the horizontal contrapuntal lines.
Comment: It's not a class (I'm doing it in my spare time), and I do care about learning more music theory. I'll definitely look into those concepts, thanks!


Associated points of Spec $\mathbb{C}[x,y]/ I$

Question: Suppose we know that the only associated points of
Spec $\mathbb{C}[x,y]/ I$ were
$[(y-x^2)]$, $[(x-1,y-1)]$ and $[(x-2,y-2)]$. Is there enough information
to deduce if this scheme is reduced or not?
I have been thinking about it, but I am confused. I would appreciate
any comments/hints. Thank you!
Answer: A reduced ring has no embedded primes, see here: http://stacks.math.columbia.edu/tag/031O
But your ring has.
Comment: Right. Of course! $[(x-1, y-1)]$ is an embedded point! Would you happen to know if it is possible to know if the scheme is reduced at $[(x-2, y-2)]$ or not by the information given?
Comment: No you cannot deduce anything about that. The irreducible component of that point could be the point itself. You have no information, whether this is a reduced point or a thick point.


Docker container running Gulp runs tasks, but not when "watching"

Question: I've put my Gulp stuff into a Dockerfile:
FROM node:14
WORKDIR /app
COPY package*.json ./
COPY gulpfile.js ./
...
RUN npm install
RUN npm install -g gulp
EXPOSE 3000
CMD ["gulp"]

When I run the following build and run it works and files are generated:
docker build . -t webteam/gulp
docker run --rm -it -v ${pwd}/src:/app/src -v ${pwd}/dist:/app/dist -p 3000:3000 webteam/gulp styles

Here's the styles task in the gulpfile:
const styles = () => src(SASS_SRC)
  .pipe(sourcemaps.init())
  .pipe(sass().on('error', sass.logError))
  .pipe(autoprefixer({
    cascade: false,
  }))
  .pipe(sourcemaps.write())
  .pipe(dest('./dist/css'));

This works perfectly.
However, when I run the default task which is written to "watch" for file changes, the task seems to start up OK. Browsersync even works from the container to my host machine. And it looks OK in the terminal.... but any file changes are not detected.
Here's my default task:
exports.default = () => {
  browserSync.init({
    server: {
      baseDir: './dist/',
    },
    startPath: '/homepage.html',
    ghostMode: false,
  });

  // watch the src files and html files for changes
  watch(SASS_SRC, exports.styles);
  watch(JS_SRC, exports.scriptsDev);
  watch(JS_SRC, exports.scriptsProd);

  // watch the dist files, and browser sync when changes
  watch(['./dist/**/*', './demo/**/*']).on('change', browserSync.reload); // TODO remove demo at some stage
};

What is needed for Docker environment to notice changes within files of the linked directory (src) to trigger the watch functions?
UPDATED
Added usePolling to watch options, as I think this is a solution to my problem if I can get it working. Add added some addition options from the docs that work with usePolling - https://gulpjs.com/docs/en/api/watch#options:
const SASS_SRC = './src/scss/**/*.scss';
const JS_SRC = ['./src/js/**/*.js', './src/js/modules/**/*.js'];
const HTML_FILES = './dist/**/*';

...

exports.default = () => {

  // Enable polling
  const watchOptions = {

    // When false, the watcher will use fs.watch() (or fsevents on Mac) for watching. If true,
    // use fs.watchFile() polling instead - needed for successfully watching files over a network
    // or other non-standard situations. Overrides the useFsEvents default. This option is passed
    // directly to chokidar.
    usePolling: true,

    // Combine with usePolling: true. Interval of file system polling. This option is passed directly to chokidar.
    interval: 100,

    // Combine with usePolling: true. Interval of file system polling for binary files. This option
    // is passed directly to chokidar.
    binaryInterval: 300,

    // When true, uses fsevents for watching if available. If explicitly set to true, supersedes the
    // usePolling option. If set to false, automatically sets usePolling to true. This option is passed
    // directly to chokidar.
    useFsEvents: false,

  };

  browserSync.init({
    server: {
      baseDir: './dist/',
    },
    startPath: '/homepage.html',
    ghostMode: false,
    watchOptions,
  });

  // watch the src files and html files for changes
  // @see https://gulpjs.com/docs/en/api/watch
  watch(SASS_SRC, watchOptions, exports.styles);
  watch(JS_SRC, watchOptions, exports.scriptsDev);
  watch(JS_SRC, watchOptions, exports.scriptsProd);

  // watch the dist files, and browser sync when changes
  watch(HTML_FILES, watchOptions).on('change', browserSync.reload); // TODO remove demo at some stage
};

However, it still doesn't register when I change a SCSS file (run styles) or change an HTML file (reload the browser)
I also tried changing the watch first argument (the path to watch files) to the container path:
const SASS_SRC = '/app/src/scss/**/*.scss';
const JS_SRC = ['/app/src/js/**/*.js', '/app/src/js/modules/**/*.js'];
const HTML_FILES = '/app/dist/**/*';

But it doesn't make any difference. Anything else I could try, or am I doing something wrong?
Answer: Docker's file sharing does not always propagate file system events (particularly on Windows or Mac), causing tools that rely on these events to detect changes to fail.
To work around this issue, you can use polling as a fallback mechanism for file watching. That means instead of relying on file system events, Gulp will periodically check for file changes.
That would have higher CPU usage, but is a reliable workaround when working within Docker containers on Windows or Mac.
You can modify your Gulp watch task to use polling by specifying the usePolling option.
Your default task would then be:
const { watch, series } = require('gulp');
const browserSync = require('browser-sync').create();

// Assuming exports.styles, exports.scriptsDev, and exports.scriptsProd are defined elsewhere

exports.default = () => {
  browserSync.init({
    server: {
      baseDir: './dist/',
    },
    startPath: '/homepage.html',
    ghostMode: false,
  });

  // Enable polling
  const watchOptions = {
    usePolling: true,
  };

  // watch the src and html files for changes with polling
  watch(SASS_SRC, watchOptions, exports.styles);
  watch(JS_SRC, watchOptions, exports.scriptsDev);
  watch(JS_SRC, watchOptions, exports.scriptsProd);

  // watch the dist files, and browser sync when changes
  watch(['./dist/**/*', './demo/**/*'], watchOptions).on('change', browserSync.reload);
};

That introduces the watchOptions object with usePolling: true, which is passed as an argument to Gulp's watch method.

However, it still doesn't register when I change a SCSS file (run styles) or change an HTML file (reload the browser)

If the core implementation of polling with Gulp's watch task within Docker is correctly set up, but the problem persists, then the issue might not solely be related to file watching mechanisms but could involve other aspects of the Docker or Gulp configuration.
Make sure the Docker volume mounts are correctly configured to reflect changes made on the host system within the container. Incorrect or missing volume mounts can lead to situations where changes are not visible inside the container, hence not detectable by Gulp's watch mechanism, even with polling enabled.
docker exec -it <container_name_or_id> /bin/sh
cd /app/src
ls -l
# Modify a file within the mounted directory on your host system.
# Back in your container terminal, list the contents again to check if the change is reflected:

File watching can sometimes be affected by file system permissions. Make sure the Docker container runs with a user having adequate permissions to read and watch the directories in question.
To isolate the issue, try testing the polling mechanism outside of Docker with a simple Gulp watch task on your host system. If polling works as expected outside of Docker, the issue likely lies with the Docker environment or configuration.
Simplify your Gulp and Docker setup to the bare minimum needed to test the watch functionality.
And increase the verbosity of Gulp's output to get more insights into what Gulp is doing.
// Example for increasing verbosity in Gulp tasks
const gulp = require('gulp');
gulp.on('start', function(evt) {
  console.log('Starting task:', evt.name);
}).on('stop', function(evt) {
  console.log('Finished task:', evt.name);
}).on('error', function(evt) {
  console.log('Error in task:', evt.name);
});

The OP Martyn adds in the comments:

I  wasn't rebuilding my image correctly.
Rebuilt now correctly:
docker build --no-cache . -t my-stuff/gulp.

OK, usePolling is working really well.
Comment: @Martyn Strange. I have edited the answer with some debugging ideas, but no definitive answer at the moment.
Comment: @Martyn Great, well done! I have included your conclusion in the answer for more visibillity.
Comment: Thanks. That sounds like the solution, but I'm still not able to get it to work. I've updated my original post. Is there anything I'm doing wrong?
Comment: Thanks for taking the time to help me, I really appreciate it. I'll check this out tomorrow. If I still can't get it working, I'll build it up from basic gulpfile.
Comment: Ugh! I stupidly wasn't rebuilding my image correctly. Rebuilt now correctly `docker build --no-cache . -t my-stuff/gulp`. OK, usePolling is working really well. Thanks again for your help.


user variables in a calculation

Question: I am producing a league table for speedway teams, I have got a query to calculate the required data based on teams results.  The part I am struggling with is the points difference (difference between points scored and scored against.
<code>    SELECT tbl_clubs.club, tbl_clubs.club_id,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away AND tbl_fixtures.awayscore is not null ,1,0)) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.home AND tbl_fixtures.homescore is not null,1,0 )) as `M`,
SUM( if( tbl_clubs.club_id = tbl_fixtures.home
AND tbl_fixtures.homescore > tbl_fixtures.awayscore, 1, 0 ) ) AS `W`,
SUM( IF( tbl_clubs.club_id = tbl_fixtures.home AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 1, 0 ) ) AS `HD`,
SUM( if( tbl_clubs.club_id = tbl_fixtures.home
AND tbl_fixtures.homescore < tbl_fixtures.awayscore, 1, 0 ) ) AS `HL`,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore >=7,1,0)) AS `4W`,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore <=6,1,0)) AS `3W`,
SUM( IF( tbl_clubs.club_id = tbl_fixtures.away AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 1, 0 ) ) AS `AD`,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore < tbl_fixtures.homescore
AND tbl_fixtures.homescore - tbl_fixtures.awayscore <=6,1,0)) AS `1L`,

SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore < tbl_fixtures.homescore
AND tbl_fixtures.homescore - tbl_fixtures.awayscore >=7,1,0)) AS `L`,

@FOR:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.homescore,0)) as `F`,

@Against:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.homescore,0)) as `A`,

SUM(@For - @Against) as `PtsDiff`,

SUM( if( tbl_clubs.club_id = tbl_fixtures.home
AND tbl_fixtures.homescore > tbl_fixtures.awayscore, 3, 0 ) ) +
SUM( IF( tbl_clubs.club_id = tbl_fixtures.home AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 1, 0 ) ) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore >=7,4,0)) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore <=6,3,0)) +
SUM( IF( tbl_clubs.club_id = tbl_fixtures.away AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 2, 0 ) ) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore < tbl_fixtures.homescore
AND tbl_fixtures.homescore - tbl_fixtures.awayscore <=6,1,0))  as `Pts`
FROM tbl_clubs
INNER JOIN tbl_fixtures ON tbl_clubs.club_id = tbl_fixtures.home

OR tbl_clubs.club_id = tbl_fixtures.away
where tbl_clubs.league_id = 3
GROUP BY tbl_clubs.club_id
order by Pts desc, PtsDiff desc, club asc
</code>
All of the query is working except for
<code>@FOR:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.homescore,0)) as `F`,

@Against:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.homescore,0)) as `A`,

SUM(@For - @Against) as `PtsDiff`,
</code>
I am getting NULL as a result for this, I am guessing its something simple, any help would be great
Answer: Firstly, you'll want to ensure that null values always default to 0 and not null.  This is something that could happen within your script, so you should ensure that 0 is the only viable default.  This should occur before this query gets executed though ideally.  It doesn't appear that this is the case based on your script, so you may want to ensure you have designed your database to cater for that.
Secondly, variable assignment inside queries is not quite as straight-forward as you'd like it to be unfortunately.  You may be better using a sub-query for your initialisations:
<code>@FOR:=(select IFNULL(SUM(tbl_fixtures.awayscore),0)  from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.away) +
        (select IFNULL(SUM(tbl_fixtures.homescore),0) from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.home)
as `F`,
@Against:=(select IFNULL(SUM(tbl_fixtures.awayscore),0)  from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.home) +
        (select IFNULL(SUM(tbl_fixtures.homescore),0) from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.away)
as `A`,
SUM(@FOR - @Against) as `PtsDiff`,
</code>
Not very elegant, but this should work.  Notice the use of IFNULL to ensure that null is converted to 0.

user variables in a calculation


What does this line mean in slick?

Question: I was looking into the play-slick3 demo and I saw the definition of this table
<code>  private class ProjectsTable(tag: Tag) extends Table[Project](tag, "PROJECT") {

    def id = column[Long]("ID", O.AutoInc, O.PrimaryKey)
    def name = column[String]("NAME")

    def * = (id, name) <> (Project.tupled, Project.unapply)
    def ? = (id.?, name.?).shaped.<>({ r => import r._; _1.map(_ => Project.tupled((_1.get, _2.get))) }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))
  }
</code>
What does the last line mean? I couldn't find anything about it in the documentation or the API
Comment: I have no idea, but I will say that that is possibly the most unpleasant-looking line of Scala I've ever seen.
Comment: what version of slick are you using?
Comment: @SomBhattacharyya 3.1.1
Answer: According to a comment at http://www.developmentalmadness.com/2016/02/23/scala-connecting-to-postgres-via-slick-3/

Maps whole row to an option. Useful for outer joins.

What does this line mean in slick?


Linq Dictionary for count of items that are in an array

Question: How can I Linq a count back from myDict where value (not key) is not in myArray
private Dictionary<string, int> myDict
int[] myArray = { 1, 2, 3 }

Not sure if below if correct I haven't tried to debug it yet but i'm just guessing it might not work as I want it to
int count = myDict.Count(x => !x.Value.Equals(myArray));

Comment: So, you haven't tried running your code and just want to check your guess here?
Comment: Correct because I knew it likely wasn't correct
Answer: var count = myDict.Count(x => !myArray.Contains(x.Value));

Answer: You could also take an intersection of both collections.
var count = myDict.Values.Intersect(myArray).Count();

Answer: The items that are in both of two different collections is the "intersection" of those two sets.  We can compute that using LINQ and then simply count its size:
int count = myArray.Intersect(myDict.Values).Count();

This implementation will also be more efficient than doing repeated linear searches of one of the collections through the use of Contains.
Answer: You need to use Contains on myArray to see if it has the Value in it, not the other way around.
int count = myDict.Count(x => !myArray.Contains(x.Value))

The Equals method you use, checks object equality.  You are asking if x.Value is equal to myArray, not if myArray has x.Value in it.


Tracking Full exit of application in flutter

Question: I have a very different scenario,
I am looking for the solution where if some one try to close the app forcefully I need to clear the sharedprefrences data before closing. So if user comes back to app, they need to relogin again
Any help will be appriciated.
Regards,
Nikhil
Answer: On mobile system you should typically not behave differently depending on whether your application gets killed in the background or not. The user shouldn't be aware of application lifecycles, it's just a matter of the OS doing memory/battery management.
That being said. There are lifecycle hooks natively for iOS (applicationWillTerminate of AppDelegate and Android onDestroy of the Application). But at this time you probably don't expect your app to have enough time to asynchronously communicate with your flutter/dart code and back again, to do the cleanup you are asking for.
So I would suggest to take a good look at your use case. One way would be to use the WidgetsBinding.instance.addObserver to listen for didChangeAppLifecycleState for the state changing to AppLifecycleState.pause and do your cleanup. So when the user switched away from your app and back again (no matter if the app was killed in the meantime) you can show a new login prompt.
There is an example in the flutter documentation on how to add a observer.
class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO check the new state.
  }