Does the 7th major scale note resolve more strongly to the lower tonic (note 1) than the higher tonic (note 8)?

Question: Does the 7 resolve more strongly to the 'lower' tonic (1) than the 'higher' tonic?
I used the word resolve as the octave notes are different despite being the same name.
My ear says going from B to lower C has more 'finality' (which I am calling resolve) than from B to higher C which sounds to me more like the first two notes of a scale.
Comment: Are you asking about whether C4 sounds stronger going to C3 or C5, or are you asking if **B4** sounds stronger going to C4 or C5? I thought you were asking the latter, since B is the seventh scale degree of the C major scale that would normally resolve to a C of some sort. C4 to C3 (or C5) is not what I would call a "resolution".
Comment: I still don't understand. A C does not "resolve" to another C because there is no tension between two Cs. There is tension between a B and a C. Also in the title you ask about the 7th scale degree. That makes sense. In the key of C the sevent scale degree is B. So talking about the seventh or B resolving makes sense. Talking about the eighth scale degree or the first scale degree (C) resolving doesn't make sense.
Comment: No. It resolves most strongly to the one it's adjacent to.
Comment: The question is phrased in a confusing way. especially in that the last paragraph doesn't seem to be about the same as the rest of it.
Comment: I am asking why it goes up instead of down. It it solely for the sake of composition? I offer the example of C4 ... does it resolve the same higher or lower? If not then the B also resolves (best) to the lower C, in of itself.
Comment: Ok, does one sound 'better' ... why would C4 to C3 sound the same as C4 to C5?

I tried to edit the question. The C 'resolving' is an example to show that up/down does matter, just not what is the adjacent note.
Comment: I'll leave this there: There are reasons why the Baba Yaga movement of Mussorgsky's *Pictures at an Exhibition* is one of the most commonly remixed-into-rock-and/or-heavy-metal classical music pieces (at least by YouTube video count of unique rearrangements), and one of them is because it starts with ugly descending major 7th leaps.
Comment: Try singing B>C going up a semitone, then try the same going down to the C below, from that same B. It may well answer the question.
Comment: Tim, I did what you asked and there's no question to me that the B going to the lower C has a much stronger resolution than going up to C. When it goes to the higher C is feels like a mode, like the first two notes of a melody. But when it goes lower the size of the jump makes it feel like it's not just a melody but it has finality.

Did you ever hear a symphony end on a single note that's on the high side of the composition? I don't recall any. Don't they usually build up and then end on a note that's low?
Comment: Possible duplicate of [Is one octave above tonic also considered as tonic?](https://music.stackexchange.com/questions/84380/is-one-octave-above-tonic-also-considered-as-tonic)
Comment: Seems clear enough to me now. I mean, the question's weird, but I think it's easy enough to understand after this edit. VTR?
Comment: @user45266 The point of the question is that resolving down is usually more important than resolving to a close-by note.
Comment: It's hard to hear "resolution" in a melody with just 2 notes. Try singing the first line of "All Glory, Laud, and Honor" (https://hymnary.org/media/fetch/96089) with the last note an octave lower!
Answer: When talking about resolutions, most if not all times the smaller the distance is the better resolution. In this case hands down the leading tone wants to resolve step wise up, not down a major 7th. That resolution would be jarring to most.
To take a step back, there is no difference from a harmony perspective from any octave equivalence in terms of generic harmony so 1, 8, 15, ect are all treated as the root note your scale/key so the idea 8 would be weaker than 1 is not correct in general terms and in this case 7 will really want to go to 8.
Comment: @RandyZeitman It's not conclusive without flow and context. One of the most famous melodies of all time does the opposite (some where over the rainbow). I'm not saying you can't perceive it as better, but there's not a general consensus on this and it's opinionated.
Comment: Either. Without knowing more about the scenario, there's not enough to say one way or another. Jumping an octave if not handled with care can be quite jarring up or down so I'd be more concerned about that.
Comment: You seem to be saying what I said - the reason is compositional. But in an isolated situation would you prefer C4 to resolve to C3 or C5?
Comment: Play it on piano and see for yourself. I think it's clear that a note resolves better to its lower octave than higher.
Answer:
The question is, does the 7 actually, technically, resolve more strongly to the 'lower' tonic (1) than the 'higher' tonic but compositionally it sounds better to resolve to the upper tonic?

I don't understand your distinction between what's "technically" right and what's "compositionally" right. In music, composition comes first, and theory is used to describe the composition.
So the reason we say that the 7th scale degree resolves up to the 1st is because that's how composers have traditionally resolved the 7th scale degree.

For example, ignoring the 7, if C4 (middle C) resolves more strongly to C4 than C5 then it would stand to reason that B actually resolves better to the lower tonic but it's always listed as going to the higher tonic because it's more compositionally useful.

This is not a good example because there is no tension between octaves. The concept of resolution in Western music theory is based on the idea of tension between the various notes. If you feel that C4 to C3 is stronger than C4 to C5, then you can certainly use that preference to influence your personal compositional style, but it is not something that has yet been incorporated into standard music theory.
Comment: @RandyZeitman the frequency ratio between octaves is 2:1, so there is no interference between the two notes; and the ratio between C4 and C3 is the same as the ratio between C4 and C5, so there is no way to rank ascending versus descending octaves.
Comment: "technically" right means the note in isolation. Why do you say there's no tension between octaves?  Why would there not be tension between any two waves that aren't the same.
Comment: Well yes, there is no phase interference. There is amplitude interference. Higher notes are louder as they have more power. Treble 'breaks through'. Guitar players often only need little amps on stage, 5-10 watts, while bass players need more.
Answer: It's kind of analogous to ionic bonding in chemistry. Take Sodium (Na) and Chlorine (Cl), for example.
Generally, students acquire the misconception that when Na and Cl react to form NaCl (commmon table salt), Cl simply removes an electron from Na, forming Na+ and Cl-.
But that's not strictly true.
Electrons actually exist in probabilistic regions, meaning there's a certain chance that an electron is in any position, rather than a defined, singular location. Because of the Octet rule (and/or other reasons), the chlorine atom - having 7 valence electrons - much more often takes on an 8th electron rather than losing all seven to go back to 0 valence electrons (which would then mean that it actually had 8 again, but you get the idea). Applying this to NaCl, the individual chlorine molecule attracts the electron so much more strongly than Na that the electron is extremely likely to be "part of" the chlorine atom at any moment. This inequality is so pronounced that we observe the Cl ion to have a negative charge. This post has some more in-depth information, as does the rest of its host question.

To bring this rant back to Music Theory, no, there are no hard-and-dry rules on how the 7th degree, or any scale degree, resolves. But we observe that nearly every time, the 7th scale degree resolves to the octave rather than all the way back down to the lower octave. A bunch of explanations exist for this, and as others have noted, smaller movements tend to be observed as "smoother" resolutions, but my point is that the 7th degree is commonly said to resolve up to the octave because that's how it happens nearly every time. If you feel it works better down to the octave, by all means give it a try, but recognise that you may be mistaking the resolution's effect with that of the effect of having the lower bass note, and that you may achieve effects that you did not intend or did not desire.
Comment: I'm taking this answer with a pinch of salt..! Except that the question itself is based on a questionable premise. And, at the end of the day, it's all in the ear of the beholder anyway. you're right than mostly the leading note resolves upwards. maybe that's why it's called the leading note? 'Salltoo much for me. +1.
Comment: @user  You seem to get it. What I'm trying to say (over and over) is that I think the notes, in of themselves, resolves far better lower ... but that doesn't serve how melodies work.  Above Peter says there's no interference between C4 and C5 as they're octaves. That's true frequency wise but not amplitude wise. Unless the two notes are the same ƒ there's a difference, perhaps not "interference" if that only means phase-interference.


Tiling a $23 \times 23$ square by $1 \times 1$, $2 \times 2$, and $3 \times 3$ tiles

Question: A $23 \times 23$ square is tiled by $1 \times 1$, $2 \times 2$, and $3 \times 3$ tiles. Prove that at least one 1 x 1 tile must be used. Find such a tiling with exactly one $1 \times 1$ tile.
Hint: put a number in each $1 \times 1$ square of the big square so that $2 \times 2$ and $3 \times 3$ tiles cover a total divisible by $3$.
I'm not sure how to utilize the hint in solving this problem.
Answer: Further hint:
$$ \matrix{1 & 0 & 1 & 0 & \ldots\\
           0 & 2 & 0 & 2 & \ldots\\
           1 & 0 & 1 & 0 & \ldots\\
           0 & 2 & 0 & 2 & \ldots\\
          \ldots &  \ldots & \ldots & \ldots & \ldots &\cr}$$
What is the total in the $23 \times 23$ square?
Comment: I want to say 386 but I'm not sure how that helps
Comment: Is it divisible by $3$?
Comment: Nope. What can I conclude from that?
Comment: Could it be a sum of numbers each divisible by $3$?  Note that the sum of the numbers in a $2 \times 2$ or $3 \times 3$ tile is divisible by $3$.
Comment: I believe the sum of numbers should be divisible by 3, yes?
Comment: Yes, if you could do the tiling with only $2 \times 2$ and $3 \times 3$ tiles, the sum would have to be divisible by $3$.
Comment: Is there a tiling with exactly one 1 x 1 tile used?
Answer: Put all ones in the top row, twos in the second row, ones in the third row and so on, every other row ones and twos.
You can check that wherever you put a big square, it has to cover a total that is divisible by 3. You can also check that the total in the entire grid is not divisible by 3. Hence you need small squares.
Comment: So without a 1 x 1 square, I cannot achieve an entire grid of squares with total sum divisible by 3?
Comment: @Jebediah Since neither of these answers has _quite_ made it explicit: for either of these numberings, any 2x2 or 3x3 tile covers a set of numbers that adds to a multiple of 3.  So if you could tile with _only_ 2x2 and 3x3 tiles, then your total sum of numbers over the grid would have to be a multiple of 3.  But the total sum of all numbers on the grid is one more than a multiple of 3, so...


Carregar dados de um campo após pressionar um botão

Question: Preciso carregar dados de um campo de uma tabela.
Exemplo: Tabela (Modelo), a pessoa está preenchendo o formulário e quer utilizar no campo Texto esse modelo, e com isso ela clicaria em um botão (Carregar Modelo) e carregaria esse modelo no input Texto.
Comment: Acho que facilitaria responder se você editasse a pergunta para incluir os trechos de código relevantes do que você já tem pronto.
Comment: Sua pergunta está muito ampla ainda, você já fez alguma tentativa de fazer isso?Já tem a estrutura da tabela feita? Já tem algum modelo de como isso funcionaria? Precisamos de mais detalhes para poder te dar uma resposta que seja boa. Para melhorar sua pergunta você pode [edita](http://pt.stackoverflow.com/posts/19252/edit)-la
Comment: Sim, já tenho.O formulário funciona perfeitamente, apenas não consigo pensar em como carregar o modelo dentro do input quando o usuário clicar (Carregar Modelo), que esse modelo é um texto pronto apenas.
Answer: Você poderá resolver isto com ajax, se você já fez os tão famosos campos select "Estado X Município", segue o mesmo raciocínio.
Ao clicar no botão acionará um evento que terá um ajax que apontará para um arquivo php, onde você pegará o parâmetro e com ele montará a consulta específica e retorna o dado do banco.

// cadastrarPaciente.js
$("#uf").on("change", function(){
    $.get("modulos/pacientes/ajax_listarCidade.php",
        {uf: $("#uf").val()},
            function(dados){
            $("#cod_cidade").empty();
            $("#cod_cidade").append(dados);
    });
});

// ajax_listarCidade.php
$PArray['uf'] = $_REQUEST['uf'];

$sql = "SELECT cod_mun, nome_mun FROM TMunicipio WHERE uf = '{$PArray['uf']}'";
...

É só seguir este raciocínio.


A continuous weighted ergodic average

Question: Let $(X_t)_{t\ge 0}$ be a continuous stationary ergodic process (w.r.t. the shift operator), and $f$ be a bounded Borel function. Prove or disprove:
$$
\lim_{n\to\infty} \frac{1}{\ln n}\sum_{k=1}^n (\ln(k+1)-\ln k)f(X_{\ln k}) = \mathbb{E}[f(X_0)] \qquad \text{a.s.}
$$
There are several results on the pointwise convergence of weighted ergodic average in the discrete case, while I did not find the counterpart in the continuous case.
Answer: I can prove that this result is true under an additional assumption, which is closely related to strong mixing and seems to hold in the cases I am interested in (see below for more details).
Assumption: for any bounded Borel function $f$, there exists constants $c_0>0, t_0>0$ and exponent $\beta>0$ (which may depend on $f$) such that $|\text{cov}(f(X_0),f(X_t))|\le c_0t^{-\beta}$ for any $t>t_0$. In other words, the correlation enjoys a polynomial decay with an arbitrarily slow speed.
Proof based on this assumption:
Since $\ln(k+1)-\ln k=k^{-1}+O(k^{-2})$, it is equivalent to prove that
$$
\lim_{n\to\infty} \frac{1}{\sum_{k=1}^n k^{-1}}\sum_{k=1}^n \frac{f(X_{\ln k})}{k} = \mathbb{E}[f(X_0)] \qquad \text{a.s.}
$$
W.l.o.g. we assume that $f\ge 0$. Denote the normalized partial sum on the LHS by $S_n$, we have
\begin{align}
\text{var}(S_n) &\le \frac{c_1}{(\ln n)^2}\sum_{i,j=1}^n \frac{|\text{cov}(f(X_{\ln i}), f(X_{\ln j}))|}{ij}\\
&= \frac{c_1}{(\ln n)^2}\left(\sum_{|\ln i-\ln j|\le t_0} \frac{|\text{cov}(f(X_{\ln i}), f(X_{\ln j}))|}{ij} + \sum_{|\ln i-\ln j|> t_0} \frac{|\text{cov}(f(X_{\ln i}), f(X_{\ln j}))|}{ij}\right)\\
&\le \frac{c_1}{(\ln n)^2}\left(\sum_{|\ln i-\ln j|\le t_0} \frac{\|f\|_\infty^2}{ij} + \sum_{|\ln i-\ln j|> t_0} \frac{c_0}{ij|\ln i-\ln j|^\beta}\right)\\
&\le \frac{c_2}{(\ln n)^2}\sum_{i=1}^n \frac{1}{i}\left(\sum_{j=ie^{-t_0}}^{ie^{t_0}} \frac{\|f\|_\infty^2}{j} + \sum_{|\ln i-\ln j|> t_0} \frac{c_0}{j|\ln i-\ln j|^\beta}\right)\\
&\le \frac{c_3}{(\ln n)^2}\sum_{i=1}^n \frac{1}{i}\left(1 + \int_1^{ie^{-t_0}} \frac{dx}{x(\ln i-\ln x)^\beta}+\int_{ie^{t_0}}^n \frac{dx}{x(\ln x-\ln i)^\beta}\right)\\
&\le \frac{c_4}{(\ln n)^2}\sum_{i=1}^n \frac{(\ln n)^{1-\beta}}{i} \le \frac{c_5}{(\ln n)^\beta}.
\end{align}
Now we fix some $\alpha>1$ and consider the sequence $k_m=[e^{\alpha^m}]$. Along the subsequence $S_{k_m}$, for any $\epsilon>0$, we have
\begin{align}
\sum_{m=1}^\infty P(|S_{k_m}-\mathbb{E}[f(X_0)]|>\epsilon) \le \frac{1}{\epsilon^2} \sum_{m=1}^\infty \text{var}(S_{k_m}) \le \frac{1}{\epsilon^2} \sum_{m=1}^\infty \frac{c_6}{\alpha^{\beta m}} < \infty
\end{align}
then by Borel--Cantelli $S_{k_m}\to \mathbb{E}[f(X_0)]$ a.s.. For the original sequence $S_n$ with $k_m\le n<k_{m+1}$, by $f\ge 0$ we have $\frac{\ln k_m}{\ln k_{m+1}}S_{k_m}\le \frac{\ln k_m}{\ln n}S_{k_m} \le  S_n\le \frac{\ln k_{m+1}}{\ln n}S_{k_{m+1}}\le \frac{\ln k_{m+1}}{\ln k_m}S_{k_{m+1}}$, and thus
\begin{align}
\alpha^{-1}\cdot \mathbb{E}[f(X_0)]\le \liminf_{n\to\infty} S_n \le \limsup_{n\to\infty} S_n \le \alpha\cdot \mathbb{E}[f(X_0)] \qquad \text{a.s.}
\end{align}
Finally choosing $\alpha\to 1^+$ completes the proof.
Background: the original problem is as follows: for i.i.d. stable r.v.s $X_1,X_2,\cdots$ with parameter $\alpha\in(0,2]$, the partial sum $S_n=\sum_{k=1}^n X_k$ satisfies
$$
\lim_{n\to\infty} \frac{1}{\ln n}\sum_{k=1}^n \frac{1}{k}f(k^{-\frac{1}{\alpha}}S_k) = \mathbb{E}[f(X_1)]\qquad \text{a.s.}
$$
for any bounded Borel function $f$.
Together with CLT, this is a generalization of P. Levy's result: for i.i.d. $X_n$ with continuous symmetric distribution,
$$
\lim_{n\to\infty} \frac{1}{\ln n}\sum_{k=1}^n \frac{1}{k}\cdot 1_{S_k>0} = \frac{1}{2}\qquad \text{a.s.}
$$
Also, this is closely related to the almost sure central limit theorem: for i.i.d. $X_n$ with $\mathbb{E}(X_1)=0, \mathbb{E}(X_1^2)=1$, then
$$
\lim_{n\to\infty} \frac{1}{\ln n}\sum_{k=1}^n \frac{1}{k}\cdot 1_{\frac{S_k}{\sqrt{k}}<x} = \Phi(x)\qquad \text{a.s.}
$$
where $\Phi(\cdot)$ is the CDF of the standard normal distribution.
One way to prove the original problem is to construct a continuous-time Levy process $(S_t)_{t\ge 0}$ with $S_1\overset{d}{=} X_1$, and then consider its Lamperti transform $(Z_t)=(e^{-t/\alpha}S_{e^t})$. It is straightforward to show that $(Z_t)$ is stationary. Ergodicity follows from the Blumenthal's zero–one law for cadlag stochastic processes with independent increments. Now we arrive at the problem stated here.
In fact, more is true for this special example: $(Z_t)$ is strongly mixing since we can verify from $(S_t)$ that $\ln\mathbb{E}[\exp(i(\theta_1 Z_0+\theta_2 Z_t))]- \ln\mathbb{E}[\exp(i\theta_1 Z_0)]-\ln\mathbb{E}[\exp(i\theta_2 Z_t)]\to 0$ as $t\to\infty$ (For this point, see Remark 3.7.3 in P. Embrechts and M. Maejima: Self-similar Processes. Princeton University Press, Princeton, NJ, 2002). Moreover, for Brownian motion ($\alpha=2$), by Renyi maximal correlation for joint Gaussian variables we know that
$$|\text{cov}(f(Z_0),f(Z_t))|\le \text{var}(f)\cdot |\text{corr}(Z_0,Z_t)|= \text{var}(f)\cdot e^{-t/2}$$ decays exponentially, which is much stronger than what we have assumed!
Remaining question:

Is there any way to prove this result using the results/proofs in ergodic theory (e.g., some maximal inequality)? In fact, from pointwise ergodic theorem we know that
$$
\frac{1}{\ln t}\int_0^t \frac{1}{u}f(X_{\ln u})du \to \mathbb{E}[f(X_0)] \qquad \text{a.s.}
$$
as $t\to\infty$, which is very close to the question here. Moreover, this problem looks very similar to the weighted ergodic average problem $\sum_{k=0}^{n-1}a_{n,k}f\circ T^k(X)$ and the subsequence problem $\frac{1}{n}\sum_{k=0}^{n-1}f\circ T^{m_k}(X)$.
For general stable processes other than Brownian motion, I highly believe that our additional assumption still holds, but I did not find proper references on maximal correlation/strongly mixing coefficient. Can anyone help me with that?

A continuous weighted ergodic average


ecomdev phpunit fixture for website specific configuration

Question: I'm trying to understand PHPUNIT + MAGENTO and I found this extension https://github.com/EcomDev/EcomDev_PHPUnit which seems to be great tool.
I want have a fixture which set shipping method 'Freeshipping' per website. I found a solution for default configuration
config:
    default/carriers/freeshipping/active: 1
    default/carriers/freeshipping/free_shipping_subtotal: 150
    default/carriers/freeshipping/name: Free
    ...

It works fine. But let's have a website ID = 2 then what do I need to add into fixture's yaml?
Answer: I think you would use:
config:
  websites/{website_code}/carriers/freeshipping/active: 1

However, the config fixtures seem to have unwanted side effects like removing other config nodes.. So as inelegant as it is, I use:
public function setUp() {
    Mage::app()->getStore(0)
        ->setConfig('carriers/freeshipping/active', 1);
    // OR
    Mage::getConfig()->setNode('websites/{$code}/carriers/freeshipping/active' 1);
}

Comment: Thankyou! I've been having huge issues with config nodes going missing (Warning: SimpleXMLElement::asXML(): Node no longer exists) when using fixtures for config.

I couldn't find any reference to anyone else having similar issues so was wracking my brain trying to find out what I'd done wrong.

I might create a convenience method for setting up all the config I want in tests to make it a bit more elegant.


How to get data from selected row, Datatables

Question: ok, finally i made though to get id show in datatables but not visible on grid.
i want to get the id, throught jquery selector or any other good way if possible.
Here is the Output HTML

Form Name	Form Path	Form CI Path	Actions

Dashboard	#	admin/dashboard/System

Dashboard	#	admin/dashboard/Users

Just need to get the data-id from the tr.
i tried this.closest('tr') but got error.
any suggestions..
Here is the script.

Answer: I hope this will work for you:
$(this).closest('tr').attr('data-id');

Comment: Thanks for reply, but it is also not working, in console it shows `undefined`
Comment: i also tried this with your code
`$(this).closest('tr').attr('data-item');`
Comment: hmmm. i tried `$(this).closest('tr').attr('data-id');` and it worked.
thanks for suggestion. just change the id to `data-id`.
Answer: You can try it once with jquery $('.use your tr class name here').attr('data-id')


How to execute a promise in nodejs with express

Question: so I'm new to Node and I've been trying to do some work with promises. My problem is that I can't seem to get my endpoint to execute it's code 'asynchronously'. The idea is that my endpoint executes the 'list' function, which should log out words to the the console and return 'true' to the response. All my promise does is wait five seconds and print out 'Promise'. I'm expecting the console to print 'Before' 'After' 'Promise' (in that order), but I'm getting 'Before' 'Promise' 'After', which would appear to me to be synchronous execution. Shouldn't the list function move onto the last line of the code ('After') and not wait for the promise to resolve/reject?
var log4js = require('log4js');
var logger = log4js.getLogger('controller');
var Promise = require('promise');

function pause(milliseconds) {
    var dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

var listPromise = function(){
    return new Promise(function (resolve, reject){
        var flag = true;

        try{
            pause(5000);
            console.log('Promise');
        }catch(err){
            logger.error('Error');
        }

        if(flag){
            resolve(flag);
        }else{
            reject(Error("Could not execute"));
        }
    });
}

 exports.list = function(req, res) {

     console.log('Before');

     listPromise().then(function(fulfilled) {
         res.json(fulfilled);
     })
     .catch(function (error) {
         res.send(error.message);
     });

     console.log('After');
 };

Comment: Promises aren't "executed", and you cannot use them to execute blocking code in parallel. They're values representing the future results of some asynchronous operation, nothing more. Your `pause` function is not asynchronous, and that's bad - use `setTimeout` instead.
Comment: Yes. I've put my comment with an example in an answer.
Comment: Okay I think I'm starting to understand. The code in the promise should be async. So for example if I used setTimeout() with a callback function?
Answer: Promises aren't "executed", and you cannot use them to execute blocking code in parallel. They're values representing the future results of some asynchronous operation, nothing more. Your pause function is not asynchronous, and that's bad - use setTimeout instead. The callbacks will actually be asynchronous then:
function pause(milliseconds) {
    return new Promise(function (resolve, reject) {
        setTimeout(resolve, milliseconds);
        console.log('Promise executor');
    });
}

exports.list = function(req, res) {
     console.log('Before');
     pause(5000).then(function(fulfilled) {
         console.log("Promise callback");
         res.json(fulfilled);
     })
     .catch(function (error) {
         res.send(error.message);
     });
     console.log('After');
};

This will log Before, Promise executor, After, and then after five seconds, Promise callback.
Answer: Your listPromise function is not really async function, it returns the promise only.
Use setTimeout function to emulate async operation:

let listPromise = () => {
    return new Promise(resolve => {
        setTimeout(_ => {
           console.log('Promise');
           resolve(true);
        }, 1000);
    });
}

let list = () => {
     console.log('Before');

     listPromise()
         .then(fulfilled => console.log(fulfilled))
         .catch(err => console.log(err));

     console.log('After');
 };

 list();


Can you show that the regular 15 sided polygon is constructible

Question: It is known from basic geometry that the regular 15 sided polygon is constructible.  It can be shown that Cos2π/15 radian is a root of the equation:
x7 +1/2 X6  - 3/2 X5  - 5/8 X4  + 5/8 X3 + 3/16 X2   - X/16  - 1/128     =  0
where X= Cos 24°. Can you demonstrate this?
This equation is algebraically solvable in terms of square roots, because this polygon is constructible.
Can you show that one form of the solution is the following:
x= Cos 24°= (-1+√w)/4 , Where w = 11+2√y , and y = 3(5+2√5).
Comment: You want two facts. They both require more typing effort than thinking effort, and are a pain for the typist. The answer "Yes, i can" is a valid answer, if the question is stated as above. There are computer algebra systems that explain the minimal polynomial and the form of the solution without pain. So which is the question again? Please show also the own efforts to attack the issue and provide more context to the question. It is the way it works. Also, using mathjax would be nice and recommended, the typist will have to use it. Can you modify the OP accordingly?!
Comment: mathjax link https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: OK, i will type that solution. Let us define first:
$$
\begin{aligned}
\xi &= \cos 24^\circ + i\sin 24^\circ=\exp\frac{2\pi i}{15}\ ,\\
c &=2\cos\frac{2\pi i}{15}=\xi+\frac 1\xi\ ,\\
x&=\frac c2=\cos 24^\circ=\cos \frac{2\pi}{15}\ ,\\
y &= 3(5+2\sqrt 5)>0\ ,\\
w &= 11+2\sqrt y\ .\\[3mm]
&\qquad\text{Then we have:}\\[3mm]
\xi&\text{ is a root of the cyclotomic polynomial $\Phi_{15}$,}\\
\Phi_{15}(X)
&=\frac{X^{15}-1}{\Phi_5(X)\Phi_3(X)\Phi_1(X)}\\
&=\frac{X^{15}-1}{\frac{X^5-1}{X-1}\cdot\Phi_3(X)\cdot(X-1)}\\
&=\frac{X^{10}+X^5+1}{X^2+X+1}\\
&=X^8 - X^7 + X^5 - X^4 + X^3 - X + 1\ .\\[3mm]
&\qquad\text{It is real and reciprocal. So we have:}\\[3mm]
0&=\Phi_{15}(\xi)=\Phi_{15}(\bar\xi)=\Phi_{15}\left(\frac 1\xi\right)\ .
\\[3mm]
&\qquad\text{We will show $c^4-c^3-4c^2+4c+1=0$:}\\[3mm]
\xi^4&(c^4-c^3-4c^2+4c+1)\\
&=(\xi^2+1)^4-\xi(\xi^2+1)^3-4\xi^2(\xi^2+1)^2
+4\xi^3(\xi^2+1)+\xi^4\\
&=(\xi^8+4\xi^6+6\xi^4+4\xi^2+1)
\\
&\qquad-(\xi^7+3\xi^5+3\xi^3+1)
\\
&\qquad\qquad-4(\xi^6+2\xi^4+\xi^2)
\\
&\qquad\qquad\qquad+4(\xi^5+\xi^3)
\\
&\qquad\qquad\qquad\qquad+\xi^4
\\
&=\Phi_{15}(\xi)
\\
&=0\ .
\end{aligned}
$$

The above (minimal) equation for $c=2\cos(2\pi/15)$ implies an obvious equation for $x=c/2= \cos(2\pi/15)$, which is:
$$
x^4 - \frac 12x^3 - x^2 + \frac 12x + \frac 1{16}=0\ .
$$
The polynomial in the OP has the polynomial above as a factor, in fact explicitly:
$$
\left(
x^{7} + \frac{1}{2} \, x^{6} - \frac{3}{2} \, x^{5} - \frac{5}{8} \, x^{4} + \frac{5}{8} \, x^{3} + \frac{3}{16} \, x^{2} - \frac{1}{16} \, x - \frac{1}{128}
\right)
\\
=
\left(x^4 - \frac 12 x^3 - x^2 + \frac 12 x + \frac1{16}\right)
\left(x^2 + \frac 12 x -  \frac 14\right)
\left(x + \frac 12\right)
\ .
$$
This clears the first question in the OP.

The second question, regarding the expression using radicals for $x$. Let us show:
$$
\begin{aligned}
(*)\qquad
x
&=\frac 18\Big(\
1+\sqrt 5+\sqrt{6(5-\sqrt 5)}
\ \Big)
\\
&=
-\frac 14+
\frac 14\sqrt{11+2\sqrt{3(5+2\sqrt 5)}}
=\frac 14(-1+\sqrt w)
\ .
\end{aligned}
$$

For the first equality, marked $(*)$ above,  we easily identify the Galois conjugates, which are
$$
x_{s,t}=
\frac 18\Big(\
1+s\sqrt 5+t\sqrt{6(5-s\sqrt 5)}
\ \Big)\ ,\ s,t\in\pm 1\ .
$$
(It is a good structural way to write so the solution(s).)
Then we compute
$$
\begin{aligned}
&64(X-x_{s,+})
(X-x_{s,-})
\\
&\qquad =
(8X-8x_{s,+})
(8X-8x_{s,-})
\\
&\qquad =
(8X-s\sqrt 5-1)^2 - 6(5-s\sqrt 5)
\\
&\qquad =
\Big((8X)^2+5+1-16X-30\Big)
-2s\sqrt 5\Big((8X-1)-3\Big)
\\
&\qquad =
64\left[\ \left(X^2-\frac 14X-\frac 38\right)
\ -\
\frac 18s\sqrt 5(2X-1)
\
\right]\ .
\\[3mm]
&(X-x_{+,+})
(X-x_{+,-})
(X-x_{-,+})
(X-x_{-,-})
\\
&\qquad=
\prod_{s\in\pm1 }
(X-x_{s,+})
(X-x_{s,-})
\\
&\qquad =
\left(X^2-\frac 14X-\frac 38\right)^2
-\frac 5{64}(2X-1)^2
\\
&\qquad =
X^{4} - \frac{1}{2} \, X^{3} - X^{2} + \frac{1}{2} \, X + \frac{1}{16}
\ .
\end{aligned}
$$
The above computation shows that all values of $x_{s,t}$ are the solutions of the above equation of degree four. It remains to numerically identify them with $\cos(2k\pi/15)$ for $k$ among the values in $1,2,\dots14$ relatively prime to $15$, and taken modulo $\pm$, so $1,2,4,7$. It turns out that we have $x=\cos(2\pi/15)=x_{++}$.
Note that this first formulas for the four roots involve only a "second recursivity level" of taking radicals.

Let us show also the second expression using radicals for $x=\cos(2\pi/15)$. For this, we want to show
$$
\frac 18\Big(\
3+\sqrt 5+\sqrt{6(5-\sqrt 5)}
\ \Big)
\
\overset{(!)}{=\!=}
\
\frac 14\sqrt{11+2\sqrt{3(5+2\sqrt 5)}}
\ .
$$
It is a claimed equality between positve reals. Equivalently after squaring:
$$
\Big(\
3+\sqrt 5+\sqrt{6(5-\sqrt 5)}
\ \Big)^2
\
\overset{(!)}{=\!=}
\
4\left(\ 11+2\sqrt{3(5+2\sqrt 5)}\ \right)
\ .
$$
The LHS may be computed as
$$
9+5+(30-6\sqrt 5)+6\sqrt 5+6\sqrt{6(5-\sqrt 5)}
+2\sqrt 5\cdot \sqrt{6(5-\sqrt 5)}\ .
$$
We have a cancellation of $6\sqrt 5$. Then the integers $9+5+30$ sum up to $44$, which is also a term on the RHS. Note that the big radical remained on the LHS can be factored, and $6+2\sqrt 5=(\sqrt 5+1)^2$. It remains to show, after a new squaring:
$$
(\sqrt 5+1)^4\cdot 6\cdot\sqrt5(\sqrt 5-1)
\
\overset{(!)}{=\!=}
\
8^2\cdot 3(5+2\sqrt 5)\ .
$$
On the LHS we can group $(\sqrt 5+1)(\sqrt 5-1)=5-1=4$. We simplify then $6\cdot 4=8\cdot 3$. We compute $(\sqrt 5+1)^3
=(8\sqrt 5+16)=8(\sqrt 5+2)$, and are done.
This completes all the points.
Comment: Wow. This is good. Given the wording in the question, with the lack of the expected factor 2 on the cosine, and the polynomial provided being reducible, I don't expect you are going to get anything from this OP other than demands to explain every little detail here. Which is why all I did was look up some items in an 1875 book. For comparison, see the 5 comments after this answer I did today: https://math.stackexchange.com/questions/3665626/group-isomorphism-question/3665641#3665641
Answer: more to the point, the primitive 15th roots of unity satisfy
$$       \omega^8 - \omega^7 + \omega^5 - \omega^4 + \omega^3 - \omega + 1 = 0         $$
while $x =2 \cos \frac{2 \pi}{15},$ which can be written as one of the $x =\omega + \frac{1}{\omega},$ satisfies
$$  x^4 - x^3 - 4 x^2 + 4 x + 1 = 0 $$
Comment: Why don't we wait till the poster shows some effort?! I have been  also constrained to submit...


Universal Casimir element

Question: On page 118 of J.E. Humphreys' book Introduction to Lie algebras and representation theory, paragraph 3 of section 22.1, what is the motivation of the definition of $c_{ad}$ in this way? Why we use the basis $x_{\alpha}, z_{\alpha}, t_{\alpha}$ but not  $x_{\alpha}, y_{\alpha}, h_{\alpha}$?
The last line of paragraph 3 of section 22.1, how to show that $\phi(c_L)$ acts as a scalar using the fact that $\phi(c_L)$ commutes with $\phi(L)$ and $\phi$ is irriducible? Thank you very much.
Comment: Second question: Schur's lemma.
Comment: @user9791: $\phi(c_L)$ is an endomorphism of $V$ as a vector space, but it is not guaranteed to be an endomorphism of $V$ as a representation unless it commutes with $\phi(g)$ for each $g \in L$, and that is the hypothesis of Schur's lemma.
Comment: My copy is in my office, but IIRC the answer to your first question has something to do with normalization. Was that base normalized with respect to the Killing form or something? Using that basis made it somehow a bit more universal, but the other would work as well (scalar multiplier difference). Qiaochu nailed your second question.
Comment: also see http://math.stackexchange.com/questions/44152/casimir-element-invariance
Comment: @Qiaochu, thank you. Here $\phi: L \to gl(V)$ where $V$ is irriducible. Since $\phi(c_L): V\to V$ is irriducible, $\phi(c_L)$ acts as by scalar or acts as $0$. Why $\phi(c_L)$ do not act as $0$. Where do we use the condition that $\phi(c_L)$ commutes with $\phi(g)$ for each $g \in L$?
Comment: @user9791: $0$ is a scalar. The condition is one of the hypotheses of Schur's lemma.
Comment: @Qiaochu, but Schur Lemma only needs $V$ is irriducible. Here $\phi$ is a representation by hypothesis. So $\phi(c_L)$ is already a homomorphism.
Answer: It doesn't matter what basis is used to define Casimir, as long as the Killing form is used properly: In any simple Lie algebra, by Cartan's criterion the Killing form $\langle,\rangle$ is non-degenerate. Given any basis $x_i$ for the Lie algebra, let $x_i'$ be the dual basis with respect to $\langle,\rangle$. Then the Casimir element is $\sum_i x_i x_i'$ in the universal enveloping algebra.
Many sources give an exercise to prove that this expression is independent of basis and that it is central in the enveloping algebra, but there is a direct argument (probably found in Serre, for example): the natural maps with simple Lie algebra $g$,
$$End(g) \approx g \otimes g^* \approx g\otimes g \subset \bigotimes{}^\bullet g \rightarrow Ug$$
are G-equivariant, where the identification of $g^*$ with $g$ is exactly via the Killing form. The identity map among endomorphisms of $g$ commutes with $G$, so its image at the other end does, as well. Consideration of the second and third items yields expressions as in the first paragraph. Poincare-Birkhoff-Witt proves that the resulting expressions are non-zero.
Comment: Yes, semi-simplicity is equivalent to non-degeneracy of the Killing form. And by $G$ I meant the Lie group... but/and the same invariance applies to the small-a adjoint action of $\mathfrak g$ if one doesn't have $G$.
Comment: thank you very much. Does $\bigotimes {}^{\cdot}g$ mean the tensor algebra of $g$?
Comment: Yes, that tensor-with-superscript-bullet it meant to be "tensor algebra" of g. Perhaps better put, it is the "universal associative algebra" attached to the vector space g. The fact that it can be _constructed_ in terms of tensors isn't its defining characteristic, categorically.
Comment: Is this still true for semisimple Lie algebras, which are not necessarily simple? I guess it is, because the Killing form remains non-degenerate. And what do you mean by G, if g is the Lie algebra?

Universal Casimir element


Problemas com JWT token

Question: Estou utilizando um sistema que, utiliza a passagem de JWT tokens para autenticação, o problema é que eu posso facilmente coletar os headers das chamadas de API e pegar meu token para poder requisitar o que quiser e pegar os dados de qualquer usuário.
Acredito que os programadores estão somente bloqueando a rota com base neste codigo:
Route::group(['middleware' => 'jwt.auth'], function()

Gostaria de saber algo para suprir esse problema(uma segunda autenticação ou método de bloqueio para que usuários que tenham token não possam coletar informações de outros usuários e informar os programadores, pois tenho receio de ter meus dados coletados por algum outro usuário com segundas intenções.
Answer: A spec do JWT token prevê esse caso perfeitamente.
Somente validar se existe ou não o token é uma baita brecha de segurança e deve ser completamente evitado.
Um token JWT é uma string cifrada que contém informações a respeito de quem emitiu aquele token (sua aplicação) e qual é o sujeito daquele token (o usuário) além de outras tantas informações.
Você primeiro precisa ter certeza que seu backend está gerando o token com essas informações, depois toda vez que uma requisição for enviada ao seu backend é preciso decifrar esse token e extrair as informações não apenas verificando sua existência como você disse que está sendo feito atualmente.
Abaixo coloco alguns links da especificação JWT com detalhes dos campos e validações.

Campos iss e sub são os que eu mencionei para armazenar as informação de qual aplicação e para quem o token foi gerado.

https://www.rfc-editor.org/rfc/rfc7519#page-9

Como gerar e validar JWT tokens

https://www.rfc-editor.org/rfc/rfc7519#page-13
Não conheço Laravel mas uma simples busca no Google me retornou uma biblioteca que já implementa a especificação do JWT.
https://github.com/tymondesigns/jwt-auth
Espero ter ajudado.

Problemas com JWT token


Symmetry in moving average smoothing in "Forecasting: principles and practice"

Question: In the textbook Forecasting: principles and practice by Hyndman and Athanasopoulos, in the moving average smoothing section (Sec 6.2), the authors speak of even order moving average smoothing not being symmetric. What is the importance of symmetry in the sense that the text talks about?
Why should it be desirable?
Any help would be appreciated.
Answer: Suppose you have an increasing trend, say $y_t=t$, i.e., $1, 2, 3, 4, ...$ and a moving window of length 4.
Then at time $t$, the actual value is $y_t=t$. But the moving average is
$$ \frac{1}{4}(y_{t-1}+y_t+y_{t+1}+y_{t+2}) = \frac{1}{4}(t-1+t+t+1+t+2)=t+0.5\neq t=y_t.$$
So your moving average is biased upward by $0.5$. And completely needlessly so: if you use a symmetric moving window of length $5$ (from $t-2$ to $t+2$), the bias will disappear.
The same happens if you have seasonal data, e.g., a sine curve. Then a moving average from a rolling window of length 4 (e.g., from $t-1$ to $t+2$) will anticipate the seasonality. It will be "ahead of its time", so to say. If you use a window from $t-2$ to $t+1$, the moving average will lag the seasonality.
To be honest, the effect will likely be minor, especially for real data where the signal is obscured by noise. But it's an unnecessary ugliness, so we like to avoid it.
Answer: This is in the chapter on seasonal decomposition in Hyndman and Athanasopoulos's textbook.
Moving averages are used in seasonal decomposition to create an unbiased baseline. If we have a 5 period moving average, that moving average is symmetric because it includes the same amount of data before (2 periods) as after (2 periods).
If we have an even order, say 4, there will be more on one side than another -- the average will reflect 2 periods before and 1 period after, which is biased (biased in favor of the before data).
Comment: Thanks for your interest and help. I understand what you're saying and I hope I do not sound a bit repetitive, but why would that 'biasedness' towards the before past data not be desirable? Do you have an example? ;)
Comment: Bias is always bad. Sometimes we use biased estimates because even though they are biased, they have other desirable properties (e.g. lower variance).  But here there's no reason to tolerate the bias.


Prove that $f'(c ) = 0$

Question: Let $f: (a,b) \to \mathbb{R}$ be a function defined on $(a,b)$. Let $c \in (a,b)$ be a local maximum and $f'( c)$ exists. Prove that $f'(c ) = 0$
Sometihng I have thought so far: For some $\delta >0$, any point $x \in (c-\delta, c+\delta)$, we have $f'(c ) = \lim_{x\to c}\frac{f(x ) - f(c )}{x-c}$
According to Fermat's proposition 6.8,
If lim$_{x \to c^-}, f'(c ) \leq 0$.
if lim$_{x\to c^+}, f'(c ) \geq 0$.
Therefore, $f'(c ) =0$... (according to the Intermediate value theorem).
Would that be correct if I do that? Thanks.
Comment: Your statment that $f'(c) = \frac{f(x) - f(c)}{x-c}$ is incorrect.
Comment: You're correct. I would rather say, however, that $f'(c)=0$ because as the limit exists, it is unique.
Comment: And, yes, you need to correct the definition of $f'(c)$.
Comment: You don't need IVT. IVT is only applicable for functions $g$ which is continuous on an interval. It is not given that $f'$ is continuous.
Comment: In the two lines "If lim ... ", you do not say anything about the limits. You have the reformulate these lines.
Answer: The key here is that the derivative $f'(c)$ exists. Since as you observe (with the inequalities reversed) $$f'(c) = \lim_{x \to c^+} \frac{f(x) - f(c)}{x-c} \le 0$$ and $$f'(c) = \lim_{x \to c^-} \frac{f(x) - f(c)}{x-c} \ge 0$$ you have $0 \le f'(c) \le 0$.
The first inequality follows from the fact that if $x \in (a,b)$ and $x > c$, then $f(x) \le f(c)$ because $f$ has a maximum at $c$. This means that the fraction $$\frac{f(x) - f(c)}{x-c} \le 0$$ since the numerator is negative (or zero) and the denominator is positive. Since limits preserve non-strict inequality you can let $x \to c^+$ to find $f'(c) \le 0$.
The second inequality is similar, except when $x < c$ the denominator is negative too, so the fraction is positive or zero.
You don't need the intermediate value theorem to conclude that $f'(c) = 0$.
Comment: $f(c)\geq f(x)\Rightarrow f(x)-f(c)\leq 0$ since $c$ is a local maximum, yes?  Would not the direction of the inequalities be reversed then, as $\lim\limits_{x\to c^+}$ implies $x>c$, etc...
Comment: Thanks for noticing and pointing out the error. I corrected it.
Comment: @Jmoravitz Thanks. Now I understand that too.
Comment: This is the Alternative Intermediate Value Theorem: If $a\le x\le b$, and $a=b$, then $x=a$. Furthermore, $x=b$.
Comment: @UmbertoP. I know I understand the concept intuitively, but with all the limits coming from left and right are still causing me confusion to understand why is your first expression $\leq 0$ and the second one $\geq 0$. Would you mind if you illustrate that a bit written. I also understand that $f(c ) \geq f(x)$, since there is a local maxima at point $c$. Thanks.
Comment: @Jellyfish I added a few lines to hopefully clarify.
Comment: @UmbertoP. Thank you so much. Now I understand.

Prove that $f'(c ) = 0$


Deriving the Jacobi Equation

Question: In do Carmo's book in chapter 5 he is deriving the Jacobi equation (ref. page 111), the setup is as follows:
$f(t,s)$ is a specified parametrized surface, and we know that for all $(t,s)$ we have $\frac{D}{\partial t}\frac{\partial f}{\partial t}=0$ where $\frac{D}{\partial t}$ denotes the covariant derivative. Then by using the fact that
$\frac{D}{\partial t}\frac{D}{\partial s}V - \frac{D}{\partial s}\frac{D}{\partial t}V=R(\frac{\partial f}{\partial s},\frac{\partial f}{\partial s})V$, we have

$0=\frac{D}{\partial s}(\frac{D}{\partial t}\frac{D}{\partial s}\frac{\partial f}{\partial t})- R(\frac{\partial f}{\partial s},\frac{\partial f}{\partial t})\frac{\partial f}{\partial t}$
$=\frac{D}{\partial t}(\frac{D}{\partial t}\frac{D}{\partial s}\frac{\partial f}{\partial s})+ R(\frac{\partial f}{\partial t},\frac{\partial f}{\partial s})\frac{\partial f}{\partial t}$

It is obvious how the first equality follows from the above fact, but how do we get the second?
Answer: You didn't copy correctly what he wrote.
He does the following:
\begin{align}0&=D_s (D_t \partial_t f) \\
&=D_tD_s \partial_t f-R(\partial_s f, \partial_t f)\partial_t f\\
&=D_t D_t \partial_s f + R(\partial_t f, \partial_s f)\partial_t f,
\end{align}
where the first equality follows, as you said, from your equation and the second from the symmetry of the curvature tensor and from the symmetry of the covariant derivative along parametrized surfaces.

Deriving the Jacobi Equation


Harmonic analysis of progression: Fm, E♭, D, Gm

Question: How would you analyze the sequence |: Fm  E♭  D  Gm :|
I hear Gm as the tonic, but that might be just because of the previous D as dominant. Fm and E♭ seem to be in the key of Fm (maybe a dorian flavor). Is it the case that the single appearance of the dominant introduces a modulation from Fm to Gm?
Comment: It's kind of dependent on other factors as well, rhythm, melody, etc., but maybe consider this as G minor with a bit of subdominant or Phrygian influence. F minor is the only harmony that doesn't fit directly in G minor.
Comment: Do you mean that you want to label the chords with Roman numerals for analysis?
Comment: @MichaelCurtis That's right, identifying secondary dominants, borrowed chords and so on.
Answer: Just using the details given, and assuming the keys are Fm and Gm, I think you would write an analysis something like this:
f: i VII g: V i

But, as @Dom points out, you should only use the key labels if a key is clearly established. Perhaps something more like this:
f: ii V7 i g: VI V i

But this isn't your case. Given the repeat signs it looks like the four chords repeat over and over, and it's not a case of modulation.
When it's appropriate you can indicate key changes with the key name and a colon. The roman numerals are then understood to be in the context of the labeled key.
Comment: That analysis is not correct. There is nothing that makes you modulate from one key to another in those 4 chords so saying that it is in two different keys is not accurate at all. The examples you use show complete modulation.
Comment: That isn't *my* analysis. I'm only showing the symbols used write out such an analysis, because that is what the OP asked about. I only used the keys they were suggesting.
Comment: It still wouldn't be in two keys which is the issue I have. Saying there are multiple keys in the analysis  needs to be backed up.
Comment: I modified my answer to show the OP's original suggestion, but it isn't the best analysis.
Answer: It's just in G minor with the F minor being borrowed most likely from another mode as Patrx2 says. Most people would just call it a vii VI V i in G minor an be done with it as you're just altering the 3rd of the subtoinc chord and that's all that is different.
If you really wanted to be fancy, you could argue that  the Fm is a secondary chord of the E♭ making the progression a ii/VI VI V i in G minor, but since the secondary doesn't have a very functional purpose this doesn't really make much of a difference in the analysis.
Answer: I'd analyse it just as you already have, by noting the chord names.  From the information you have given we can't do much more, and can only guess at a tonal centre.  (Let's not say "at a key", because that could lead to a fruitless discussion whether bVII is an acceptable chord.)  D, Gm does indeed hint at a dominant - tonic function (D7 would have made it even stronger).  But not every dominant - tonic pair has to lead to THE tonic.


Angular 7: como atualizar a variável no html automaticamente quando o valor da mesma for alterada no arquivo .ts?

Question: Eu tenho uma variável que recebe valor quando a página renderiza, e ele parece corretamente no template. Entanto se eu alterar o valor dela com a página já carregada o valor no .ts fica atualizando (conferido com console.log) mas no html permanece sem mudança.
Eu já tentei utiliar o ngModel mas isso não deu certo porque também estou utilizando um array de objetos e objetos desse array.
html

     <textarea class="textarea" id="item-textarea" [value]="item.text">
     </textarea>

Ts
public itens:any[] = [];

constructor() {

}

ngOnInit() {
    this.initItens();
    this.changeItens();
}

initItens() {
    let item = new Item();
    item.text = "Hello world";
    this.itens.push(item);
}

changeItens() {
    let item = new Item();
    item.text = "Bye bye World";
    this.itens.push(item);
    console.log(this.itens); //saída conforme o esperado
}

Gostaria de saber o que é necessário ser feito para poder sempre que atualizar a variável no arquivo .ts também atualizar no html, para o angular 7.
Obrigada.
Comment: Tenta assim: this.itens=[...this.itens,item];
Answer: Tenta mudar a referencia do seu array pro angular saber que algo mudou.
 this.itens=[...this.itens,item]

Comment: ajudou, obrigada


mvc 4 missing anything on these cascading dropdowns

Question: hello good evening everybody I am trying to get data when one of my dropdown selected index change here are my codes I couldn't get where am ı missing or doing something wrong I am very glad if you help me thank you .
this is my script code
$("#ddOrder").change(function (e) {
            alert = "basıldı";
            var oID = $(this).val();
            $.getJSON("../Accessory/loadWorkshops", { _orderId: oID },
                   function (data) {
                       var select = $("#ddAcc");
                       select.empty();
                       select.append($('<option/>', {
                           value: 0,
                           text: "Aksesuar seçiniz"
                       }));
                       $.each(data, function (index, itemData) {
                           select.append($('<option/>', {
                               value: itemData.Value,
                               text: itemData.Text
                           }));
                       });
                   });
        });

these are my controller codes
public ActionResult addAccessoryShipment()
    {
        if (Session["_userName"] == null)
        {
            return RedirectToAction("Index", "Home");
        }

        HelperPartial _helper = new HelperPartial(
            ViewData,
            Session["_userName"].ToString(),
            Session["_userPermissionId"].ToString()
            );

        Repository<Order> _ro = new Repository<Order>();
        IEnumerable<SelectListItem> _orderSelectListItem = _ro.All().AsEnumerable().Select(s => new SelectListItem
        {
            Text = s.code,
            Value = s.id.ToString()
        }).OrderBy(o => o.Text);

        ViewData["ddOrder"] = _orderSelectListItem;

        Repository<AccessoryList> _ra = new Repository<AccessoryList>();
        IEnumerable<SelectListItem> _clothSelectListItem = _ra.All().AsEnumerable().Select(s => new SelectListItem
        {
            Text = s.name,
            Value = s.id.ToString()
        }).OrderBy(o => o.Text);

        ViewData["ddaList"] = _clothSelectListItem;

        return View();
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult loadWorkshops(string _orderId)
    {
        //IEnumerable<MyCustomerProductType> _myCustomerProductType = _rc.All().Select(s => new MyCustomerProductType { id = s.id, customerName = s.customer.name, productTypeName = s.productType.name });

        int _oId = Convert.ToInt32(_orderId);

        Repository<OrderCloth> _ra = new Repository<OrderCloth>();

        IEnumerable<MyOrderCloth> _clothSelectListItem = _ra.All().Where(o => o.orderId == _oId).Select(s => new MyOrderCloth
        {
            workshopName = s.workshop.name,
            workshopId = s.workshopId
        });

        List<SelectListItem> _workshopListItem = new List<SelectListItem>();

        foreach (MyOrderCloth item in _clothSelectListItem)
        {
            _workshopListItem.Add(new SelectListItem
            {
                Text = item.workshopName,
                Value = item.workshopId.ToString()
            });
        }

        //ViewData["ddwList"] = _workshopListItem;

        return Json(_workshopListItem, JsonRequestBehavior.AllowGet);
    }

and here are my view codes
  @using (Html.BeginForm("AccessoryShipmentAdd", "Accessory", FormMethod.Post))
{
        @Html.ValidationSummary(true)

        Sipariş No

            @Html.DropDownListFor(model=>model.orderId,(IEnumerable<SelectListItem>)ViewData["ddOrder"],"seçim yapınız",new {id="ddOrder", @class = "span6 chosen"})

        @Html.ValidationMessageFor(model => model.orderId)

        Atölye Seçiniz

            @Html.DropDownListFor(model=>model.workshopId,new SelectList(Enumerable.Empty<SelectListItem>(),"workshopId","workshopName"),"seçim yapınız",new {@id="ddAcc" ,@class = "span6 chosen"})

        @Html.ValidationMessageFor(model => model.workshopId)

        Aksesuar Seçiniz

            @Html.DropDownListFor(model=>model.accessoryListId,(IEnumerable<SelectListItem>)ViewData["ddaList"],"seçim yapınız",new { @class = "span6 chosen"})

        @Html.ValidationMessageFor(model => model.accessoryListId)

I can get datas from loadWorkshops class but it doesnt return to my dropdown. what can I do for this ?
Answer: Try this (change "/>" in option to ">"):
$("#ddOrder").change(function () {
        var oID = $(this).val();

        $.getJSON("../Accessory/loadWorkshops", { _orderId: oID },
            function (resultData) {
                var selectACC = $("#ddAcc");
                selectACC.empty();
                selectACC.append($('<option>', {
                    value: 0,
                    text: '-- Aksesuar seçiniz --'
                }));

                $.each(resultData, function (index, itemData) {
                    selectACC.append($('<option>', {
                        value: itemData.Value,
                        text: itemData.Text
                    }));
                });
            });
    });

Update your controller to something like this:
//Place the fetching of data in private
private IList<MyOrderCloth> GetClothOrders(int _orderId)
{
    Repository<OrderCloth> _ra = new Repository<OrderCloth>();

    IList<MyOrderCloth> clothOrders = null;

    clothOrders = _ra.MyOrderCloth.Where(o => o.orderId == _orderId).ToList();

    return clothOrders;
}

//Accessed by Javascript
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult loadWorkshops(string _orderId)
{
    int id = 0;

    if (!string.IsNullOrEmpty(_orderId))
    {
        id = Convert.ToInt32(_orderId);
    }

    var clothList = GetClothOrders(id);
    var clothData = clothList.Select(a => new SelectListItem()
    {
        Text = a.workshopName.ToString(),
        Value = a.workshopId.ToString(),
    });

    return Json(clothData, JsonRequestBehavior.AllowGet);
}

Comment: I am gonna be crazy .. I can see the data in controller but my dropdown is still empty :)
Comment: Change your dropdown @id="ddAcc" to just id="ddAcc". Javascript could not find your dropdown control that's why.


How to keep multiple drupal websites up to date

Question: I do a lot of web consulting and drupal is my preferred tool of choice. But as I grow, it seems like drupal gets more and more needy. At least once a week, if not more, my inbox gets messages that drupal needs updating, and I have to go and update the dev server, verify nothing broke, and then update the production server, and again verify that nothing broke.
I'm using drush to help me with this, but this is still taking considerable time away from my business, time I could be billing to the customer.
Does anyone have a solution to this? Some way to automate the updates and then a regression test, and if successful, do the same on production?
Answer: You could write scripts to do this.  You'd probably want to tie in to the Drupal unit testing module as well.
I can't provide you with any actual examples, because I'm not sure how it would be done reliably.
In my opinion, you're looking at a business problem that can't be fixed with a programming solution.  If I were in your shoes, I would start charging customers an ongoing maintenance fee for upgrades.
Answer: I use the following script:
https://github.com/greg-1-anderson/utiliscripts/blob/master/drupal-backup-all
n.b. not guaranteed to be bug-free.  The "verify nothing broke" and "update the production server" are manual steps, but at least my update sites are available for testing when I want to do it.


Multiple notification icons on one bar?

Question: Is it possible to create a notification bar that contains multiple icons horizontally and each icon launches a separate service/activity?
Comment: Are you talking about replacing the stock notification bar in Android, or is it a custom notification bar inside your own application you want to make?
Comment: Sorry, I mean the pull down notification area.
Answer: No, a notification only has a single PendingIntent (as seen in this API method). You could conceivably create a custom notification layout with multiple icons, but you could only launch one activity.
Update:
Actually if you read that doc carefully, it looks like as of API 11, you can do what you're trying to accomplish by setting RemoteViews.setOnClickPendingEvent on your views in your custom layout!
Comment: I see.  Would it be possible to pass a variable to the one activity, but the variable changes depending on which icon is clicked?
Comment: Apparently it's changed in API 11, updated answer to reflect that.

Multiple notification icons on one bar?


Clarification regarding claim that the class Safe is exception safe

Question: You'll find on page 937 of this document the following code:
template<class T> class Safe
{
    T* p;  // p points to a T allocated using new
    public:
    Safe() : p(new T) {}
    ~Safe() { delete p; }
    Safe& operator=(const Safe& a) { *p = *a.p; return *this; }
    // ...
};

It seems like, the object that was pointed by p will be leaked in the assignment operator above.
Answer: It isn't a leak because he isn't CHANGING the pointer. If he did
Safe& operator=(const Safe& a) { p = a.p; return *this; }

Then it would be a memory leak. He's doing an assignment to the object pointed to by p, not to p itself.
Answer: No. There will be no leaks because he did not change the pointer. Of course, it's still missing the copy constructor, but beyond that, there is no error.
Comment: I'm giving you the credit for the answer, for this was the first I received.
Answer: The assignment is not a problem: It isn't the pointers being assigned but the pointed to values. Assuming T's assignment is exception safe, Safe<T>'s copy assignment is safe, too. However, the class is missing the copy constructor.


How update the column value depending on the value of other column by procedure?

Question: In PostgreSQL database I have table called RELATIONSHIP:
| SURVEY_ID                            | EMPLOYEE | ORGANIZATION_NAME | STATUS (default: false) |
|--------------------------------------|----------|-------------------|-------------------------|
| d5f9c639-13e6-42c1-9043-30783981724b | Mark     | Apple             | false                   |
| d5f9c639-13e6-42c1-9043-30783981724b | Bob      | Apple             | true                    |

This table has unique key which you can create by next sql statement:
ALTER TABLE RELATIONSHIP ADD CONSTRAINT RELATIONSHIP_UNIQUE_KEY UNIQUE (SURVEY_ID, EMPLOYEE);

Lets say I want to add new 3 record by procedure in RELATIONSHIP table.
CALL creator(
    'd5f9c639-13e6-42c1-9043-30783981724b',
    ARRAY['Mark', 'Bob', 'Kate'],
    ARRAY['Google', 'Google', 'HP']
);

If SURVEY_ID and EMPLOYEE values are unique and there is no such record in the table I want to add that record to the table. For example third record wasn't in table in the beginning. For thats why I add it. In the same time if SURVEY_ID and EMPLOYEE values are not unique and there was such record in the table I don't want to add them. For example first and second records. The problem is that I need to update value of ORGANIZATION_NAME column if status is true. For example first record's status false. For thats why I need to update the value of ORGANIZATION_NAME column from Apple to Google. The second record does not change. How to make this update correctly?
Other word, I want such result finally:
| SURVEY_ID                            | EMPLOYEE | ORGANIZATION_NAME | STATUS (default: false) |
|--------------------------------------|----------|-------------------|-------------------------|
| d5f9c639-13e6-42c1-9043-30783981724b | Mark     | Google            | false                   |
| d5f9c639-13e6-42c1-9043-30783981724b | Bob      | Apple             | true                    |
| d5f9c639-13e6-42c1-9043-30783981724b | Kate     | HP                | false                   |

Right now my procedure looks like this:
CREATE OR REPLACE PROCEDURE creator(SURVEY_IDENTIFIER uuid, EMPLOYEES VARCHAR[], ORGANIZATION_NAMES VARCHAR[]) AS $FUNCTION$
    BEGIN
        INSERT INTO RELATIONSHIP (SURVEY_ID, EMPLOYEE, ORGANIZATION_NAME)
        SELECT
            SURVEY_IDENTIFIER SURVEY_ID,
            EMPLOYEE FROM UNNEST(ARRAY[EMPLOYEES]) EMPLOYEE,
            ORGANIZATION_NAME FROM UNNEST(ARRAY[ORGANIZATION_NAMES]) ORGANIZATION_NAME
        ON CONFLICT ON CONSTRAINT RELATIONSHIP_UNIQUE_KEY
        DO NOTHING;
    END;
$FUNCTION$ LANGUAGE plpgsql;

PROBLEM:
SQL Error [21000]: ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time Tip: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.

The problem is partially solved after adding SELECT DISTINCT as you adviced.
If I call procedure with such values there is no error:
CALL creator(
  '99c89a24-fff2-4cbc-a542-b1e956a352f9',
  ARRAY['Mark', 'Kate', 'Mark'],
  ARRAY['NEXT', 'U12', 'NEXT']
);

The problem is teal the same if I call procedure with such values:
CALL creator(
  '99c89a24-fff2-4cbc-a542-b1e956a352f9',
  ARRAY['Mark', 'Kate', 'Mark'],
  ARRAY['NEXT', 'U12', 'HP']
);

What can be done in this case in your opinion? I think the best way in this case is to set the last value of ORGANIZATION_NAME. In mean would be better to set HP.
Answer: You want to change the ON CONFLICT clause:
INSERT INTO RELATIONSHIP (SURVEY_ID, EMPLOYEE, ORGANIZATION_NAME)
    SELECT SURVEY_IDENTIFIER as SURVEY_ID,
           u.EMPLOYEE, u.ORGANIZATION
    FROM UNNEST(ARRAY[EMPLOYEES],
                ARRAY[ORGANIZATION_NAMES]
               )  u(EMPLOYEE, ORGANIZATION_NAME)
    ON CONFLICT ON CONSTRAINT RELATIONSHIP_UNIQUE_KEY
        DO UPDATE SET ORGANIZATION_NAME = EXCLUDED.ORGANIZATION_NAME
                  WHERE NOT RELATIONSHIP.STATUS;

Note that I also changed the FROM clause to do a parallel unnesting of the arrays.  I do not recognize the double FROM syntax used in the query in your question.
For the last problem, I think this version of the query will work:
    SELECT DISTINCT ON (u.EMPLOYEE) SURVEY_IDENTIFIER as SURVEY_ID,
           u.EMPLOYEE, u.ORGANIZATION
    FROM UNNEST(ARRAY[EMPLOYEES],
                ARRAY[ORGANIZATION_NAMES]
               ) WITH ORDINALITY u(EMPLOYEE, ORGANIZATION_NAME, n)
    ORDER BY u.EMPLOYEE, n DESC

Comment: @NurzhanNogerbek . . . Does `SELECT DISTINCT` solve that problem?
Comment: Thank you for your answer. I seems to me that we need a condition when updating the value of `ORGANIZATION_NAME` column. As I said before in post I need to update the value of `ORGANIZATION_NAME` column only if `STATUS` column of existing record has `false` value. For example Mark's organization name changed, but Bob's organization name not. Do you have any ideas about this moment?
Comment: @NurzhanNogerbek . . . You can add a `WHERE` clause.
Comment: Sorry for this question but how correctly I need to call this procedure? In my original post you can notice the example code of how I call procedure. Right now procedure show me such error when I try to run it: `SQL Error [42P01]: ERROR: missing FROM-clause entry for table "u". Where: PL/pgSQL function creator(uuid,character varying[],character varying[]) line 3 at SQL statement`. Do you have any ideas?
Comment: I changed from `u.ORGANIZATION_NAME` to `excluded.ORGANIZATION_NAME`. Now it say that something wrong with `where` condition: `SQL Error [42702]: ERROR: column reference "status" is ambiguous`.
Comment: Well, finally I found 3 mistake. 1) column skipped. Must be: `*** SURVEY_ID, EMPLOYEE, ORGANIZATION_NAME FROM ***`. 2) Instead of  `u.ORGANIZATION_NAME` change to `excluded.ORGANIZATION_NAME`. 3) Also in `where` condition must be `WHERE NOT RELATIONSHIP.STATUS`. Please can you update your answer? I can mark it as correct in that case.
Comment: The only problem which I notice is that procedure raise error if I try to add the same values. `SQL Error [21000]: ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time Tip: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.` I would be grateful to your advice.
Comment: The problem is partially solved. Can you check my post again please?! I explained why the problem is only partially solved. What can you advice to situation which I described?


Harp Multiple Glissando

Question: I don't know if it is the correct term, but how to write in the score a harp glissando where the hands pass many times from the start note to the endnote?
Here's an audio example: https://drive.google.com/file/d/1k__35AsIYI9JmHycT1vBEBNfbLu_MbG0/view?usp=sharing
Answer: After some research I found what might be the answer: Slow Cluster Glissando
Answer: The classical solution I can find is to notate multiple glissando lines, emphasized by an explicit note "up and down ad libitum".

(Source: Symphony No. 9, Ralph Vaughan Williams)

Harp Multiple Glissando


How to access to node on form_submit

Question: I added a button to the page. I'm trying to get the values of the field when I click the button. But I can not understand how to access the node from submit? Am I on the right track or should I look for another solution? I tried to add $node to the function redirect_button_form_submit but this does not work.
function show_on_map_node_view($node, $view_mode, $langcode) {
    $url = url(current_path(), array('absolute' => TRUE));
  if (($node->type == 'addproblem') && (strpos($url, "problem"))) {
    $form = drupal_get_form('redirect_button_form');
    $node->content['redirect_button'] = $form;
 }
}

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Show on map'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
//How to access the $node here?

    $geofield = field_get_items('node', $node, 'field_location_exif');
    $location = array(lat => $geofield[0][lat], lon => $geofield[0][lon]);
    $path = '<front>';
    $options = array('query' => $location);
    drupal_goto($path, $options);
}

Answer: You can pass the node as an argument to your form builder and store it there.
$form = drupal_get_form('redirect_button_form', $node);

function redirect_button_form($form, &$form_state, $node) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Show on map'),
    );

    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    $node = $form_state['build_info']['args'][0];

    $geofield = field_get_items('node', $node, 'field_location_exif');
    $location = array(lat => $geofield[0][lat], lon => $geofield[0][lon]);
    $path = '<front>';
    $options = array('query' => $location);
    drupal_goto($path, $options);
}

drupal_get_form can take additional arguments besides $form_id.

Any additional arguments are passed on to the functions called by
  drupal_get_form(), including the unique form constructor function. For
  example, the node_edit form requires that a node object is passed in
  here when it is called.

Also, to do a form redirect you can use:
$form_state['redirect'] = path...
Instead of drupal_goto which should not be used here.

When $form_state['redirect'] is an array it should be populated with
  arguments appropriate for drupal_goto() - which is to say, the second
  element in the array can itself be an array holding all the properties
  expected by url()'s $options argument, including fragment, query,
  absolute, etc.
Comment: Oh, and I overlooked this - you should not use drupal_goto to do a form redirect. Set the path with `$form_state['redirect'] = path...`.

How to access to node on form_submit


How to reasonably estimate the probability of your father being exactly 12222 days older than you?

Question: On 2024/05/03, my brother is 10,000 days of age, while my father will be 22,222 days old.
To tell them as a fun-fact, I would like to grab a feel of how special this is. I have no access to datasets that could provide me a distribution of the likelihood of becoming a parent at n days of age. It doesn't matter whether this child is the father's first child.
(Off-topic: I asked chat gpt for inspiration on how to celebrate this event, and to my surprise it was quite creative as long as it didn't have to organize it itself.)
Kind regards from Belgium
Comment: I think we have to try to define what counts as "special". Would it also be similarly "special" if on that date, your dad were 15000/16000/17000/18000/19000/20000/21000 etc. days old? What about 15555/16666/17777/etc.? What about 23456?
Comment: The probability of being *exactly* 12,222 days old is probably quite low, but not significantly higher or lower than being exactly 12,221 or 12,223 days old. There's also the question of whether you want the absolutely probability P(12222 days old) or some conditional probability P(12222 days old | age between X and Y days) for some age range X-Y days old. (The narrower the range, the higher the probability, assuming 12222 is in [X, ]. If it isn't, of course, the probability is zero.)
Comment: @user182601:  Reminds me of that quote from Richard Feynman:  "You know, the most amazing thing happened to me tonight... I saw a car with the license plate ARW 357. Can you imagine? Of all the millions of license plates in the state, what was the chance that I would see that particular one tonight? Amazing!"
Comment: _"It doesn't matter whether this child is the fathers first child."_ In fact, it does not matter at all if he is the fathers ot "his" child. Forecasts of growth in population base only on momens quota. BTW, while you are at it, my father was  21.850 days older than me (due to 2nd WW) -- how likely is that?
Comment: @MichaelSeifert: These days, I imagine it would be pretty low; that car is probably from the 1950s (maybe 1960s)!
Comment: I think what you are really asking is what is the probabilty of two events decades  apart with have a difference in day number where all the digits but the first one are the same.  In this case the probabilty that the last two are the same is $1$ in $10$.  That the last three are the same is $1$ in $100$ and so on.  That the difference of day is has the last four digits the same is $1$ in a $1000$.  But just because something specific is unlikely doesn't mean it is unusual.  Had the been born $12,587$ days apart there could have been something *else* that was interesting.
Answer: Oops, you do say that you're from Belgium (I somehow missed that at first), but I'm going to use statistics from the U.S., because that's what I found first.
If your brother turns $10\,000$ days old on $2024$-$05$-$03$, then they were born in December $1996$. At that time, fathers' ages were approximately normally distributed with a mean of about $\mu \approx 30.0$ and a standard deviation of about $\sigma \approx 6.7$. Your father was about $33.5$ years old, so about $z \approx 3.5/6.7 \approx 0.52$ standard deviations above the mean.
The probability density function (PDF) of the standard normal distribution is
$$
f(z) = \frac{1}{\sqrt{2\pi}}e^{-\frac{z^2}{2}}
$$
Here, that evaluates to $f(0.52) \approx 0.35$. One day is about $\frac{1}{6.7\cdot365} \approx 0.00041$ standard deviations, so the probability of falling in a one-day slice $3.5$ years above the mean is about $0.00041 \times 0.35 \approx 0.00014$, or about one chance in $7000$. (I kept some extra digits around till the end.)
I wouldn't trust that figure very far, but this gives an idea of how to ball park it. It's not very far off Robert Israel's result. Keep in mind, though, that there are probably quite a few numbers you would consider as remarkable as $12\,222$.

ETA (2024-02-09). Bringing a caveat from the comments into this answer: ajd138 from the comments suggested that the normal approximation wasn't appropriate for the father's age at the child's birth. That's clearly true at the extremes, but in this case the age is less than a standard deviation above the mean, and my guess is that the normal approximation is not bad in the neighborhood of the mean.
This answer was intended to show a method for using a parametric distribution—the normal distribution, in this case—for obtaining a probability. If such a distribution is not available, one can use the method in Dan's answer and simply find a sufficiently fine histogram for the probability. However, if someone has an idea for a better parametric distribution, I'm all ears!
Note also that Amir's answer raises an interesting issue with respect to the father's probability of surviving to see their child's $10\,000$th day. The impact of conditioning on the father's survival is an interesting one, although I think the question's interpretation doesn't obviously rest on that condition.
Comment: @ajd138: Certainly in the extremes it is not. Near the mean, I don't think it's a bad approximation, and I submit it's better than a uniform distribution across some interval. Do you have a better parametric one for the data I adduced, by any chance? ETA: Oops, I switched sources at some point; I don't think the one I linked to actually has a breakdown by age. Sorry! Still interested to hear if you have a good alternative characterization, though.
Comment: @Dan: There might be others—$12\,221, 12\,321, 11\,211, \ldots$. It's hard to say exactly what the OP might find equally remarkable, but there are surely quite a few, as I say!
Comment: If you assume that the father-son age difference is between 20 and 40 years, then there are 8 possible day counts that are "remarkable" in having the last 4 digits the same: 7777, 8888, 9999, 10000, 11111, 12222, 13333, and 14444.
Comment: I don't think a normal distribution is appropriate in this case
Comment: I'm really flattered to see so much solid responses(!) thanks to all of you! The answers indeed converge to an order of magnitude of 1/7000, therefore suggesting that *if* I would consider my brother as a normal representative random sampled Belgian, then 1655 Belgians would normally already share this unique special case^^. So unworthy for instance to bother a local press instance to cram this into a little article^^.
Comment: @PieterDepamelaere: You can still think of it as special for happening *to you* as opposed to someone else. See also [this video](https://youtu.be/6JwEYamjXpA?si=kni32VctP3tg5TpG&t=2859).
Answer: 12,222 days = 33 years (and about 5½ months)
I haven't been able to find information specific to Belgium, but if you assume that the age distribution of fathers is similar to Norway, then the probability of your dad being 33 when you're born is approximately 5%.
If you assume that all birth dates between your dad's 33rd and 34th birthdays are equally probable, then the probability that he's exactly 12,222 days older than you works out to $\frac{0.05}{365} \approx 0.000137$, or about 1 in 7300.
Comment: ... and so about $1$ in $7300$ just like @BrianTung's answer
Comment: I'm really flattered to see so much solid responses(!) thanks to all of you! The answers indeed converge to an order of magnitude of 1/7000, therefore suggesting that *if* I would consider my brother as a normal representative random sampled Belgian, then 1655 Belgians would normally already share this unique special case^^. So unworthy for instance to bother a local press instance to cram this into a little article^^.
Answer: In Western societies, males typically have children from, let's say, age $20$ to $45$ years, or about $7300$ to $16400$ days. I haven't looked up detailed statistics, and they would in any case differ from country to country and from year to year.  That's a span of about $9100$ days, and as a very rough estimate
any of those $9100$ days would have probability about $1/9100$ of being the difference between your father's age and yours.
Comment: I'm really flattered to see so much solid responses(!) thanks to all of you! The answers indeed converge to an order of magnitude of 1/7000 or indeed a 1/9100 underbound based on a uniform distribution baseline. This suggests that *if* I would consider my brother as a normal representative random sampled Belgian, then 1655 Belgians would normally already share this unique special case^^. So unworthy for instance to bother a local press instance to cram this into a little article^^.
Comment: "this unique special case"  I think it's important that you identify just what the unique special case actually *is*.  Is it that $12,222$ is an interesting number because of all the $2$s.  Had the been $13,333$ days apart would that have been boring and uninteresting? What if they were born $12,345$ days apart?  What if they were born, $10,529$ days apart?  The probability of *that* happening is *exactly* the same as being born $12,222$ days apart.
Answer: For computing the probability, it is not enough to only focus on the father's paternal age. We also need to consider that both father and brother survive until 05-03-2024.
As described below in detail, what computed in the other three answers is the probabilty of the following event:
$B$: The father has a child 10,000 before 05-03-2024.
and not the event given in the OP:
$A$: On 05-03-2024, the father is 12222 days older than the brother (his son).
One can see tha A happens only if the following event also occurs:
$\color{blue}{C}$: The father and his son survive until 05-03-2024.
That is
$$A=B \cap \color{blue}{C}.$$
Thus, the probability of that on  05-03-2024 the father is 12222 days older than the brother, event $A$, is
$$\mathbb P(A)=\mathbb P(B \cap\color{blue}{C})=\color{blue}{\mathbb P \left ( \text{Brother's age} \ge 10000 \right ) \times \\ \mathbb P \left ( \text{Father's age} \ge 22222 \, \big | \, \text{Father's age} \ge 12222  \right )} \times \\ \mathbb P \left ( \text{Father's paternal age} \in [12222,12222+1]  \right ).$$
Above, we hiddenly assume that 1) the father was alive 10000 days ago, 2) the residual life is not affected by the paternal time, and 3) the reference time for calculation of the probability is a time instant before the father becomes 18 years old; see case A.1 in the first part below on reference time.
If the lifespan (LS) of a Belgian man follows pdf $f_{LS}$ with cdf $F_{LS}$, and the paternal age (PA) of a Belgian man follows pdf $f_{PA}$ with cdf $F_{PA}$; then the probability is approximately:
$$
\fbox{$\color{blue}{\left (1-F_{LS} (10000) \right )\frac{ 1-F_{LS}(22222) }{  1-F_{LS} ( 12222  ) } } f_{PA} ( 12222  ) $}$$
in which the following approximation is used: $$F_{PA} (12222+1 )-F_{PA} (12222)\approx f_{PA} (12222 ).$$
Computation of probability when both LS and PA distributions are normal
If the lifespan of a Belgian man follows $N(\mu_1,\sigma_1^2)$, and the paternal age of a Belgian man follows $N(\mu_2,\sigma_2^2)$; the probability is approximately:
$$
\color{blue}{\left (1-\Phi \left ( \frac{10000-\mu_1}{\sigma_1} \right ) \right ) \times \\
\frac{\left (1-\Phi \left ( \frac{22222-\mu_1}{\sigma_1} \right ) \right )}{1-\Phi \left ( \frac{12222-\mu_1}{\sigma_1} \right) }} \times \\ \frac{1}{\sqrt{2\pi}\sigma_2} e^{-\frac{(12222-\mu_2)^2}{2\sigma_2^2}} .$$
For
$$\mu_2 \approx 30.0×365, \sigma_2 \approx 6.7×365,$$
it can be significantly smaller than about 1 in 7000, obtained in other answers depending on the mean (life expectancy) $\mu_1$ and standard deviation $\sigma_1$ of the lifespan.
In fact, the probability can be written as
$$\color{blue}{k }\times \frac{1}{7000} $$
where $$k=\left (1-\Phi \left ( \frac{10000-\mu_1}{\sigma_1} \right ) \right ) \times \frac{\left (1-\Phi \left ( \frac{22222-\mu_1}{\sigma_1} \right ) \right )}{1-\Phi \left ( \frac{12222-\mu_1}{\sigma_1} \right) }.$$
Let $\sigma_1=\sigma_2 \approx 6.7×365$ and consider the following scenarios:
for $\mu_1 \approx 50.0×365$,  $\, \color{blue}{k=0.05251}$
for $\mu_1 \approx 60.0×365$,  $\, \color{blue}{k= 0.44764} $
for $\mu_1 \approx 70.0×365$,  $\, \color{blue}{k=0.91322} $
for $\mu_1 \approx 80.0×365$,  $\, \color{blue}{k=0.99784}.$
Hence, when the life expectancy is greater than 80 years old, which is the case for Belgian men according to this site, then $k \approx 1$ (under the normality assumption, which is strongly criticized below; see the second part below on distributions).
Reference time for calculation of probability
To calculate the probability of a temporal event, we must fix the time at which we calculate the probability, called here reference time. The level of uncertainty of the event varies over the time. Different cases are considered below (the adverb ago in the following stands for the days before the specific date of 05-03-2024, not current date).
A- The reference time for calculation of the probability is before the birth of the brother (so we need to take into account the survival of both too). Here, we have two sub-cases:
A.1. The reference time is before $22222-18 \times 365$ days ago (we have done our analysis above based on this assumption).
A.2. The reference time is between $22222-18 \times 365$ days ago and $22222-10000$ days ago.
In A.2, as the father gets older, the distribution of the paternal age may be affected and needs to be updated using a conditional distribution.
In both A.1 and A.2, we assume that the father's paternal age is always greater than 18.
B- The reference time for calculation of the probability is after the birth of the brother and before the specific date of 05-03-2024.
In this case, we don't need to take into account that the father becomes a parent 10000 days ago, as he is a father now.
However, the event is still uncertain. In this period, the probability only depends on that both father and brother survive until the specific date in the remaining days.
C-  The reference time for calculation of the probability is after the specific date of 05-03-2024. In this case, the event becomes fully certain, and the probability of occurrence of the event is nothing but 1.
Remark: One may think we can ignore the surviving part of the event (considering it as here-and now, occurring with probability 1) and only focus on the birth part as wait-and- see, because when the father and brother are informed about the event they are required to be alive; while based on the above described cases, you can clearly see that in this reasoning two different reference times for calculation of the probabilities of the birth and surviving parts of the event are hiddenly considered, which is not correct.
Distributions of lifespan and paternal age
As pointed in a comment below by @Nuclear Hoagie, the normal distribution may be problematically narrow for the lifespan, as it puts 95% of people within 13.4 years of the average lifespan. For $\mu_ 1=50$, it means almost no one lives to even 65, and for $\mu_ 1=80$, almost all pass 65 years old. Hence, more reasonable distributions for lifespan $f_{LS}$ and the paternal age $f_{PA}$ need to be considered.
This paper, on a data set from Swiss, shows that proportional hazard (PH) Weibull and Gompertz model and skew-normal distribution are the best for the lifespan distribution, shown below for men and women:
Comment: I'm not quite sure how this gets to an answer an order of magnitude different than the others, it seems the main difference is including the probability both people survive long enough (in addition to the probability their birthdays are at the right interval to begin with). But that would imply that only 1 in 10 father-son pairs survive to the son's 28th birthday, which surely cannot be the case.
Comment: I find the normal distribution of lifespans to be problematically narrow - it puts 95% of people within 13.4 years of the average lifespan. At u1=50, it means almost no one lives to even 65, and at u1=80, it means practically everyone lives past 65, but those aren't very good models of population. A Belgian life expectancy of 80 years doesn't indicate that nearly 99.9% of Belgians reach their 60th birthday, which is what the normal distribution using an SD of 6.7 years implies.
Comment: I grant the point. What is $k$ in this case?
Comment: @Amir: Although—I wonder if OP would have found it any less remarkable in the unfortunate case where his father did not survive to see his $22\,222$nd day.
Comment: @BrianTung  Thank you! I just added $k$ for different scenarios. It depends on the mean and standard deviation of Belgian men.
Comment: @Amir: I'm having trouble following this. It makes it seem that if the average man is $50$ years old, the probability of a difference of $12\,222$ drops off by a factor of about $20$? I must be misunderstanding this somehow; that seems wildly off.
Comment: @NuclearHoagie nice point! Could you suggest a more reasonable distribution for lifespan?
Comment: With respect to completeness, this approach receives full marks thanks. I honestly did not consider that unfortunate case. Also, they will hear it from me only on that day so being alive is required. The converging answers suggest that approximately 1650 Belgians already share this special case^^.
Somebody on Quora was creative enough to exploit the ambiguity of my question: https://www.quora.com/What-is-the-probability-of-your-dad-being-12222-days-older-than-you-On-2024-05-03-my-brother-is-10-000-days-of-age-and-my-dad-22-222-days/answer/Jayanta-Mukherjee-49?__nsrc__=4&__snid3__=65393478558
Comment: @BrianTung You may note that for the average 50 years, it is not surprising because the probability of being alive after 22222 days (60 years) is 0.05251.
Comment: @NuclearHoagie regarding to your comment, you may check the update.
Comment: Oh, you mean if the *lifespan* is $50$ years on average? OK. I would use "lifespan" instead of "age" for $\mu_1, \sigma_1$.
Comment: @BrianTung I made some improvements. You may check.
Comment: @PieterDepamelaere If you think this answer is more complete, I suggest that you accept it, not for me, because it will help future readers understand the details better. To calculate the probability of the event, an important part of it cannot be ignored (both father and brother survive).
Comment: @PieterDepamelaere Also, to calculate the probability, you must **fix the time at which you calculate the probability**.
Comment: @PieterDepamelaere 1) This event is uncertain (wait-and-see) if the time of calculation is **before the birth of your brother** (so you need to take into account the survival of both too), otherwise, 2) at the time instant you will tell them (at the specific date) and after that, it is **certain** (here-and-now) and its probability of occurrence is 1. 3) Note at any time instant after the birth of your brother and before the upcoming date, the event is still uncertain and the probability is only equal to the probability of both survive until the specific date in the remaining days.
Comment: I just added more details on time of calculating the probability. I need to remark that assuming the lifespan has a normal distribution ( which is not accurate), and that the life expectancy in Belgium is larger than 80 years old, $k\approx 1$, and you can use 1 in 7000 (under normality assumption of lifespan distribution), see the part on normal distribution.


How to run a Service in an android wear forever

Question: I am trying to create a service(in smart watch) which should run forever even if the user is not using the app. Main purpose is to use the service for Speech Recognition. So whenever user say a specific word the app should be able to respond just like google voice.
However, for test purpose, I am printing an integer in the Log, but it only executed once. that means the service is not running forever.
My service code:
public class VoiceService extends Service {

private IBinder mBinder = new VoiceBinder();
int i = 1;
public VoiceService() {
}

@Override
public void onCreate() {
    super.onCreate();
    updateLog();
}

public void updateLog() {
    ++i;
    Log.v("DATA", Integer.toString(i));
}
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    return mBinder;
}

//inner helper class
public class VoiceBinder extends Binder {

    //constructor
    VoiceService getService() {
        return VoiceService.this;
    }
}
}

My MainActivity Code:
serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            VoiceService.VoiceBinder binder = (VoiceService.VoiceBinder) iBinder;
            iBinder = (IBinder) binder.getService();
            MainActivity.this.voiceService = ((VoiceService.VoiceBinder)iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            voiceService = null;
        }
    };

    //bind service
    bindService(new Intent(this, VoiceService.class), serviceConnection, getApplicationContext().BIND_AUTO_CREATE);
    startService(new Intent(this, VoiceService.class));

AndroidManifest:
<service
        android:name=".VoiceService"
        android:enabled="true"
        android:exported="false">

    </service>

My output:
12-20 22:27:20.307 23624-23624/? V/DATA: 2

Comment: what makes you think it would run more than once?
Comment: If it's a service which runs some code in the background forever, then shouldn't this code be executed?
Comment: which part of the service do you think runs forever? Surely not onCreate, which is only called when the service is first created
Comment: Its same on onStartCommand as well. So I am not sure about any other method which runs forever.
Comment: Well, neither of them run forever
Comment: then what does run forever?
Answer: You might want to go through Running in a Background Service wherein it mentions that

Long-running foreground operations can cause problems and interfere with the responsiveness of your user interface, which annoys your users and can even cause system errors. To avoid this, the Android framework offers several classes that help you off-load operations onto a separate thread that runs in the background. The most useful of these is IntentService.

And, also note that:

If your app targets Android 5.0 (API level 21), you should use JobScheduler to execute background services.

For best application's performance and minimize draining of battery, you may want to also check the following links:

Best Practices for Background Jobs
Adding Voice Capabilities
Create a background service in android wear
Comment: thanks for the reply. I will do that. Currently I a getting error. I have somehow managed to execute my code continuously via CountDownTimer, but after a certain period, garbage collector frees the memory and my main task does not execute though the CountDownTimer keeps on Executing the method.


Como colocar uma variável no meio da rota no angular

Question: Olá, estou desenvolvendo um front-end que irá se conectar com varias API's iguais, porem com bancos distintos( O Cliente tem a API instalada, mas esse front é para acesso dos colaboradores, e por questão de diminuição de manutenção atualizando em todos clientes vamos hospedar o front em um único local e fazer o controle de onde acessar), porem para saber qual API acessar gostaria de fazer ele pegar pela rota, mas como a ideia é hospedar em uma única URL gostaria de colocar o nome da empresa responsável pela API que vou acessar. Por Exemplo

www.minhaempresa.com/{VariavelComNomeDoCliente}/{rotas normais do angular}

ai com a VariavelComNomeDoCliente faria um controle de URL para encontrar a API certa.
Answer: Você poderia definir uma variável global por exemplo quem sabe na app.js
var enderecos = {
    cliente1: 'www.minhaempresa.com/nomeCLiente1/',
    cliente2: 'www.minhaempresa.com/nomeCLiente2/',
}

ai na hora de chamar poderia fazer
enderecos.cliente1 + 'rota-normal'


Exiting JFrame when JButton is clicked

Question: I am writing a Login GUI and want the cancel button to close the entire program when clicked. I'm a freshman computer science major and still semi-new to java and programming in general. Here is my code:
Main Class:
public class loginGui
{
    public static void main(String[] args)
    {
        lGui gui = new lGui();
        lGui.gui();
    }
}

GUI class:
public class lGui
{
    public static void gui()
    {
        JFrame frame;
        JTextField field;
        JLabel l;
        JPasswordField p;
        JButton login, cancel;
        JCheckBox check;

        frame = new JFrame("Login");
        frame.setSize(300, 150);
        frame.getContentPane().setBackground(Color.LIGHT_GRAY);
        frame.setLocation(300, 200);
        frame.setLayout(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        l = new JLabel("Username: ");
        l.setLocation(15, 14);
        l.setSize(l.getPreferredSize());
        frame.add(l);

        field = new JTextField("Username");
        field.setColumns(15);
        field.setSize(field.getPreferredSize());
        field.setBackground(Color.DARK_GRAY);
        field.setForeground(Color.LIGHT_GRAY);
        field.setLocation(90, 10);
        field.setToolTipText("Enter User Name");
        frame.add(field);

        l = new JLabel("Password: ");
        l.setLocation(15, 54);
        l.setSize(l.getPreferredSize());
        frame.add(l);

        p = new JPasswordField("Password");
        p.setColumns(15);
        p.setSize(p.getPreferredSize());
        p.setBackground(Color.DARK_GRAY);
        p.setForeground(Color.LIGHT_GRAY);
        p.setLocation(90, 50);
        p.setToolTipText("Enter Password");
        frame.add(p);

        login = new JButton("Login");
        login.setSize(login.getPreferredSize());
        login.setLocation(195, 78);
        login.setToolTipText("Login");
        frame.add(login);
        login.addActionListener(new loginAction());

        cancel = new JButton("Cancel");
        cancel.setSize(cancel.getPreferredSize());
        cancel.setLocation(95, 78);
        cancel.setToolTipText("Cancel");
        frame.add(cancel);
        cancel.addActionListener(new cancelAction());

        check = new JCheckBox("Remember me?");
        check.setSize(check.getPreferredSize());
        check.setLocation(120, 100);
        check.setToolTipText("Remember your username for next time");
        frame.add(check);

        frame.setVisible(true);
    }

    static class cancelAction implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            frame.dispose();
        }
    }

    static class loginAction implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {

        }
    }
}

I keep getting a "cannot find symbol" error here in the cancel button ActionListener:
frame.dispose();

Answer: frame only has context from within your static method gui. Start by getting rid of the static declaration and make frame an instance field of the class
public class lGui
{
    private JFrame frame;
    private JTextField field;
    private JLabel l;
    private JPasswordField p;
    private JButton login, cancel;
    private JCheckBox check;

    public void gui()
    {
        //...

You also won't need the static declarations on the inner classes...
protected class cancelAction implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        frame.dispose();
    }
}

protected class loginAction implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {

    }
}

You might find it easier to make initialise the UI from within the classes constructor instead of the gui method, leaving it to show the window
You should also avoid using null layouts, pixel perfect layouts are an illusion within modern ui design.  There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Instead, have a look at Laying Out Components Within a Container for some more ideas
Answer: The code in gui method has to be in a constructor and your JFrame object has to be defined outside of any methods, as a field of the class :)

Exiting JFrame when JButton is clicked