Por que cada browser interpreta/formata um HTML mal formatado diferentemente dos demais?

Question: Essa semana me deparei com um bug em um sistema. Esse sistema foi desenvolvido em Asp Web Forms e em determinada página tem um input que está como hidden.
Ao realizar um Post percebi que no Chrome e no Firefox o valor desse input não estava sendo enviado na request e no IE o mesmo era enviado.
Analisando o código, percebi algo de estranho nesse input, a tag do mesmo não estava sendo fechada, ficando então dessa forma:
<input type="hidden" name="id" value="<% response.Write(vID) %>"

Vejam que falta um >. Em cada navegador que testei, IE, Chrome e Firefox, o HTML gerado fica diferente dos demais.
Chrome:

Firefox:

IE:
Comment: Porque eles são diferentes :P Não sei se consigo responder melhor que isto :) De qualquer forma o que é mal formatado só é interpretado por liberalidade, se está errado, não confie naquilo.
Comment: Na verdade, são resultados equivalentes. O único detalhe é que o Chrome não segue à risca as recomendações W3C/WHATWG neste caso, que definem que os atributos booleanos devem conter ou uma *string* vazia ou uma *string* com o valor desejado. Estou comentando por estar sem tempo agora. Quem sabe após o almoço em converta em resposta, caso ninguém responda antes.
Answer: Cada navegador tem sua engine, que interpreta o HTML, Javascript, Css. O ruim disto (ou não) é que cada navegador vai / pode apresentar o seu site de uma forma distinta. Este erro que comentou ainda não é tão gritante como questões de alinhamento que as vezes nos fazem arrancar os cabelos. Principalmente no IE(O diferentão...)
Dá uma pesquisada nos engines dos navegadores, verá que há muitas diferenças entre eles e que isso é inclusive uma grande preocupação em sistemas que devem rodar com características cross-browser...


Comparison of two logistic regression models (significant result with anova() but very similar AUCs)

Question: I have compared two logistic regression models using the function anova(mod1,mod2,test="Chisq") in R. The result that I obtained is the following:
Model 1: Status ~ Added.genes.var
Model 2: Status ~ Added.genes.var + mult_genes
Resid. Df Resid. Dev Df Deviance  Pr(>Chi)
1       887     1218.0
2       886     1184.2  1   33.805 6.093e-09 ***

As far as I understand, this means that adding the 'mult_genes' predictor variable to the model, significantly improves its fit.
For this reason, when checking the area under the curve (AUC) with the function auc() of the package pROC, I was expecting to see a significant difference in that as well, but I obtained, for model 1 and 2 respectively:
Area under the curve: 0.6147
Area under the curve: 0.6158

I believe 0.61 is quite low as AUC...does this mean that both models perform poorly? And how is it possible to get such a significant result when comparing models with anova(), and so similar AUCs at the same time?
Thanks a lot!
Answer: "Significant" in the context of your hypothesis test means that if the coefficient for mult_genes were really zero (i.e. mult_genes had no effect on Status) the chances of estimating that coefficient to be as big or bigger than the estimate you made are small. That's not the same as saying it makes a big difference to the predictions over its range in your sample, given that you've included Added.genes.var. So there's no contradiction between its being "significant" & only making a small difference to the AUC.
As to the AUC's being poor or otherwise, that depends entirely on what you intend to do with the model. For some applications it might be fine; for others, hopeless: have you got a better model up your sleeve, do other people have better models, could you reasonably expect to get a better model?
Comment: It does indicate that: just don't confuse "significantly improved" with "greatly improved". Someone here suggested "discernible" would have been a better choice than "significant" as a statistical term: so think "the fit of Model 2 is discernibly improved with respect to Model 1".
Comment: Thank you for your answer! So, doesn't the p-value of 6.093e-9 with a reduced residual deviance for model 2 indicate that its fit is significantly improved with respect to model 1? If not, which parameters should I check to see if 'mult_genes' significantly improves my model? Please tell me if I am missing something...


Show that $\Omega(0)=I$

Question: For each $r\geq0$, let $\Omega(r):C((-\infty,0])\rightarrow C((-\infty,0])$ be a map defined by $\Omega(r)(x(t))=x(t-r)$ for $t\leq0$. How can I prove that $\Omega (0)=I\ $?
My attempt: If $r=0 \Rightarrow\Omega(0)(x(t))=x(t)$. I could note that $\Omega^n(0)(x(t))=\Omega(0)(\Omega(0)\circ...\circ\Omega(0)(x(t)))=...=\Omega(0)\left ( \Omega(0)(x(t)) \right )=\Omega(0)(x(t))=x(t)$, ie $\Omega^n(0)(x(t))=x(t),\ n\in \mathbb{N}$. Is that correct? Can someone help me to continue please?
Answer: No, I'm sorry but your proof is nonsense.
The chief problem here is that you have misplaced parentheses.  $\Omega(r)$ has the following action on each $x$:
$$(\Omega(r)x)(t)=x(t-r)$$
It is an $r$-shift operator.  If $r=0$, the shift is null.  In symbols:
$$(\Omega(0)x)(t)=x(t-0)=x(t)$$
In other words, $\Omega(0)x$ is just $x$ itself.
There is not much here to prove.
Comment: No. The expression "$\Omega(r)(t)\cdot x(t)$" is itself nonsense.  Each $\Omega(r)$ is an operator. Call it $T$. and each $T$ sends a function $x$ to a different function $y$.  The function $y$ is defined by $y(t)=x(t-r)$.  Since $Tx=y$, we have $(Tx)(t)=x(t-r)$. And since $T=\Omega(r)$, we have $(\Omega(r)x)(t)=x(t-r)$.

Show that $\Omega(0)=I$


Finding conditional expectation: $\mathrm{E}(aX + b | cX + d < eY + g)$

Question: I'm trying to obtain a formula for the following object, without imposing any distributional assumptions:
$$
E(aX + b | cX + d < eY + g)
$$
Obviously by linearity of $E$, $\ aE(X| \frac{eY + g - b}{a}) + b$, given c > 0.
I've derived this, is it correct?:
$$
= a\int^\infty_{-\infty} \int^\infty_\frac{eY + g - b}{a} X \frac{f_{x,y}}{f_y}dx dy + b
$$
If so, why have I found the following similar formula elsewhere - is this when the two variables $X, Y$ are independent?
$$
a\frac{1}{P(cX + d < eY + g)} \int^\infty_\frac{eY + g - b}{a} X f(x) dx + b
$$
Comment: Make an affine transformation of the variables.  In particular, let the first variable be $cX - eY + d-g.$
Comment: Why not simplify your question first?  A little algebra will readily reduce it to $E(\alpha X + \beta Y + \gamma \mid X \lt 0),$ thereby eliminating half of the unknown parameters and hugely simplifying the calculations.  But since you impose no distributional assumptions, the main question is too general to be answerable.  BTW, all your formulas do make some distributional assumptions: in particular, you appear to assume $(X,Y)$ has a density.
Comment: Thanks for the response! I'm happy to assume X and Y jointly distributed by some f(x,y). Am I missing something simple, how can I transform it to the form E( | X<0) you mentioned?
Answer: Provided $e^2+c^2\ne 0,$ the event $cX + d \lt eY + g$ defines a half plane.  (When $e^2+c^2=0,$ this event is either empty or universal, giving trivial answers.)
This suggests we can simplify the problem with a change of coordinates.  To this end, define a new random variable
$$U = cX + (-e)Y + (d-g)$$
so that the conditioning event is $U \lt 0.$
The expectation is a linear function of $X,$ which now needs to be expressed in terms of $U$ and another variable.  A nice choice (among many) would be a variable orthogonal to $U,$ such as
$$V = eX + cY.$$
We may solve for $aX+b$ in terms of $U$ and $V,$ giving
$$aX + b = \frac{a}{c^2+e^2}\left(c(U + g-d) + eV\right)+b = \alpha U + \beta V + \gamma$$
where
$$\alpha = \frac{ac}{c^2+e^2},\quad \beta = \frac{ae}{c^2+e^2},\quad \gamma = \frac{a(g-d)}{c^2+e^2}+b.$$
As a result, the conditional expectation has been re-expressed as

$$\eqalign{ E(aX + b\mid cX + d \lt eY + g) &= E(\alpha U + \beta V +
\gamma \mid U \lt 0) \\ &= \alpha E(U\mid U \lt 0) + \beta E(V \mid U\lt 0) + \gamma }$$

This is as far as one can go towards simplification in general, but the following remarks may be of some use.

To find these expectations you might need to find the joint distribution of $(U,V).$  When $(X,Y)$ has a density $f_{X,Y},$ $(U,V)$ will also have a density and can be expressed in terms  of $f_{X,Y}$ and the Jacobian of the transformation, equal to $c^2+e^2.$
The only bivariate calculation is the second term, $E(V\mid U \lt 0).$  In terms of $f_{U,V}$ that's a relatively simple integral conceptually (assuming $\Pr(U\lt 0)\ne 0$), given by $$E(V\mid U \lt 0) = \frac{1}{\Pr(U \lt 0)}\int_{-\infty}^0\left(\int_{-\infty}^{\infty} v\,f_{U,V}(u,v)\,\mathrm{d}v\right)\mathrm{d}u.$$  This is recognizable as an integration of conditional expectations over all negative $u$--and that can be convenient, because often regression methods provide explicit formulas for conditional expectations.  (E.g., in the bivariate Normal case the conditional expectation is a linear function of $u.$)
Answer: Use $E(Z|A)=\frac{E(Z1_A)}{P(A)}$
#Conditional_expectation_with_respect_to_an_event
So without any assumption about distribution of $(X,Y)$,By defining $A=\{ cX + d < eY + g\}$  we have
$$E(aX + b | cX + d < eY + g)=E(aX + b | A)=a E(X  | A)+b=a\frac{E(X 1_A)}{P(A)} +b=a\frac{E(X 1_A)}{P(cX + d < eY + g)} +b$$
$$a\frac{\int_{\{\omega \in \Omega\mid cX(\omega) + d < eY(\omega) + g \}}X \, dP}{P(cX + d < eY + g)} +b$$


Editing Python's buit-in datetime module (just to to test how editing of built-in modules works). But it still behaves like it never changed

Question: Tried this on both Ubuntu and Windows
Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:34:34) [MSC v.1928 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.__file__
'C:\\Program Files\\python3810\\lib\\datetime.py'

Then edited the file. Just for a test replaced a return line from isoformat method of a class date
class date:
...
    def isoformat(self):
        """Return the date formatted according to ISO.

        This is 'YYYY-MM-DD'.

        References:
        - http://www.w3.org/TR/NOTE-datetime
        - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
        """
        # return "%04d-%02d-%02d" % (self._year, self._month, self._day)
        return "%04d-%02d" % (self._year, self._month)

    __str__ = isoformat

Reloaded the Python shell, but the return of str is the same.
Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:34:34) [MSC v.1928 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> d = datetime.date.today()
>>> d
datetime.date(2023, 11, 16)
>>> d.__str__()
'2023-11-16'

So, is this even supposed to work like this, or something else have to be done?
Comment: There was a comment to a now deleted answer, it's basically answers my question. I don't remember the exact username, but if you will read this, you can post your answer and I will accept.
Comment: I just didn't know that this module written in Python being used just as a backup and there is a main _datetime written in C. So I removed the  `from _datetime import *` and it works as I was expecting. But, I've already put it back, since all of this just to understand how thing work with a modules written in Python.
Comment: This works perfectly for system wide python installation. Bit it breaks things for my Django environment. It crashes with `SystemError: initialization of _psycopg raised unreported exception` But no point investigating this, since I got the answer I wanted. The only I will try look into more is from where datetime importing _datetime written in C. Where it's located in Python installation.
Answer: You are on the wrong track.
Try to use inheritance from datetime module objects, although it is not entirely trivial.
import datetime

class MyDate(datetime.date):
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, *args, **kwargs)
    def isoformat(self):
        return "%04d-%02d" % (self.year, self.month)
    __str__ = isoformat

if __name__ == '__main__':
    date = MyDate(1,2,3)
    print(date)


How to increment the C++list's Iterator inside a for loop to iterate over specific pattern say for example each second element?

Question: Usually in C++ one can iterate over each second element by doing so:
for (int i = 0; i < 10; i = i + 2 ){
       //do Somthing
}

and for a C++ list (from library list) one can iterate over each element like so:
std::list<int> dY = {5,4,5,8,9,7,10,4};
std::list<int>::iterator iterdY;
for (iterdY = dY.begin(); iterdY != dY.end(); iterdY++) {
        // do Something
    }

Now my question is what should I write instead of iterdY++ to iterate over each second element ??
Comment: Could you not just use a regular `for` loop, without the iterators? (Defeats the point of the question, but might be helpful)
Comment: @cs1349459 No raw for loops!  https://youtu.be/f_tLQl0wLUM?t=583
Comment: Does this answer your question? [How to increment an iterator by 2?](https://stackoverflow.com/questions/1057529/how-to-increment-an-iterator-by-2)  Just be careful about containers that have an odd number of elements.  It's up to you to prevent incrementing your iterator past the end.
Answer: Probably the easiest way is to introduce a second iteration variable.
std::list<int> dY;
int n = 0;
std::list<int>::iterator iterdY = {5,4,5,8,9,7,10,4};
for (iterdY = dY.begin(); iterdY != dY.end(); iterdY++, ++n) {
    if ((n % 2) == 0) {
        // do Something
    }
}

Comment: I would have defined `n` as an `unsigned` instead. :)
Answer: std::advance(iterdY, 2)
But you can no longer use the comparison iterdY != dY.end() because if the list has an odd number of elements you will skip over the end iterator, and into the territory of undefined behavior.
You must make sure that the list have an even number of elements first, if using iterators, or use some other way to keep track of the iterator not passing beyond the end.

If your compiler supports C++23 you can use ranges and stride_view to skip over every second element in the container.
See example here (using the earlier Ranges v3 library, which is the base for the C++20 standard library ranges).
Using the original ranges v3 library with earlier C++ standards is possible as well.
Answer: For starters I think you mean a list in this declaration
std::list<int>::iterator iterdY = {5,4,5,8,9,7,10,4};

like
std::list<int> dY = {5,4,5,8,9,7,10,4};

instead of the iterator.
You can do something like the following
for ( auto it = dY.begin(); it != dY.end(); ++it == dY.end() ? it : ++it ) {
//...

Here is a demonstration program.
#include <iostream>
#include <list>

int main()
{
    std::list<int>dY = {5,4,5,8,9,7,10,4};

    for ( auto it = dY.begin(); it != dY.end(); ++it == dY.end() ? it : ++it )
    {
        std::cout << *it << ' ';
    }
    std::cout << '\n';
}

The program output is
5 5 9 10

Answer: I'd use two steps and a function:
auto iterdY = dY.begin();
while (iterDy != dy.end()) {
    do_something(*iterDy++);
    if (iterDy == dY.end())
        break;
    do_something(*iterDy++);
}

Answer: After understanding all of suggested answers I would like to propose this solution:
#include <iostream>
#include <string>
#include <list>
using namespace std;

int main()
{
    std::list<int> dY = {5,4,5,8,9,10,11};
    std::list<int>::iterator it = dY.begin();
    int step = 3; // Here one can change the step to print each third element
    for (int i = 0 ; i < dY.size() ; i+= step )
    {
        std::cout << *it <<'\n';
        std::advance(it, step);
    }
    std::cout << '\n';
}

output is:
5 8 11


Override path with Views

Question: How can I override the default display of a taxonomy term with a view ?
eg : the path of a taxonomy term taxonomy/artist/artist_name take me to the default display of a taxonomy term and I want to display a specified view to the same path.
in resume override the path.
thanks !
Answer: Make the page display path taxonomy/term/% and the first argument to the view should be the term ID. There is a disabled view for this purpose which should set these up for you, but if you already have a view you can also make that override the core taxonomy path by making the two adjustments I mentioned.
Comment: I changed the path of the taxonomy term from "taxonomy/term/%" to "taxonomy/artist/%" in the disabled view that i of course enabled. In the view all it's ok but when i go to the specified path in my browser it's display the default display and not my view.
Comment: I think you're confusing the path alias of your taxonomy terms with the actual system path that you want to over-ride.  Have you setup any path aliases for the terms/vocabulary?
Answer: When you changed the path of the taxonomy term  as you state in your comment on George's answer, I assume you mean that you defined an alias using the Pathauto module.  The problem with this is that Drupal reads the alias and converts it to taxonomy/term/% before it acts upon the URL.  This means that your view is never called and the the default taxonomy view is used to display the content.
There are two ways to get to your view.  The first is to use the default taxonomy view that George mentioned.  The second is to remove the taxonomy alias in path auto so that no conversion is made to the path. Drupal will then direct its response to your View with that path name.
Also, it is not necessary to convert the path argument to to a term number for use in the contextual filter.  You can also  use the name.  Set the configuration of the contextual filter to content:term id.  Under the settings for "When the term is in the URL..." select the validation option and pick the validator "taxonomy term" and the vocabulary that applies. Then pick "term name converted to term ID" from the filter drop down box.  You  must also check "transform spaces..." if your URL can have multiple words for the term so that dashes and spaces are interpreted correctly together.

Override path with Views


Read integers from text file and store them into an array

Question: I am pretty much new to C++ and got this assignment from school to do and now I am stuck as I can't get it to work, some help would be appreciated. Thanks in advance.
I have a text file with integers like this:  8 3 7 1 2 0
I need to create program which reads those integers and stores them in an array. Program checks text file and counts how many integers are there and accordingly creates array of size that is needed then it fills that array with integers from the file. I've came up with something like this:
#include <iostream>
#include <fstream>
using namespace std;

int main(){

    ifstream File("data.txt");
    int count;
    File >> count;
    int array[count];
    for(int i=0; i<count; i++){
        File >> array[i];
    }

    cout<<"File contains: "<<count<<" integers";
    cout<<"Array of integers taken from the file: ";

    for(int i=0; i<count; i++){
        cout<<array[i];
    }
}

For some reasons my count integer doesn't get any value, I've checked and it's just a zero after program and thus my whole code won't work.
Comment: Use `File.is_open()` to see if you open the file successfully.
Comment: Try checking to see if each I/O operation (opening, each read operation) actually succeeds.   Also `int array[count]`, with `count` a variable is not valid C++ (if your compiler accepts it, it is as a compiler-specific extension).   Also, from the sample you describe, the file does not contain the number of subsequent integers to be read.
Comment: It would be helpful to know if the rest of the read operations do succeed.
Answer: Variable lenght array does't exist un c++.
Use a vector<int> to store the data.
Btw, you can use:
System("pwd");//linux

To check working path.
Answer:
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() or std::numeric_limits<T>::min() is written and failbit flag is set.

This comes from the documentation of operator>> of std::ifstream. As you can see, if extraction fails, then the variable is set to 0. Why did extraction fail? Well, you never check if the file is open or not, so it is possible that the file doesn't exist and loading it failed.
But even if your file is loaded correctly, it doesn't seem to me that the first element in the file is the amount of integers in it. If it is not, you will have to read each integer, and store them in a dynamic array, as you do not know the size (like std::vector.)
Comment: Oh, so it's like that then, I have to use vectors for this, shame that I haven't studied them yet...


How normal distribution and normal approximation are related?

Question: The formula for normal distribution.
$f(x) = \frac{e^\frac{-(x-u)^2}{2q^2}}{q\sqrt{2*\pi}}$
where $u$ is the expected value, $q$ is the standard deviation.
Normal approximation defines $u=n*p$ and $q^2 = n*p*(1-p)$
Please consider coin flipping example. For this $p=1/2$, $u=n/2$, $q^2=n*1/2*(1-1/2)=n/4$
Putting $u$ and $q$ to the formula of normal distribution we should have $f(x) = \frac{e^\frac{-2(x-n/2)^2}{n}}{\sqrt{\pi*n/2}}$
I want to double check my understanding because in R. Sedgewick's "Algorithms in C 3rd edition" on page 86 given resulted formula as $f(x) =  \frac{e^\frac{-(x-n/2)^2}{n}}{\sqrt{\pi*n/2}}$ (i.e. it missed 2 in the nominator of power of $e$).
Comment: $e^{-(x-n/2)^2/n}$ is definitely wrong for fair coin flips, since that implies twice the variance is $n$, but twice the variance is definitely $n/2$. One possible way this error could come about is if there was a Poisson approximation in the middle, but the Poisson approximation is not suitable for fair coin flips anyway.
Answer: Your answer looks good to me. The factor in the exponent is $1/(2q^2)$, whilst that in the denominator, under the square-root, is $2 q^2$---one is the reciprocal of the other. This is the case in the answer you give: your exponent-factor is $2$ and your denominator-factor is $1/2$. The answer you cite in the book(?) does not satisfy this: one is $1$ and the other $1/2$.
This doesn't mean that your answer is necessarily right---although, it is! Rather, I am explaining how the book's answer is necessarily wrong.
It is always a good idea to have little sanity checks like this in mind. They are good ways for spotting mistakes and can save a lot of hassle! I emphasise, though, that they do not guarantee correctness: if you replace your $2$s with $15$s, then the sanity check still holds; but the answer would be wrong.


Digital Logic 3 Light Switch In A Room Question

Question: There are three doors in a room with a light switch next to each one. You can turn on the light from any door when you enter, and you can turn-off the light from any door when you leave.
a) Write the truth table for the function
b) Use the Karnaugh map to see if it can be simplified
c) Draw logic circuit for the function
d) Check if it is possible to realize function with a single logic gate
Especially d is the hardest one for me to solve. Can you help me?
If you wanna see the picture of question, click here.
Comment: Could you tell us what you have tried so far? Did you get through parts a,b,c?
Comment: Also, what exactly is the "function" that is supposed to represent this function? Presumably, the output of any function in this context should be "true" or "false"; perhaps this should refer to whether the light is on or off. However, what are the *inputs* to this function?
Answer: Labelling the switches by each door as $A$, $B$, and $C$, and using digital electronics notation,

Logical OR is represented with a $+$,
AND is represented with multiplication. $A$ AND $B$ is $AB$,
Negation is represented with an overline. Not $A$ is $\overline{A}$,
"Exclusive or" (XOR) is represented as $\oplus$,

a Karnaugh map would look something like:
\begin{array}{c|cccc}
&\overline{A}\overline{B}&\overline{A}B&AB&A\overline{B}\\ \hline
\overline{C}&0&1&0&1\\
C&1&0&1&0
\end{array}
Unfortunately this doesn't simplify on the Karnaugh map in an obvious way. It can be simplified using the laws of Boolean algebra though.
\begin{align}
\overline{A}B\overline{C}+ABC+\overline{A}\overline{B}C+A\overline{B}\overline{C}\\
A(BC+\overline{B}\overline{C})+\overline{A}(B\overline{C}+\overline{B}C)\\
A(\overline{B\oplus C})+\overline{A}(B\oplus C)\\
A\oplus(B\oplus C)\\
\end{align}
Although it may look like you can't implement a single logic gate to realise function, since it is an application question, you could just recommend the 3-input XOR gate bellow:

XOR logic gates with more than 2 inputs are sometimes called "odd functions" or "modulo-2 sum functions", since they return TRUE whenever an odd number of their inputs are true, precisely the requirements for a light to turn on in your question.


How many beats are in 6/8 time?

Question: In 6/8 time, each measure contains six eighth notes. We are often told that therefore there are six beats in 6/8 time.
But when my band plays a piece in 6/8, the conductor counts in two. Also, the tempo is often denoted with a dotted quarter note next to it; and I once read an SE post (I don't remember where) claiming that 6/8 time does not mean six eighth notes, but rather two dotted quarters.
So are there really only two beats, or are there six?
Answer: There are two basic types of meter: simple meter, which divides beats naturally into two parts, and compound meter, which divides beats naturally into three parts.
Time signatures where the top number is a multiple of three, like 6/8, 9/8, 12/8, etc. are usually compound meter.  The bottom number in a compound signature indicates the division of the beat.
If you write measures of 2/4 using all eighth note triplets you'll get the same rhythm as if you wrote measures of 6/8 using all eighth notes.  Using a compound meter eliminates the need to write "3" over all the beams.
As far as conducting and counting goes, if it's fast it's done in two, and if it's slow it can be done in six.
Answer: "We are often told that therefore there are six beats in 6/8 time."  Really?  By who?  Not someone who's got through an elementary music theory class.
The standard answer is 'two'.  Most of the time when you see 6/8, the conductor will beat two in the bar.
4/4 has 4 beats.  But sometimes, in a slow piece, the conductor may decide to beat it 'in 8'.    In the same way, a slow 6/8 may be taken 'in 6'.  But that  basic 2 count will still be there.
Don't get sidetracked by 'America'.  It shifts between 6/8 and 3/4.   Modern music does this sort of thing a lot.  A piece notated in 6/8 may constantly shift between 3+3 groupings and 2+2+2 groupings, beween 6/8 and 3/4.  We don't always bother to keep changing key signatures.
'America' is often notated as 6/8 in a song copy.  In the original score it was given as 6/8(3/4).  (And no, none of us have encountered "Seis" anywhere else either!   If you're interested, start at paragraph 32 of this:
http://www.echo.ucla.edu/Volume2-Issue1/wells/wells.pdf)
Answer: There are two beats of dotted crotchets in 6/8 time, 6/8 is compound duple time with dotted crotchet beats.
Answer: TL;DR: 6/8 implies a measure of 6 eighth notes, by default grouped into two groups of three.  How many "beats" you feel or how you count it can vary.  To those of you who teach music: I don't really care how many "beats" you say are in 6/8, but please teach students the groupings of the eighth notes, not just "6 beats per bar."  Otherwise, students won't feel the meter correctly, and it will lead to lots of confusion later.

The details...
A lot of questions appear on the nature of 6/8 in this forum.  Specifically, this question of "2 beats" vs. "6 beats" seems to cause a lot of arguments and consternation among beginning music students.
And for good reason.  Different teachers often have different opinions.  I've seen lots of practical method textbooks written for instruments that introduce 6/8 as "6 beats per measure, where the eighth note gets the beat," whereas the majority of music theory textbooks introduce 6/8 as "compound duple time," implying a two-fold division with the word "duple."  The first group generally starts yelling about how the 6 is obviously in the time signature, while the latter group shout back about the history of time signatures with 6, 9, and 12, and how they obviously indicate "compound" meters.
I have to admit, as someone who leans toward the latter view, that I sometimes cringe when I see 6/8 introduced in textbooks with the "6 beats" definition, as it's generally an unhelpful way to view the meter 95% of the time.  And it doesn't get at the two-fold division implied by the 6/8 meter, which emphasizes the first and fourth eighth notes of the bar (even at slower tempos).  But, there are times (maybe <5% of the time) when "6 beats" makes sense as a description.  So, that view isn't "wrong" either.
It all has to do with the definition of a "beat."  Which I'll come back to momentarily.  But first, let's discuss why the answer to this question is ambiguous in the first place.

Let's start with something more basic.  How about 4/4?  How many "beats" are in a 4/4 bar?  Most people will say "obviously" four.  But the metric organization of a 4/4 bar is more complicated than that.  In particular, there are stress accents implied: the strongest on the first beat, a secondary/medium stress on the third beat, and weaker beats on 2 and 4.  Overall, a bar of 4/4 has a pattern of Strong-Weak-Medium-Weak stresses.  From one perspective, there are 4 primary components here.  But if we choose to focus on the more "stressed" beats, we might focus only on beats 1 and 3 (and in fast tempos, sometimes we might tap our feet or clap with only every other "beat" like that), i.e., two "beats" per bar.  Or, in another sense, we could choose to feel only the strongest stresses, feeling that "downbeat" like the conductor's hand coming down only once per bar.  These are all ways to "feel" the meter.  We could even emphasize lesser levels of stress, particularly at a slow tempo.  We might sense 8 pulses (STRONG-and-WEAK-and-MEDIUM-and-WEAK-and...) ticking away at the eighth-note level.
What I'm describing here is metric hierarchy.  We often are taught to feel meter as a hierarchical pattern of levels of stresses, some stronger, some moderate, some weak.  Depending on which level we hear or choose to emphasize, we may sense more or less important "beats" in a notated 4/4 bar.
The same goes for 6/8.  For historical reasons, 6/8 implies stress on the first and fourth eighth notes of each bar.  (STRONG-weak-weak-MEDIUM-weak-weak...)  That's different from 3/4, which implies stress on the first, third, and fifth eighth notes.  (STRONG-weak-MEDIUM-weak-MEDIUM-weak...)  In both cases, we see groups of twos and groups of threes, just at different levels of the metric hierarchy.  At a slow tempo, you might choose to follow both 6/8 and 3/4 at the eighth-note pulse level, but you'll hear different patterns of stressed notes.

All of this is great, but you may be saying by this point: "So which is the BEAT?!"  And that's a really complicated question.  Generally, in common English when we refer to "beat," we're referencing something that music theorists often call tactus, that is, the metric level where you might tap your foot, or the place you "feel the pulse."
And that's a difficult thing to predict.  Different people may feel a different tactus for the same piece.  (This is why you sometimes will see some members of a crowd clapping twice as fast as others as they're clapping along with music.)  Psychological studies have shown that most people tend to prefer a tactus to fall in the range from about 40 beats per minute up to around 160 beats per minute, with the maximum salience of beats preferred around 100-110 bpm.  In some extreme cases, people may feel a tactus down to around 30 bpm or up to around 240 bpm.
If you're hearing a piece in 4/4 played at a tempo of quarter note = 160, what determines whether you tap your foot at 160 bpm (the quarter note "beat" level) or perhaps at 80 bpm (at the half note level, a little closer to the "most comfortable" and preferred tactus range)?  Or, to get back to our 6/8 question, why might one piece be notated and felt with a tempo of dotted-quarter = 50 bpm while another piece is notated and felt with an eighth-note = 150 bpm?  Both are arguably at the "same tempo," but the "beat" may be felt quite differently.
A lot of it is influenced by style expectations, a sense of "groove" in popular styles, etc.  It's rather difficult to predict from just looking at a piece on the page, regardless of its notated meter.  Yet crowds often naturally will gravitate toward a particular preferred "beat."
Still, in the end, whatever level we choose to tap our feet or clap our hands to, there will be levels of divisions of 2 and/or 3 at higher and lower levels of meter.  Our most common meters capture these different configurations of 2s and 3s: 6/8 has a two-fold division at a higher level and a three-fold division at a smaller metric level.  3/4 has a three-fold division at a higher level and a two-fold division at a lower level.  2/4 and 4/4 have two-fold divisions generally for at least two levels.  9/8 implies a three-fold division at two levels.
Note that the default division at each level is two-fold in modern rhythmic notation (unless triplets are written).  Historically, there could be three-fold division at even more levels, though it was rare.  (On a couple occasions, I have seen a 27/16 or 27/8 time signature, denoting a three-fold division on three consecutive levels.  But that's quite complicated to notate effectively in modern rhythmic notation, which is why we resort to triplets.)
But again, note that all of these written meters don't necessarily indicate where you should "feel the beat," i.e., where you tap your foot.  That's a matter of tempo and musical style, not the time signature.
So, to go back to the original question of 6/8 -- in something like 95% of cases, the tactus ("beat") is meant to be felt at the dotted-quarter level, with two primary "beats" per measure.  However, particularly at very slow tempos, people may tap their feet or sense that the "primary pulse" of the meter is at the eighth-note level, implying six "beats" per measure.  (In a piece in 6/8 with eighth-note = 60 bpm, very few people are going to be tapping their feet only once every 3 seconds at 20 bpm to accord with the dotted-quarter groupings.)  But even in this latter case, those beats are still grouped into two groups of three eighths.  The metric hierarchy levels are all still implied by the time signature, regardless of how you count the measure or at what level you "feel the beat."
In the end, I'd say one of the hardest things for beginning students to realize is that the score is NOT "the music."  It is a blueprint to follow, not necessarily how you "feel" it (or conduct it or tap your foot to it or interpret it or dance to it).  Modern time signatures are meant as a shorthand to show the relationships of the 2s and 3s of metric hierarchy, not necessarily as a way to tell you where to tap your foot or how many "beats" to feel per measure.  Once you realize that, it doesn't matter how many "beats" are in the 6/8 bar.  It's just a representation of specific metric level groupings... no matter which level you use to tap your foot or how the conductor swings a baton.
Answer: According to Dolmetsch, each measure contains a number of main beats—such as the three in 3/4, or the two in 6/8—which are each divided into inner beats. So a main beat in 3/4 time would contain two inner beats (assuming an eighth-note rhythm), while a main beat in 6/8 time would contain three, the eighth notes.
When a 6/8 piece is conducted in two, it's because the piece is very fast, and counting the eighths individually would be infeasible; beats 1 and 4 are the strongest, so it's usually reduced to those two.
However, some 6/8 sections can be counted in three, if your composer or conductor specifies it. 6/8 can even be counted in six, if the piece is really slow.
So whether 6/8 time contains two or six beats is a matter of context.
Comment: I've never seen 6/8 conducted in three, and I've played in 3 school concert bands and watched some orchestras on top of that. I've only ever seen 6/8 conducted in six or two.
Comment: @Dekkadeci At various times I've seen 6/8 conducted in one, two, three, six and twelve. Of course two and six are by far the most common
Comment: @Dekkadeci One of the pieces my class is playing is in 7/8 based on Afghani music, and switches between a lot of meters. A large section of it is in 6/8 and my conductor frequently switches between 2+2+2/8 and 3+3/8.
Comment: 6/8 always has 2 beats.
Comment: It must be a quirk of our piece's meter, then, because my conductor explicitly indicated that she'd count some sections in three.
Comment: @dfhwze I've never encountered that before, so I can't say for sure. There's probably a lot of variation between composers, though. As another idea, you could treat it as an asymmetrical 4+4+4+3/16.
Answer: 6/8 time is 2 dotted crotchets in a bar. The confusion where there are 6 beats, is because there are six pulses; which are the quavers.
Answer: I am firmly in the Compound Duple camp when it comes to 6/8 etc, however as a conductor and music teacher I have come across some 'modern' music where the time signature 6/8 has been taken quite literally as 6 8ths. That is normally when the time signature is varying between numbers of 8th notes in a sequence of bars such as 4/8; 5/8; 4/8; 6/8; 4/8 etc. The clarity comes first when you view how the 8th's have been grouped within the bar and second when you try out the music in different ways. In these cases the composer has chosen to stick with a time signature that emphasizes the continuity of the 8th note. A piano piece by Darius Brubeck called Tugela Rail perfectly illustrates this albeit it is 5/4; 6/4 instead of 8ths. 6/4 is also compound duple but in this case is written as if in 3/2. The sentiment remains the same.
Answer: It all depends on the tempo. If it's fairly slow then it's natural to count six beats in a measure. If the tempo is faster then two beats is much easier. If the tempo is really fast a conductor might only give one beat per bar, and if it's really slow a conductor might even subdivide the eights and conduct in twelve.
If the 6/8 measure is mixed with other time signatures it sometimes makes more sense for the conductor to give three beats. I've even seen "America" from "West Side Story" which has alternating 6/8 and 3/4 bars, conducted all the way through in three. (Not that I think that's a good idea)

How many beats are in 6/8 time?


Subversion commits not appearing in repo

Question: Good morning to all.
I am just starting with subversion and need some help.
I have setup a repo on my server for my web directory. Steps followed are:
svnadmin create /path/to/repo

Then I import the project with:
svn import /my/webserver/dire file:///path/to/repo

and start the server with
svnserve -d

Everything works fine and I can download the repo from my client with:
svn co svn+ssh ://user@server:/path/to/repo

Now on my client I edit foo.html and add a file called test. I add the file to svn with
svn add test.

Finally I commit the changes with
svn commit.

The log popups up with the changes and additions, I confirm and I get the message that test is being uploaded.
The problem is that when I log into the server and check /path/to/repo I do not find the new test file and the edited foo.html file.
Am new to subversion so I need some help. Thanks to all!
Answer: The copy at /path/to/repo is the repository itself, the structure of which only makes sense to subversion and will not directly contain the file you commit.
To have the server get copy of the contents of the repo, you will want to do a checkout on the server as well:
svn co file:///path/to/repo /path/to/checkout

Then once changes are made by a client to the repo, you can bring the checked out copy up to current with..
svn up /path/to/checkout

Comment: @FabrizioMazzoni You'll always need to run `svn update` (`up` for short) on a checked out copy in order for it to get the latest changes that have been committed - you can set up a cron for this if you'd like it to always be up to date.
Comment: Thanks. So basically the original source will never change and `/path/to/checkout` will always be the latest version once i decide to commit any changes done by me or others?


What is the formula for add/removing compound and non-compound tax from a value?

Question: I had posted this question on stack overflow because I am trying to implement a method that will loop through a set of percentages and add or remove them to a value based on some properties that are set.  Here is a link to the question.  I believe I have the compounding part correct. I partially have the non-compounding part, the problem is that I need to add just 1 to the very end instead of every time through the loop.  The other issue I am facing is how do I mix compounding and non-compounding in the formula.  Basically, I have the following scenarios:
All percentages are compounded and removed from the total.
All percentages are non-compounded and removed from the total.
All percentages are compounded and added to the total.
All percentages are non-compounded and added to the total.
All percentages are compounded, but some are removed and some are added.
All percentages are non-compounded, but some are removed and some are added.
Some percentages are compounded and some are non-compounded, but they are all added.
Some percentages are compounded and some are non-compounded, but they are all removed.
Some percentages are compounded and some are non-compounded, and they could be removed or added.
I believe I covered everything.
Thanks for the help
Answer: What base are the non-compounded ones taken on?  For example, assume a 100 base price, a +3% and -6% compounded, a +10% and -8% non-compounded tax.  If the non-compounded taxes are on the base you just get $100\cdot1.03\cdot0.94+100\cdot0.10-100\cdot0.08=100(1.03\cdot0.94+0.10-0.08)$ for a final price or  $100(1.03\cdot0.94+0.10-0.08)-100$ for the total tax. Is this what you are after?
Comment: If I understand your answer correctly, I believe what I want to do is take the compounded tax on the new base that is calculated from the previous tax.
Comment: Yes, that is the meaning of compounded.  The total tax won't change with the order you apply them, but how much each tax is will do so.
Comment: I did your example in a calculator,  what is supposed to be the correct result.
Comment: I just made it up on the fly, but I get 98.82 for the final price, or a tax of -1.18


makedirs cannot create directory because it contains a question mark

Question: Someone created an awesome script to download videos for personal use which is permitted under their TOS. However when the script tries to create a directory based on the title name, it creates an error due to a question mark "?" in the title. Windows does not permit special characters in the directory name. Is there a way to tell makedirs to ignore special character?
Traceback (most recent call last):
  File "D:\nick.py", line 91, in <module>
    main()
  File "D:\nick.py", line 88, in main
    episode.download()
  File "D:\nick.py", line 37, in download
    os.makedirs(dirname)
  File "C:\Users\*****\AppData\Local\Programs\Python\Python38\lib\os.py", line 223, in makedirs
    mkdir(name, mode)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "The Crystal Maze\\What's The Sign For Winning?"

Comment: Hi.  Can you please show your code?  I need to know what version of python you are using, and what libraries.  Thanks
Comment: You can edit it yourself - `os.makedirs(dirname.replace('?', '_'))`
Comment: @Peter
Thanks for quick replies. I'm not a developer. So I couldn't figure which line to add this.
On line 223 I see this:
` mkdir(name, mode) `
Do I replace that line with your suggestion?
Comment: That does work however since it is working on filename and subtitle filename too see new error:
Comment: ```
Traceback (most recent call last):
  File "D:\download2.py", line 91, in
    main()
  File "D:\download2.py", line 88, in main
    episode.download()
  File "D:\download2.py", line 48, in download
    self._download_item(url, os.path.join(dirname, title))
  File "D:\download2.py", line 24, in _download_item
    with open(output + ".ttml", "w", encoding="utf-8") as file:
OSError: [Errno 22] Invalid argument: "The Crystal Maze\\What's The Sign For Winning?\\What's The Sign For Winning?   S1.ttml"
```
Comment: To see the code: https://gist.github.com/relrelb/920370c07221b4b89b8999818e7fe899
Answer: You can remove the symbols using this line:
''.join([i for i in name if i.isalnum() or i.isspace()])

You'll have to change dirname in the source code for what I wrote above:
os.makedirs(dirname) # in line 37, in download

It will save as the name, but without the symbols:
Out[58]: 'The Crystal Maze Whats The Sign For Winning'

Comment: I think that would be line 37 in a file called `download`? search for `os.makedirs(dirname)`
Comment: Yes line 37:
`
 def download(self):
  name = self.name.replace("/", " ")
  if '"' in name:
   name = name[name.index('"') + 1:name.rindex('"')]
  dirname = os.path.join(self.show.name, name)
  if not os.path.isdir(dirname):
   os.makedirs(dirname)
`

So it should look like this?

`
 def download(self):
  name = self.name.replace("/", " ")
  if '"' in name:
   name = name[name.index('"') + 1:name.rindex('"')]
  dirname = os.path.join(self.show.name, name)
  if not os.path.isdir(dirname):
   os.makedirs(''.join([i for i in name if i.isalnum() or i.isspace()]))
`
Comment: Apparently there's more to this... Since it relates to filename and subtitle filename too... Newest error:
Comment: ```
Traceback (most recent call last):
  File "D:\download2.py", line 91, in
    main()
  File "D:\download2.py", line 88, in main
    episode.download()
  File "D:\download2.py", line 48, in download
    self._download_item(url, os.path.join(dirname, title))
  File "D:\download2.py", line 24, in _download_item
    with open(output + ".ttml", "w", encoding="utf-8") as file:
OSError: [Errno 22] Invalid argument: "The Crystal Maze\\What's The Sign For Winning?\\What's The Sign For Winning?   S1.ttml"
```
Comment: To see the code: https://gist.github.com/relrelb/920370c07221b4b89b8999818e7fe899
Comment: I'm afraid you'll have to do the same for the subtitle files. I think you hvlave to replace "title" this time. But I can't help you further I'm now afk
Comment: Thank you. got it. I added replace ?  to _ in two locations (line 32 and 46). It worked. You mentioned "title" which helped me. Thank you.


Change drupalsite/user to drupalsite/customadmin

Question: Currently to login as an admin I need to navigate to the URL http://drupal.mysite.com/user and then I am logging in with userid admin.
I want to change the user part of the URL to my own custom URL containing customadmin, so that I can navigate to my login page with URL http://drupal.mysite.com/customadmin (instead of URL http://drupal.mysite.com/user).
I know there are some core file that can be changed to do this, like:
'H:\xampp\htdocs\mydrupal\modules\user\user.module'

I.e by modifying the hook menu for login like so:
/**
   * Custom menu for login
   */
  $items['customadmin'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'page callback' => 'user_page',
    'access callback' => TRUE,
    'file' => 'user.pages.inc',
    'weight' => -10,
    'menu_name' => 'user-menu',
  );

But I wonder if there is some other way to do this (instead of making changes in core files, which is not recommended of course).
Comment: @Pierre.Vriens : Thanks for information and upvote ;)
Comment: I find your question a bit bizar, but not inappropriate. Do not worry too much about downvotes on SE. Rather consider them as opinion epressions. Also note that it does not "cost" any reputation to downvote a question, while downvoting an answer costs -1 to the downvoter. However, a downvote to a question or an answer always costs -2 to the author of the question or answers. So downvoting questions is cheap (at no cost). so why bother? Also: if you only get 1 upvote (like mine ...), it compensates for 5 downvotes (5 * (-2) = -10) ...
Comment: You're Welcome! Also at http://chat.stackexchange.com/rooms/22624/new-user-experience-for-drupal-answers ... And note 'somebody' also upvoted your comment already ... Right!
Answer: Do not edit core files (ever).
You can do this without code by setting a path alias for the /user path.
Go to admin/config/search/path/add and add the alias customadmin for existing path user:

Now if you go go to /customadmin you will see the login or user page. If you want to ensure that that the /user path also redirects to /customadmin, just enable the Global Redirect module (no configuration needed).
Comment: Sry for late reply Will setting`path alias ` disable `/user` i dnt want them to see login page if they are trying to navigate to `/user`
Comment: Oh got it .....just have to redirect user to custom admin.....thanks
Comment: Everything working fine, how do I make `/user` to show 404 instead of `/customadmin` whole purpose of this was to hide the `adminurl` from third person
Comment: You could just put a redirect for /user in your .htaccess I suppose. Why would you need to do this?
Comment: I dnt want others to reach my admin login page....it was to try to make site more secure @autopoietic
Comment: Strong passwords and disabling user registration should accomplish this without worrying about whether someone can locate the login.
Comment: hmmmm... Thanks @autopoietic for suggestion, I am already making strong password, I will also disable user registration


Flutter: Dynamically Updating TextField Values Based on User Input

Question: I am currently working on my Flutter application and I am encountering difficulties in achieving a specific functionality. The objective is to automatically populate and disable the third TextField on a page that consists of three TextFields, once any two of the TextFields have been filled. Additionally, when at least one of the filled TextFields is cleared, the disabled TextField should be re-enabled.
To illustrate with examples:

In the first scenario, upon entering data in both the first and second fields, the third field should become disabled, and its value should be the product of the values entered in the first and second fields. Consequently, whenever input is entered in either the first or second field, the value of the third field should be updated accordingly.

In another scenario, if data is entered in the first and third fields, the second field should be disabled and its value should be updated automatically. Similarly, I would like the first field to exhibit the same behavior when input is entered in the second and third fields.
I attempted to create a function utilizing the TextEditingController and the onChanged function of the TextField, but I have been unsuccessful in achieving continuous updates to the TextField value. Therefore, I would greatly appreciate any assistance in this matter.
Thank you in advance for your support.
Answer: You can use TextEditingController and flag var combination to achieve what you need. there are so many other ways too. below i added working example implementation.
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MathScreen(),
    );
  }
}

class MathScreen extends StatefulWidget {
  const MathScreen({super.key});

  @override
  State<MathScreen> createState() => _MathScreenState();
}

class _MathScreenState extends State<MathScreen> {
  bool t1 = true;
  bool t2 = true;
  bool t3 = true;

  TextEditingController t1Controller = TextEditingController();
  TextEditingController t2Controller = TextEditingController();
  TextEditingController t3Controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(32.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        enabled: t1,
                        keyboardType: TextInputType.number,
                        controller: t1Controller,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(30.0),
                          ),
                          filled: true,
                          hintStyle: TextStyle(
                            color: Colors.grey[800],
                          ),
                          hintText: "",
                          label: Text("Amount"),
                          fillColor: Colors.white70,
                        ),
                        onChanged: (value) {
                          if ((t3Controller.text == "" || !t3) &&
                              (t2Controller.text != "")) {
                            setState(() {
                              t3 = false;
                              t1 = true;
                              t2 = true;
                              t3Controller.text = value == ""
                                  ? ""
                                  : (num.parse(value) *
                                          num.parse(t2Controller.text))
                                      .toString();
                            });
                          }
                          if (t3Controller.text != "" &&
                              (t2Controller.text == "" || !t2)) {
                            setState(() {
                              t2 = false;
                              t1 = true;
                              t3 = true;
                              t2Controller.text = value == ""
                                  ? ""
                                  : (num.parse(t3Controller.text) /
                                          num.parse(value))
                                      .toString();
                            });
                          }
                          if (t2Controller.text == "" &&
                              t1Controller.text == "" &&
                              t3Controller.text == "") {
                            setState(() {
                              t2 = true;
                              t1 = true;
                              t3 = true;
                            });
                          }
                        },
                      ),
                    ),
                    Text(" X "),
                    Expanded(
                      child: TextField(
                        enabled: t2,
                        keyboardType: TextInputType.number,
                        controller: t2Controller,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(30.0),
                          ),
                          filled: true,
                          hintStyle: TextStyle(
                            color: Colors.grey[800],
                          ),
                          hintText: "",
                          label: Text("Unit Price"),
                          fillColor: Colors.white70,
                        ),
                        onChanged: (value) {
                          if ((t1Controller.text == "" || !t1) &&
                              (t3Controller.text != "")) {
                            setState(() {
                              t1 = false;
                              t2 = true;
                              t3 = true;
                              t1Controller.text = value == ""
                                  ? ""
                                  : (num.parse(t3Controller.text) /
                                          num.parse(value))
                                      .toString();
                            });
                          }
                          if (t1Controller.text != "" &&
                              (t3Controller.text == "" || !t3)) {
                            setState(() {
                              t3 = false;
                              t1 = true;
                              t2 = true;
                              t3Controller.text = value == ""
                                  ? ""
                                  : (num.parse(value) *
                                          num.parse(t1Controller.text))
                                      .toString();
                            });
                          }
                          if (t2Controller.text == "" &&
                              t1Controller.text == "" &&
                              t3Controller.text == "") {
                            setState(() {
                              t2 = true;
                              t1 = true;
                              t3 = true;
                            });
                          }
                        },
                      ),
                    ),
                    Text(" = "),
                    Expanded(
                      child: TextField(
                        enabled: t3,
                        keyboardType: TextInputType.number,
                        controller: t3Controller,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(30.0),
                          ),
                          filled: true,
                          hintStyle: TextStyle(
                            color: Colors.grey[800],
                          ),
                          hintText: "",
                          label: Text("Total Price"),
                          fillColor: Colors.white70,
                        ),
                        onChanged: (value) {
                          if ((t1Controller.text == "" || !t1) &&
                              (t2Controller.text != "")) {
                            setState(() {
                              t1 = false;
                              t3 = true;
                              t2 = true;
                              t1Controller.text = value == ""
                                  ? ""
                                  : (num.parse(value) /
                                          num.parse(t2Controller.text))
                                      .toString();
                            });
                          }
                          if (t1Controller.text != "" &&
                              (t2Controller.text == "" || !t2)) {
                            setState(() {
                              t2 = false;
                              t1 = true;
                              t3 = true;
                              t2Controller.text = value == ""
                                  ? ""
                                  : (num.parse(value) /
                                          num.parse(t1Controller.text))
                                      .toString();
                            });
                          }
                          if (t2Controller.text == "" &&
                              t1Controller.text == "" &&
                              t3Controller.text == "") {
                            setState(() {
                              t2 = true;
                              t1 = true;
                              t3 = true;
                            });
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
              ElevatedButton(
                  onPressed: () {
                    setState(() {
                      t2 = true;
                      t1 = true;
                      t3 = true;
                      t2Controller.text == "";
                      t1Controller.text == "";
                      t3Controller.text == "";
                    });
                  },
                  child: Text("Reset"))
            ],
          ),
        ),
      ),
    );
  }
}

Answer: set a controller for every textfield
in the first field onChanged method check if the second textfield is not empty if not disable the third and do your calculation and if it was empty and the third textfield in not empty disable the second and do your calculation
repeat this approach on all the three textfields according to the order and then handle the empty and clear data with this idea you can achieve what you want


Thrift converting optional to default or required

Question: I have a thrift struct
struct Message {
    1: optional int userID;
    ...
}

Is it a safe operation to change it to default require-ness?
struct Message {
    1: int userID;
    ...
}

If I know it's always set? What about "required"?
Comment: Possible duplicate of [How do I make a required thrift field optional?](https://stackoverflow.com/questions/37558302/how-do-i-make-a-required-thrift-field-optional)
Comment: Why? I am asking the opposite: from optional to default.
Comment: Did you read the answer? No.
Comment: @JensG are you sure? I have an optional field and I simply remove optional (make it default), you think it's un-safe? Could you give one example where it will break?
Answer: As outlined in this answer, there are three degrees of (so-called) requiredness in Thrift:

required: must exist on read, must be set on write
optional: may or may not be set, entirely optional
"default": may not exist on read, always written (unless it is a null pointer )

To answer the question(s) asked:

It is safe to change optional to default (i.e. remove the optional keyword).
Changing optional to required may break compatibility. Unless you make sure all clients/servers are updated accordingly, it may happen that the older side does not supply a value for such a field. In that case, the other end will reject the incoming request or response as incomplete, because that required field is missing from the received data.

For further reading on the subject you may want to consult Diwaker Gupta's highly recommendable "Missing Guide".
Comment: Some very helpful context on default vs optional: https://grokbase.com/t/thrift/user/08azr2zpzv/default-required-optional


How to preserve the original structure of a word while textmining

Question: I would like to create a list of words that appear at least two times based on a specific web page.
I succeeded to get the data and to get a list with count per each word but
I need to retain the words that have  an Upper case to stay this way.Right now the code produces the words list with lower case only.
For example, the word "Miami" turns into "miami" while I need it as "Miami".
How can I get the words in their original structure ?
Attached is the code :
library(XML)
web_page <- htmlTreeParse("http://www.larryslist.com/artmarket/the-talks/dennis-scholls-multiple-roles-from-collecting-art-to-winning-emmy-awards/"
                          ,useInternal = TRUE)

doctext = unlist(xpathApply(web_page, '//p', xmlValue))
doctext = gsub('\\n', ' ', doctext)
doctext = paste(doctext, collapse = ' ')

library(tm)
SampCrps<- Corpus(VectorSource(doctext))
corp <- tm_map(SampCrps, PlainTextDocument)

oz <- tm_map(corp, removePunctuation, preserve_intra_word_dashes = FALSE) # remove punctuation
oz <- tm_map(corp, removeWords, stopwords("english")) # remove stopwords
dtm <-DocumentTermMatrix(oz)

findFreqTerms(dtm,2) # words that apear at least 2 times
dtmMatrix <- as.matrix(dtm)
wordsFreq <- colSums(dtmMatrix)
wordsFreq <- sort(wordsFreq, decreasing=TRUE)
head(wordsFreq)
wordsFreq <-  as.data.frame(wordsFreq)
wordsFreq <- data.frame(word = rownames(wordsFreq), count = wordsFreq, row.names = NULL)
head(wordsFreq,50)

The same problem occurs when I use this lines of code to get a three word ngram:
library(RWeka)
BigramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 3, max = 3))
tdm <- TermDocumentMatrix(oz, control = list(tokenize = BigramTokenizer))
inspect(tdm)

Answer: The problem is that by default, there is an option in DocumentTermMatrix() that lowercases your terms.  Turn this off and you will preserve case.
dtm <- DocumentTermMatrix(oz, control = list(tolower = FALSE))
colnames(dtm)[grep(".iami", colnames(dtm))]
## [1] "Miami"   "Miami,"  "Miami."  "Miami's"

Here's another way to do it using the quanteda package, might be more straightforward:
require(quanteda)
# straight from text to the matrix
dfmMatrix <- dfm(doctext, removeHyphens = TRUE, toLower = FALSE,
                 ignoredFeatures = stopwords("english"), verbose = FALSE)
# gets frequency counts, sorted in descending order of total term frequency
termfreqs <- topfeatures(dfmMatrix, n = nfeature(dfmMatrix))
# remove those with frequency < 2
termfreqs <- termfreqs[termfreqs >= 2]
head(termfreqs, 20)
##      art            I      artists   collecting         work           We   collection   collectors
##       35           29           19           17           15           14           13           12
##     What contemporary          The        world           us           It        Miami          one
##       11           10           10           10           10            9            9            8
##   always         many         make          Art
##        8            8            8            7

We can see that the case for "Miami" (e.g.) is preserved:
termfreqs[grep(".iami", names(termfreqs))]
## Miami Miami's
##     9       2

Comment: Thanks a lot @Ken Benoit. package quanteda seems great.


Implicit assumption in z-test of difference in proportions?

Question: In reading through the literature on z-tests for difference in proportions, I often see it stated that the null hypothesis only tests whether p1 = p2, not whether p1 = p2 = any specific value for the pooled proportion.  But in fact when we use the overall/pooled proportion from our sample to estimate the population proportion to calculate our test statistic, are we not actually making a concrete assumption about a specific value that p1 and p2 are both equal to?
As an illustration, suppose a researcher is interested in evaluating whether men or women in a large city are more likely to own a pet.  The researcher performs separate, independent random samples of 20 men and 20 women and records whether they own a pet or not.  Now lets say the results are that 8 of the 20 men own pets, and 12 of the 20 women own pets.  The overall (pooled) proportion of pet owners from this exercise is 20/40 or 0.5.   By using 0.5 to calculate our test statistic, aren't we really testing the probability that p1 = p2 = 0.5? There is nothing in the standard calculation of the test statistic which says anything about the probability that p1 = p2 = 0.2, or 0.8, or any other value other than 0.5.
It seems to me that if you wanted to really test the probability p1 = p2 = any specific value, you would need to run separate tests for specific different possible p1=p2 values, and then weight the outcomes by the likelihood of these different possible prior probabilities. But that begs the question of what the distribution of prior probabilities looks like....
But really rather than getting into a long discussion on a much more complex analysis involving estimating alternative prior probability distributions, I really am looking for confirmation that the more common approach of using a z-test for difference in proportions is actually testing the validity of a null hypothesis that p1 = p2 = the specific value as determined by the pooled sample proportion - despite what I have commonly encountered in textbooks and online explanations which claim that no specific value for p1 = p2 is being tested.
Comment: An astute question. See also [On Fisher's exact test: What test would have been appropriate if the lady hadn't known the number of milk-first cups?](http://stats.stackexchange.com/q/136584/17230) for some discussion of exact tests. Nuisance parameters can be a nuisance.
Comment: Thanks for your comment!  Since first learning about the FET, I have always felt it to be a very exact answer in search of proper question.  I have tried to calculate a p-values more directly by simply looking at all the possible discrete outcomes for the product of two binomials, and summing all outcomes which have an equal or lower probability of occurring compared to the specific outcome observed in the 2 independent samples.  After all, isn't the purpose of hypothesis testing to see just how rare the outcome we have observed must be if the null is true?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/40374/discussion-on-question-by-user221943-implicit-assumption-in-z-test-of-difference).
Answer: The textbooks are right and you test $p_1=p_2$ vs. them not being equal. The standard test statistic is a quantity., for which the distribution is asymptotically known under the null hypothesis, which is the basis for using it. It so happens to involve the observed proportions  (unsurprisingly, really), but the value of $p_1$ is just a nuissance parameter.
Comment: Thank you - I have accepted your answer but I must admit the intuition for this still escapes me.  I understand that the observed pooled proportion is the Most Likely Estimate (MLE) and therefore is certainly superior to using any other alternative.  But this concept of the value of p1 and p2 being a nuisance parameter that doesn't really impact our hypothesis test is counter-intuitive for me.  There is certainly some probability of the true proportion being say 30% instead of 50%, and using 30% instead of 50% would certainly change test-statistic and the corresponding p-value, no?
Comment: Using a different number would give a different test statistics, but under repeated sampling using this formula gives a level $\alpha$ test. Or frame it as a logistic regression, where we assume $Y_i \sim \text{Bin}(n_i, p)$ and $\text{logit}(p) = \text{logit}(p_1) + 1{i=2} \times \beta$. If you do a hypothesis test for the log-odds ratio $\beta$, you are not doing a hypothesis test for $\text{logit}(p_1)$ and you could commit a separate type I error for it. Another thing is that $p_1 = p_2 = \text{sample proportion}$ is not an up-front hypothesis (depends on the sample proportion!).


How to subtract two columns in Informix 12.10

Question: I would like to subtract a column from another column in Informix 12.10.
SELECT
    NAME,
    PRICE1
    PRICE2,
    (PRICE1 - PRICE2) AS VALUE
FROM PRODUCTS

Does somebody have an idea how can I do that?
Comment: Note that there are only 3 values selected by the SQL shown, not 4 as the layout suggests is intended.  Since there is no comma at the end of the line containing just PRICE1, the PRICE2 on the next line is treated as the 'display label' (column alias) for PRICE1.  Adding a comma after the first PRICE1 would display the two raw prices and the difference.  Using the explicit AS clause should suspend any keyword meaning for VALUE — Informix takes a permissive attitude towards using keywords as identifiers.
Comment: What is the error you get?
Answer: VALUE is a keyword in IBM Informix SQL.  Use something else for the alias, or, if you must use VALUE, then wrap it in double quotes.
SELECT
    NAME,
    PRICE1
    PRICE2,
    (PRICE1 - PRICE2) AS "VALUE"
FROM PRODUCTS;

Comment: I changed it to the original post.


How do I sort an array of custom classes?

Question: I have a class with 2 strings and 1 double (amount).
class Donator

string name
string comment
double amount

Now I have a Array of Donators filled.
How I can sort by Amount?
Comment: A donator is a connoisseur of donuts.
Comment: @Jeff Oh no, he definitely wants to use `IndividualHumanBeingWhoDonated`
Comment: Duplicates: http://stackoverflow.com/questions/1301822/how-to-sort-an-array-of-object-by-a-specific-field-in-c http://stackoverflow.com/questions/1812044/how-to-sort-an-array-of-objects-in-visual-c http://stackoverflow.com/questions/1211617/sort-an-array-of-strongly-typed-objects-based-on-a-property-of-the-object-c
Answer: If you implement IComparable<Donator> You can do it like this:
public class Donator :IComparable<Donator>
{
  public string name { get; set; }
  public string comment { get; set; }
  public double amount { get; set; }

  public int CompareTo(Donator other)
  {
     return amount.CompareTo(other.amount);
  }
}

You can then call sort on whatever you want, say:
var donors = new List<Donator>();
//add donors
donors.Sort();

The .Sort() calls the CompareTo() method you implemented for sorting.
There's also the lambda alternative without IComparable<T>:
var donors = new List<Donator>();
//add donors
donors.Sort((a, b) => a.amount.CompareTo(b.amount));

Comment: @eschneider - That is almost always overkill for something this simple.  How would that be "better"?
Comment: A class implementing IComparer is probably a better approach.
Comment: Chances are they will need to sort various ways.

DonorAmountComparer, DonorLastNameComparer, DonorAmountThenLastNameComparer.
Comment: @eschneider - That's *completely* outside the question...but even if they needed to, it's still much more compact to do in a lambda.  The decision to use a comparer would be personal preference, and no one I've worked with has opted for that in the past few years.
Comment: I disagree, It's totally related. In most cases I agree with you, but in a case where you will probably need multiple sort orders, a comparer is the best approach.
Comment: @eschneider - Sure it's related, but it's *not the question*  The question was: "How I can sort by Amount?"  This does that in much less code and fewer classes than IComparer.  Should we create an IComparer for Linq instead of using `.OrderBy()`? Why not?, it's the same  argument.  In .Net 1 you had only IComparer, in 2.0 they added something better, in 3.0 even better, why not take advantage of it?
Answer: By implementing IComparable and then use Array.Sort.
public class Donator : IComparable {
    public string name;
    public string comment;
    public double amount;

    public int CompareTo(object obj) {
        // throws invalid cast exception if not of type Donator
        Donator otherDonator = (Donator) obj;

        return this.amount.CompareTo(otherDonator.amount);
    }
}

Donator[] donators;  // this is your array
Array.Sort(donators); // after this donators is sorted

Comment: He could also pass a lambda expression if he doesn't want to create a new class
Comment: Tried it, but how to sort really?
Answer: You can also use delegates:
class Program
{
    static void Main(string[] args)
    {
        List<Donor> myDonors = new List<Donor>();
        // add stuff to your myDonors list...

        myDonors.Sort(delegate(Donor x, Donor y) { return x.amount.CompareTo(y.amount); });
    }
}

class Donor
{
    public string name;
    public string comment;
    public double amount;
}

Answer: I always use the list generic, for example
List<Donator> MyList;

then I call MyList.Sort
MyList.Sort(delegate (Donator a, Donator b) {
   if (a.Amount  b.Amount) return 1;
   else return 0; );

Comment: This is the same as a.Amount.CompareTo(b.Amount)
Comment: Right. In addition, with my method, you can then add additional logic to sort by Amount first, then, Name if Amount is the same, etc. CompareTo is simpler for this case, and my example would only be useful if you needed more interesting sorting logic.
Comment: I think you're missing a wavy.
Answer: You could use MyArray.OrderBy(n => n.Amount)
providing you have included the System.Linq namespace.
Comment: I tried myArray = myArray.orderby... error is:Fehler 1 Eine implizite Konvertierung vom Typ "System.Linq.IOrderedEnumerable" in "DongleDonatorSite.Donator[]" ist nicht möglich.
Comment: Use .ToArray() to turn the enumerable back into an array.
Comment: You might want to add `.ToArray()` at the end or change the type of the variable you are assigning the result to. By the way, in many cases it is more practical (but not always when performance is an issue) to stop using arrays and start using a generic list.
Comment: According to the OP he is using .Net 2.0
Answer: Here is a sort without having to implement an Interface.  This is using a Generic List
    List<Donator> list = new List<Donator>();
    Donator don = new Donator("first", "works", 98.0);
    list.Add(don);
    don = new Donator("first", "works", 100.0);
    list.Add(don);
    don = new Donator("middle", "Yay", 101.1);
    list.Add(don);
    don = new Donator("last", "Last one", 99.9);
    list.Add(don);
    list.Sort(delegate(Donator d1, Donator d2){ return d1.amount.CompareTo(d2.amount); });

Answer: Another way is to create a class that implements IComparer, then there is an overload to pass in the Comparer class.
http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx
This way you could have different classes for each specific sort needed. You could create one to sort by name, amount, or others.


SVM (and Random Forest) for stock prediction - training/test accuracy high and validation poor

Question: i'm facing this kind of issue. I set up a good model (122 variables) with 1700 records: training accuracy and test are close to 80%. I'm trying to predict 8 days ahead, the movement of a stock index. Basically i did:
use both SVMRadial and RF in R
created a partition 70/30 to split training set and test  use repeatedCV (5 folds x 5 times)
at the end, i got encouraging accuracies in classification, both in training and test set.
Finally i tried to validate the model, testing  unseen data: i performed a direct 8-days step ahead to process current  record (time t) to get the result for time t+8 (the latest Y to feed, the output of the classifier, is from 8 days in the past).Then i carried on training the model with the freshest data and jumping 8 records ahead on and on iteratively. Accuracy dramatically drops down to 50/55% making the classifier pointless. This happens both in SVMRadial and in RF: practically the model, even though always trained till the last available complete data (with the relevant y, that is +1 or -1), is unable to be accurate with new data.I also tried a recursive solution to fill the 8 missing Ys with random forest, getting poor results. Why my model is unable to generalize, providing good results just only  8 records ahead from the last training point? is the cause overfitting with cross validation? How can i manage it?
thank in advance!
regards
Answer: While not knowing what your predictors are, it works out that multi-instrument (and multi-market) models usually perform much better on out-of-bag (out-of-training) data.  See the software package called VantagePoint, which uses separate prediction models (neural networks, not too far from SVM) for the 2-day lagged data, 5-day lagged data, and 10-day lagged data - and then determines which time-frame is the most dependable.  Most of their models use data/indices from other markets and exchanges.
Another issue for stock price prediction is that many of the days or epochs of time you are using are redundant, so you may not need 1700 records or 122 predictors.  Thus, you might use PCA on both the days and the 122 predictors to reduce the dimensions (decorrelate/denoise).  Jurik Research sells a module known as DDR (decorrelator, dimension reducer) which can perform two-way PCA on time and features for financial data.
Comment: I've tried a lot of neural network approaches to stock price prediction, and results were not that good either.  Markets are a complex system, so you commonly have to use pattern recognition as well, involving e.g. fractals, etc.
Comment: Thanks for your prompt answer. Basically i'm using technical indicators and other indices as predictors (e.g.S&P500).I'll sure try a PCA, that should be embedded in preProcess options (R) to reduce dimension and decorrelate. I have tried everything in feature engineering: make differences to kill trends, exponential smoothing, data transformation ,lagged variables, feature selections tools like Boruta, RFE , GAs. Random forest has an incredible ability to classify (as time ahead increases): it keeps this skill for the very following  record  , but cannot go up to the last effectively. Thanks!


JPA 2.0 & EJB 3.1 - update the owner side relationship was trying to insert record?

Question: I have a model:
@Entity
class A {
   @ManyToOne
   B b;
   int i;
}

@Entity
class B {
   @OneToMany(mappedBy="b")
   List list = new ArrayList();
}

Now in my EJB service I do:
void f(Aid,Bid){
   A a = em.find(A.class, Aid);
   B b = em.find(B.class, Bid);
   a.setB(b);
}

This throw db constraint exception (INSERT INTO B VALUES... WITH SAME VALUES THAT ALREADY EXIST IN CURRENT B).

Why it's try to insert a new record to B while it's already exist in B table and the relationship is not PERSIST?

NOTES:
1 When i do after the last row:
em.merge(a);

It's work as well...???
2 When i do a.setI(1); without merge - it's changed in DB (like i thought it will)
THANKS!!!
Comment: Your question is really confusing.  What are you asking?
Comment: Can you provide more information on your model like id properties etc?
Answer: It's a bidirectional relationship. You should always update both sides of the relations ships. Otherwise, if you don't directly have problems while persisting, you can easily corrupt your cache and face some stange bugs in your application.
So, if you have this:
A a = em.find(A.class, Aid);
B b = em.find(B.class, Bid);
a.setB(b);

You should add this right after:
List aList = b.getList();
if (!aList.contains(b)) {
    aList.add(b);
}

2 When i do a.setI(1); without merge -
  it's changed in DB (like i thought it
  will)

If you're using an entityManager in an ejb (which I seems you do regarding your tags), it's normal that changes to managed entities are persisted. Was that te question?
Also, you should make sure that entities identity, equals() and hashcode() are defined correctly (maybe it is, but you didn't mention it).


Computing probability distribution function for uniform random variables and Y=1-X

Question: X is uniform random variable in [0,1] and Y=1-X. How do I calculate the distribution function F(X,Y)? I can see that Y is also uniformly distributed and can draw the intervals. But I am unable to compute the distribution function when x+y>1 & x,y in [0,1]. How do I compute it for this specific case?
Answer: $F(x,y) = P(X \le x, Y \le y)$
Using the fact that $Y= 1-X$ and after simplifying, the above can be re-written as:
$F(x,y) = P(1-y \le X \le x)$
Since, $X$ is a uniform between 0 and 1, it follows that:
$F(x,y) = x+y-1$
Update
The above is a bit sloppy as I did not specify the domain of the cdf where it is non-zero appropriately. Consider:
$F(x,y) = P(1-y \le X \le x)$
Thus,
$F(x,y) = x+y-1$
Two points about the above cdf:

For the above cdf to be non-zero it must be the case that:
$x > 1-y$

Also, note that the cdf attains the value of 1 when $x+y=2$.

Thus, the correct way to represent the cdf is:
$F(x,y) = 0$ if $x+y \le 1$
$F(x,y) = x+y-1$ if $1 \le x+y \le 2$
$F(x,y) = 1$ otherwise
Comment: And what if x=12 and y=1/2? Then your answer will have  F(12, 1/2)=12+1/2-1=23/2.
Comment: @PeterR good point! Fixed the error.
Answer: I'm interpreting your question as concerning the cdf, which by definition is a function $F$ for which
$$F(x,y) - F(x,0) - F(0,y) + F(0,0) = \Pr(X \le x, Y \le y) \text{;}$$
$$F(0,0) = 0.$$
For $x + y \lt 1$, the right hand side is zero and the left hand side becomes a statement that $F$ is a bilinear function, implying (in conjunction with some of the initial values specified below) that the graph of $F$ is part of a plane.  For $x + y \gt 1$, the assumption of uniform distributions implies $F$ must be increasing at a unit rate in both $x$ and $y$, whence the graph of $F$ in this region is a part of a plane of the form $x + y = \text{constant}$.  From the evident restrictions
$$F(x, 0) = F(0, y) = 0,$$
$$0 \le x  \le 1, 0  \le y  \le 1,$$
it is geometrically obvious that the first piece of the graph must lie in the xy plane and the second piece must intersect the first along the line segment $x + y = 1, 0  \le x  \le 1$.  The full solution therefore is
$$F(x,y) = 0 \quad \text{if} \quad x + y  \le 1$$
$$F(x,y) = x + y - 1 \quad \text{if} \quad x + y \gt 1.$$

This result is the Fréchet–Hoeffding minimum copula $W(x,y)$.  Generally, a copula expresses a multivariate distribution after the marginal variables have been subjected to a probability integral transformation; that is, the marginals have been made uniform.  All 2D copulas must have values between this minimum $W$ and the maximum copula $M(x,y) = \min(x,y)$.  $W$ expresses maximum anticorrelation between the variables while $M$ expresses maximum correlation between them.  Follow the link (a Wikipedia article) for Mathematica plots of these copulas.
Comment: @Srikant: Done.  Thank you for the excellent guidance.
Comment: +1 A better answer than mine as it explicitly takes into consideration the range over which the pdf is non-zero.
Comment: @Srikant: Thanks; you are generous.  Did you notice the connection with the theory of copulas?  Maybe we should even add a "copula" tag.
Comment: @whuber My familiarity with copulas does not go very far. In any case, I am not sure how many will see the connection. So, a copula tag may just confuse some.
Comment: @Srikant: Granted.  But isn't the point of tags to facilitate searches and create semantic ties among threads?  I'm sure plenty of existing tags also have the potential to confuse the uninitiated already.  Maybe this is a discussion for the meta site?
Comment: @whuber True. But, right now the connection to copulas is a bit obscure for those who do not know what they are. Perhaps, you can add a line or two to make the connection in which case the tag 'copula' may make sense.


Express multivariate normal as a univariate normals

Question: I want to find the univariate normals of a multivariate normal in order to plot them. If we assume that each are independent, then I know that we can use the mean vector and diagonal of the covariance of the multivariate normal can be used as the means and variances of those independent univariate normal distributions.
Is it same to assume so or are there any other technique to derive the univariate normals of a multivariate normal?
I appreciate any help resolving the above doubt.
Comment: @MichaelChernick, I guess so. According to the [wikipedia](https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Marginal_distributions) the marginal distribution of multivariate normal distribution is derived by dropping the irrelevant variables. Therefore, can't I just used the individual mean and variance of each variable to find its 1-dimensional marginal?
Comment: Are you talking about determining all the 1-dimensional marginals?  If so you can get them by integrating out all the other components from the joint distribution.
Answer: Your comment:

Therefore, can't I just used the individual mean and variance of each variable to find its 1-dimensional marginal?

This is exactly what you can do. To see this in the case for a bivariate normal
$$\left(\begin{array}{c}X_1 \\X_2 \end{array}\right) \sim N_2\left(\left(\begin{array}{c}\mu_1 \\\mu_2 \end{array}\right), \left(\begin{array}{cc}\sigma^2_1 & \sigma_{12} \\ \sigma_{12} & \sigma^2_2 \end{array}\right) \right)\,. $$
Let $\rho = \sigma_{12}/\sigma_{1} \sigma_2$. The pdf of this random variable is
$$ \Tiny f(x_1, x_2) = \dfrac{1}{2 \pi \sigma_2 \sigma_2 \sqrt{1 - \rho^2}} \exp \left\{-\dfrac{1}{2\sqrt{1-\rho^2}}\left( \dfrac{(x_1 - \mu_1)^2}{\sigma^2_1}  - \dfrac{2\rho(x_1 - \mu_1)(x_2 - \mu_2)}{\sigma_1 \sigma_2} + \dfrac{(x_2 - \mu_2)^2}{\sigma_2^2} \right)\right\} \,.$$
To obtain the marginal distribution of $X_1$, we integrate out $X_2$. You can find a proof of that here. For the multivariate normal case, you can find a proof here.
Comment: +1 -- but the proof is dead simple.  It amounts to observing that after integrating out all the other variables, the integrand is still the exponential of a quadratic form in the remaining variable and that its leading term and linear term do not change. (That is, there's no need actually to perform the integration or even to write out the PDF explicitly.) Those facts uniquely determine the answer.
Answer: If you have a multivariate normal with means $\mu$ and covariance matrix  $\Sigma$, then the univariates (marginals) are simple normals with corresponding mean $\mu_i$ and the variance $\Sigma_{ii}$: $$x_i\sim\mathcal N(\mu_i,\Sigma_{ii})$$


Python ttk.OptionMenu Option Font Style

Question: Before you call this a duplicate of any existing post on StackOverflow, please read:
I have a ttk.OptionMenu widget and I cannot seem to shift the style of the options in the widget. The style that I have applied has only modified the display box for the selected entry, but I am interested in changing the font style of the drop-down so that it matches the selected option as well.
import tkinter as tk
from tkinter import ttk

root=tk.Tk()

optList1 = [
    "1",
    "2",
    "3"
    ]

var1 = tk.StringVar(root)
var1.set(optList1[0]) #first value default

someStyle=ttk.Style()
someStyle.configure('my.TMenubutton',font=('Futura',20))

optMenu1 = ttk.OptionMenu(root, var1, optList1[0], *optList1, style='my.TMenubutton')
optMenu1.pack()

root.mainloop()

I am unsure why the defined style does not apply to the options that display and I would appreciate any help on this. My suspicion is that the drop-down selections are using some separately defined font style that could potentially be a system font setting.
Comment: Try `optMenu1['menu'].configure(font=('Futura',20))`
Comment: @stovfl thank you very much! I had seen many answers in the past with the `menuname` portion of the configure statement, but that must not exist in the `ttk.Optionmenu` variant because it says that the attribute does not exist. This solved my problem!

Please copy this to an answer so I can choose this as an answer for future people to benefit from!
Answer: You have to configure dropdown selections separately by using:
optMenu1['menu'].configure(font=('Futura',20))

Here is the code:
import tkinter as tk
from tkinter import ttk

root=tk.Tk()

optList1 = [
    "1",
    "2",
    "3"
    ]

var1 = tk.StringVar(root)
var1.set(optList1[0]) #first value default

someStyle=ttk.Style()
someStyle.configure('my.TMenubutton',font=('Futura',20))

optMenu1 = ttk.OptionMenu(root, var1, optList1[0], *optList1, style='my.TMenubutton')
optMenu1['menu'].configure(font=('Futura',20))#add this to your code it will change style for dropdownlist
optMenu1.pack()

root.mainloop()

Answer:
Try:
optMenu1['menu'].configure(font=('Futura',20))

stovfl, Feb 11 (2019) at 22:15
Comment: This is literally a copy-paste of a comment to the question...
Comment: Add more details to your answer will help users.

Python ttk.OptionMenu Option Font Style


Relation between Pi and the Median

Question: I was reading about efficiency here and came across something curious.
For large N the sample median is approximately normally distributed as

Then again here I found that for a sample of size N=2n+1 from the normal distribution, the efficiency for large N is
 and, naturally, as N tends to infinity,
I'm reminded of the YouTuber 3blue1brown in this Ted Talk and his curiosity how sliding blocks and their collisions were related to pi, but he did not see any circles.
My question is twofold:

I'm genuinely curious how pi is related to the Median this much (and probably more).
And since pi is intimately related to circles, can I say that the Median is associated with circles in some way? If so, what sort of association is it?
Comment: usually with these things i think it's more that $\pi$ is related to the (complex) exponential which truly is ubiquitous rather than circles
Comment: My post at https://math.stackexchange.com/a/3558/1489 describes relationships between $\exp(-z^2),$ polar coordinates, and 2D disks.
Answer: To answer your specific question about the median, there's a passage in your second link, in the section on sample median:

Sampling distribution
... The distribution of the sample median from a population with a density function $f(x)$ is asymptotically normal with mean $m$ and variance
$\begin{align}\frac{1}{4nf(m)^2}\end{align}$
where $m$ is the median of $f(x)$ and $n$ is the sample size.

The example pulled from your first link assumes a normal population with mean $m$ and unit variance. In this case, $$f(x) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp(\frac{-(x-m)^2}{2\sigma^2})=\frac{1}{\sqrt{2\pi}}\exp(\frac{-(x-m)^2}{2})$$ The normal distribution's mean is equal to its median, so $f(m)=\frac{1}{\sqrt{2\pi}}$. Putting it together then, we have that the sampling distribution of the median is asymptotically normal with mean $m$, and variance given by
$$\frac{1}{4n(\frac{1}{\sqrt{2\pi}})^2}=\frac{2\pi}{4n}=\frac{\pi}{2n}$$
That's all to say that the reason $\pi$ shows up here is that the formula for the asymptotic variance includes the density function of the population, evaluated at the median. When the population is normally distributed, this brings $\pi$ into the term for the variance, because of the $\pi$ constant in the normal density.
As for why $\pi$ shows up in the normal density, @jld's comment and @whuber's link to his answer offer great insight.

Relation between Pi and the Median