How Many 4-Digit Positive Even Numbers Use Only Digits 0 Through 4, With No Digits Repeating?

Question: I am currently working on this problem:

How many 4-digit multiples of 2 use only digits 0 through 4, with no digits repeating?

I understand/know the basic idea of how to solve this kind of problem:
You multiply the number of possible numbers that could be in each place, for example, for How many 4 digit numbers use only digits 0 through 3, with no digits repeating?, the answer would be 3 * 3 * 2 * 1, or 18.
In my problem, the last digit of any even number is either 0, 2, or 4. That gives us this current multiplication equation:

_ * _ * _ * 3

The reason I am stuck on this problem is because, in the first space, there could either be 4 possibilities(1, 2, 3, 4) or 3 possibilities(1, 3, 4 OR 1, 2, 3),  depending on if 2 or 4 is used in the ones column.
And depending on the 1st column, the following numbers of possibilities will be one minus the last number.
Now, because there can be two possible number of possibilities in the left-most/4th space, there can be two multiplication problems, which makes this problem confusing for me:

4 * 3 * 2 * 3

OR

3 * 2 * 1 * 3

So my question is: How would you solve this problem?
Comment: They are $60$, namely $$(1024, 1032, 1034, 1042, 1204, 1230, 1234, 1240, 1302, 1304, 1320,
1324, 1340, 1342, 1402, 1420, 1430, 1432, 2014, 2034, 2104, 2130,
2134, 2140, 2304, 2310, 2314, 2340, 2410, 2430, 3012, 3014, 3024,
3042, 3102, 3104, 3120, 3124, 3140, 3142, 3204, 3210, 3214, 3240,
3402, 3410, 3412, 3420, 4012, 4032, 4102, 4120, 4130, 4132, 4210,
4230, 4302, 4310, 4312, 4320)$$
Comment: Consider cases, depending on whether the units digit is $0$.
Answer: The answer can be written as
$$1\cdot4\cdot3\cdot2+2\cdot3\cdot3\cdot2$$
The idea is to split the count into two cases, according to whether the ones digit (which makes the number even) is $0$ or not.  There's only one way to choose $0$, after which the remaining digits can be chosen in $4\cdot3\cdot2$ ways. There are two ways to choose nonzero ones digit (either $2$ or $4$), but that means there are only three choices for the lead digit, since you have to avoid the $0$. But after that, the two interior digits can be chosen in $3\cdot2$ ways.
Added later: The heart of this solution is the calculation of $1\cdot4+2\cdot3$, which amounts to counting the number of two-digit even numbers out of the digits $0$ to $4$; the remaining $3\cdot2$ is routine. I was bemused by the observation that $1\cdot4+2\cdot3=10={5\choose2}$, where the latter counts the number of (unordered) choices of $2$ of the $5$ digits, and wondered if this could be attributed to anything more than numerical coincidence (aka, Richard Guy's Strong Law of Small Numbers). It turns out it can:
Note that each odd digit can be paired with a distinct nonzero even digit, e.g., $1$ with $2$ and $3$ with $4$. Now pick any pair of digits, which can be done in $5\choose2$ ways. If one of the chosen digits is $0$, put it in the ones digit and use the other as the lead digit.  If both are even but neither is $0$, put the smaller in the ones digit and use the larger as the lead digit. If both are odd, replace each one with the even digit it's been paired with and then put the larger of these in the ones digit and use the smaller as the lead digit.
This works as long as each odd digit can be paired with a nonzero even digit, i.e., if the set of available digits consists of $0$, $k$ odd digits, and $k$ nonzero even digits, giving a count of $2k+1\choose2$ two-digit even numbers. (It also works without the $0$, the count being simply $2k\choose2$ in that case.)
Answer: You can choose one's place in $3$ ways $(0, 2, 4)$.
Once you do that, you now have $4$ digits left for the second place (ten's), $3$ for the third (hundred) and $2$ for the $4$th (thousand).
That gives you $3 \times 4 \times 3 \times 2 = 72 \ $ numbers.
But this also counts numbers that have $0$ in thousand place. We need to remove them as they are not $4$ digit numbers really.
So if I fix $0$ in thousand place, I have $2$ choices for one's place ($2, 4$), $3$ remaining for the ten's and $2$ remaining for the hundred place, which is $12$ numbers in total (= $2 \times 3 \times 2$).
So the count of numbers you are interested in $ = 72 - 12 = 60$.


Undefined for chrome.storage.sync.get?

Question: In my content script, I set a a couple chrome.storage values, and in my popup script, I read and get those values.
I've tried everything, but it keeps returning "undefined" which doesn't make sense because the value is certainly not undefined.
My content.js script:
imgs=["test.png","othertest.png"]

for (i = 0; i < imgs.length; i++){
    var key = "image"+i
    var value = imgs[i]
    chrome.storage.sync.set({key: value}, function() {
      console.log('Value is set to ' + value + ' and key is set to '+key);
    })
}
chrome.storage.sync.set({"count": imgs.length}, function() {
      console.log('Saved count value. Current count: '+imgs.length)
});

My popup.js script:
document.addEventListener('DOMContentLoaded',function(){
    chrome.storage.sync.get(['count'], function(result) {
        console.log(result.value)
        for (i = 0; i < result.value; i++){
            chrome.storage.sync.get(['image'+i], function(result) {
                var img = document.createElement("img")
                img.src = result.value
                document.body.appendChild(img)
            })
        }
    })
})

My popup.html file:
<!doctype html>

        <meta charset="utf-8">
        <title>Untitled Document</title>

Images

The popup.js script is supposed to get every image from chrome.storage and display them on the popup. Any help would be greatly appreciated.
Comment: See also [How to use a variable for a key in a JavaScript object literal?](//stackoverflow.com/q/2274242)
Comment: Is the callback in `set` being executed?
Comment: @Royson yes. It returns `Value is set to test.png and key is set to image1`
Answer: This worked for me thanks to my finding of this answer!
Popup.js:
document.addEventListener('DOMContentLoaded',function(){
    function getCountValue(callback) {
        chrome.storage.sync.get("count", callback);
    }
    function getImageValue(number,callback) {
        chrome.storage.sync.get(['image'+number], callback);
    }
    getCountValue(function (count) {
        for (i = 0; i < count.count; i++){
            getImageValue(i, function(imgvalue){
                for (var property in imgvalue) {
                    if (imgvalue.hasOwnProperty(property)) {
                        var img = document.createElement("img")
                        img.src = imgvalue[property]
                        document.body.appendChild(img)
                    }
                }
            })
        }
    })
})

Undefined for chrome.storage.sync.get?


Content Type Content Theme Template

Question: Is it possible to make a template based on node content?
For instance, is it possible to page--[node-type]--%.tpl.php or block--[content-type].tpl.php or page--[content-type]--%.  I tried node--[content-type].tpl.php but to no avail.  When I use the theme developer module, it shows me that my content is being created as a 'block.tpl.php' template.
What I want to do is theme the content of node name 'vehicle'. I want to put custom headings, styles and classes for divs in, and display suite is not giving me these options.  Any other suggestions would be awesome.
Thanks
Answer: You are right node--[content-type].tpl.php is what you are looking for ,, but you need to get the fields values which can be done with print_r($node) inside the tpl file.
clear your cache to be sure to see the result.

Content Type Content Theme Template


Uncertainty proving statement via contradiction

Question: If $a,b,c\in\Bbb N$ then at least one of $a-b$, $a+c$, and $b-c$ is even.
For the sake of contradiction, assume $a-b$, $a+c$, and $b-c$ are all odd. This gives us $a-b=2l+1$, $a+c=2m+1$, and $b-c=2n+1$ for $l,m,n\in\Bbb N$.
Now we have:
$\begin{align*}a-b&=2l+1\\a&=2l+b+1\end{align*}$
Substituting:
$\begin{align*}(2l+b+1)+c&=2m+1\\2l+b+c&=2m\\b&=2m-2l-c\end{align*}$
Substituting again:
$\begin{align*}(2m-2l-c)-c&=2n+1\\2m-2l-2c&=2n+1\\2c&=2m-2l-2n-1\\c&=m-l-n-\frac12\end{align*}$
But this is impossible for $c\in\Bbb N$, thus a contradiction and we are finished.
$\blacksquare$
I'm wondering if my reasoning is sound for this proof.. is there a simpler way I could have done it? Any advice welcome
Comment: If you add them all together you get $2a$ which is even.  An odd plus and odd  plus an odd is odd.   Indeed you must have either onee even and two odds or three evens.  But I'd prefer to read your proof than my argument.
Answer: Your proof is fine.
Here's any easier one: Suppose $a+c$, $a-b$, $b-c$ are odd. Then their sum is odd. This is a contradiction since there sum is $2a$, which is even.


How to solve a 4th order PDE using Fourier spectral method?

Question: I would like to solve PDE in a numerical way (Fourier spectral method, actually). And I think I should find some particular solution of the equation to apply the method, but I don't know how.
The equation is:
$$\frac {\partial y}{\partial t} - \frac{\partial ^2 y}{\partial x^2} + \frac{\partial ^4 y}{\partial x^4} = 0.$$
I thought $y = e^{-12t} \sin{2x}$ might be a particular solution. So I used following modified MATLAB code:
(Originally, it was made to solve KdV equation, and it put particular solution of KdV equation to u. I just put the particular solution above to u.
%         FFT with integrating factor v = exp(-ik^3t)*u-hat.

% Set up grid and two-soliton initial data:
  N = 256; dt = .4/N^2; x = (2*pi/N)*(-N/2:N/2-1)';
  A = 2; B = -12; clf, drawnow, set(gcf,'renderer','zbuffer')
  u = sin(A*x)*exp(12*t);
  v = fft(u); k = [0:N/2-1 0 -N/2+1:-1]'; ik3 = 1i*k.^3;

% Solve PDE and plot results:
  tmax = 0.006; nplt = floor((tmax/25)/dt); nmax = round(tmax/dt);
  udata = u; tdata = 0; h = waitbar(0,'please wait...');
  for n = 1:nmax
    t = n*dt; g = -.5i*dt*k;
    E = exp(dt*ik3/2); E2 = E.^2;
    a = g.*fft(real( ifft(     v    ) ).^2);
    b = g.*fft(real( ifft(E.*(v+a/2)) ).^2);     % 4th-order
    c = g.*fft(real( ifft(E.*v + b/2) ).^2);     % Runge-Kutta
    d = g.*fft(real( ifft(E2.*v+E.*c) ).^2);
    v = E2.*v + (E2.*a + 2*E.*(b+c) + d)/6;
    if mod(n,nplt) == 0
      u = real(ifft(v)); waitbar(n/nmax)
      udata = [udata u]; tdata = [tdata t];
    end
  end
  waterfall(x,tdata,udata'), colormap(1e-6*[1 1 1]); view(-20,25)
  xlabel x, ylabel t, axis([-pi pi 0 tmax 0 2000]), grid off
  set(gca,'ztick',[0 2000]), close(h), pbaspect([1 1 .13])

But it doesn't seem that it works pretty well.
Comment: Taking the Fourier transform wrt $x$ we can solve the resulting ODE analytically to give $\hat{y}(k,t) = \hat{y}(k,0) e^{-(k^2+k^4)t}$ so the solution at any time $t$ can be obtain from two simple Fourier transforms: $$y(x,t) = \mathcal{F}^{-1}\left[\mathcal{F}[y_0]e^{-(k^2+k^4)t}\right]$$ I'm assuming here the domain is $(x,t)\in \mathbb{R}\times [0,\infty)$ and that $y(x,0)$ is given.
Comment: What domain $\mathbb{R}\times [0,\infty)$ ? What initial (and/or boundary) condition?
Comment: Well, any boundary condition or domain that suits this equation is fine, But  unfortunately I don't know how to set appropriate ones. What I gotta do is  to know how the fourier spectral method works for high-order linear PDEs.
Comment: Note that $e^{-12t}\sin(2x)$ is not a solution of the given PDE. You probably forgot the minus sign in front of $-y_{xx}$. A correct solution is $y(x,t) = e^{-(a^2+a^4)t}\sin(ax)$ so for $a=2$ we get $e^{-20t}\sin(2x)$.
Answer: I'm a little late to answer the question, but I stumbled upon it while researching the subject. This answer may help the next people working on this equation and using this code made by Lloyd N. Trefethen (p27.m)
As you said the code you used was made to solve the KdV equation which is really different from your equation. The Korteweg–de Vries is third-order nonlinear dispersive partial differential equation. It reads
$$ u_t + u u_x + u_{xxx} = 0$$
and can be rewritten as
$$ u_t+ \left(\frac{1}{2}u^2\right)_x + u_{xxx} = 0.$$
As explained in the comments, the code uses Fourier spectral methods coupled with the integrating factor method. The latter method is used to deal with the nonlinearity that you do not have in your equation. Here's the development leading to this code:
The Fourier transform of the last equation leads to
$$\hat{u}_t + \frac{i}{2}k\widehat{u^2} - i k^3 \hat{u} =0.$$
Now by multiplying by the integrating factor we get
$$e^{-ik^3t}\hat{u} + \frac{i}{2}e^{-ik^3t}k\widehat{u^2} - ie^{-ik^3t} k^3 \hat{u} =0.$$
Let $\hat{v} = e^{-ik^3t} \hat{u}$ and $\hat{v}_t = -ik^3\hat{v} + e^{-ik^3t}\hat{u}_t$, the initial problem becomes
$$\hat{v}_t + \frac{i}{2}e^{-ik^3t}k\widehat{u^2} = 0 $$
and in Fourier space
$$\hat{v}_t + \frac{i}{2}e^{-ik^3t}k\mathcal{F}\left(\mathcal{F}^{-1}\left(e^{ik^3t}\hat{v}\right)^2\right) = 0.$$
Add the Runge-Kutta scheme and you obtain the code above.

Back to your equation. The Fourier transform of
$$u_t - u_{xx} + u_{xxxx} = 0$$
is
$$\hat{u}_t + (k^2+k^4)\hat{u} = 0.$$
As mentioned in the comments above, given an initial condition, you can find an analytic solution of this equation. For the numerical side, a classical spectral code with a well chosen time step will work very well for this linear equation. You can also compute the solution given by Winther using any FFT algorithm.


Set cell font on DataGridView before/as form is shown

Question: Background
When I hit a button on a WinForm, I am loading data into a BindingSource that serves as the data source for a DataGridView.  Once the data is loaded, I go through and make some modifications to the DataGridView; in particular, I 1) set any cells that are valued as DBNull to the string value "NULL", 2) italicize the same cells, and 3) highlight some rows.
Simple example of what I'm doing:
private void btnFetch_Click(object sender, EventArgs e)
{
    // If there's already a DataSource, Dispose of it.
    if (bsMessageTracking.DataSource != null)
    {
        (bsMessageTracking.DataSource as DataTable).Dispose();
    }

    // Get new DataSource.
    bsMessageTracking.DataSource = GetDataTable(); // Details not relevant.

    // Show NULL values.
    foreach (DataGridViewRow row in dgv.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.Value is DBNull)
            {
                cell.Value = "NULL";
                cell.Style.Font = new Font(dgv.DefaultCellStyle.Font, FontStyle.Italic);
            }
        }
    }

    // Apply highlighting.
    foreach (DataGridViewRow row in dgvMessageTracking.Rows)
    {
        if (HighlightRow(row)) // Details not relevant.
        {
            row.DefaultCellStyle.BackColor = Color.LightYellow;
        }
    }
}

The data gets loaded based on input into a TextBox on the form.
Situation
Everything works great if this occurs on the button click.  However, in order to provide some convenience to the user, I am allowing this form to get loaded with data prepopulated - the main form will instantiate this form with the data to put into the TextBox, and this btnFetch_Click handler will get called from the constructor:
internal MessageTracking(string ID)
{
    InitializeComponent();

    // Setup data source.
    dgvMessageTracking.DataSource = bsMessageTracking;

    // Set ID and run query.
    if (ID != null)
    {
        // Set ID.
        txtlID.Text = ID;

        // Run!
        btnFetch_Click(null, null);
    }
}

The value of the cells gets changed (so I see NULL), but the font and the highlighting don't stick.
What I've tried
If I replicate the highlighting code in the OnShown method, the highlighting sticks.  However, replicating the font code there doesn't work.  I can make the font stick if I put it in CellFormatting, but that seems like overkill to me, because I only need this to be run once when the form is loaded - it works fine if the process is run after the form is visible.
Plea
If anyone has any suggestions, I would appreciate them.  Thanks!
Answer: For the event handler you are using I would suggest using the dataGridView Cell_Formatting like @zimdanen. However, here is how I made it work.
    private void small8PtToolStripMenuItem_Click(object sender, EventArgs e)
    {
        fontSize = 8;
        dataGridBatchHistory.Refresh();
    }

fontSize is an integer I used to set the font dynamically and you can set most properties this way. than i would call my CellFormatting function
    private void dataGridBatchHistory_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        e.CellStyle.Font = new Font("Tahoma", fontSize);
    }

this would update my form with the new correct size upon clicking my toolstrip menu item. however i believe this works for many of the events you can create!
Answer: I guess, from the lack of responses, that there is no better way if you want the formatting shown when the form first becomes visible.  I have removed the Show NULL values portion of the btnFetch_Click handler and added this dgvMessageTracking_CellFormatting handler to handle this functionality at all times:
private void dgvMessageTracking_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.Value is DBNull)
    {
        e.Value = "NULL";
        e.CellStyle.Font = new Font(dgvMessageTracking.DefaultCellStyle.Font, FontStyle.Italic);
    }
}


How to create curved shape for email template

Question: I'm trying to create an email template, but in email (Outlook/Gmail), borderRadius isn't supported. Is there any way to create it using Canvas or any other CSS method? I can't directly use an image because it contains clickable links.
Comment: Does this answer your question? [Rounded corners in outlook without images](https://stackoverflow.com/questions/7405493/rounded-corners-in-outlook-without-images)
Comment: Noting Gmail does in fact support border-radius https://www.caniemail.com/features/css-border-radius/
Answer: I'm not an expert in HTML email but I know that tables are still used heavily, so perhaps you could build this as a table, using background images in the corner cells.
Comment: That would work. You can also just do this for Outlook desktop using conditional comments, and leave border-radius for everything else.


Ring of trigonometric functions with real coefficients

Question: Let $R$ be the ring of functions that are polynomials in $\cos t$ and $\sin t$ with real coefficients.

Prove that $R$ is isomorphic to $\mathbb R[x,y]/(x^2+y^2-1)$.
Prove that $R$ is not a unique factorization domain.
Prove that $S=\mathbb C[x,y]/(x^2+y^2-1)$ is a principal ideal domain and hence a unique factorization domain.
Determine the units of the rings $S$ and $R$. (Hint: Show that $S$ is isomorphic to the Laurent polynomial ring $\mathbb C[u,u^{-1}]$.)
Answer: (1) Send $X$ to $\cos$ and $Y$ to $\sin$. The kernel of this homomorphism consists from the polynomials $f\in\mathbb{R}[X,Y]$ with the property $f(\cos t,\sin t)=0$ for any $t\in\mathbb{R}$. Now prove that this implies $f$ divisible by $X^2+Y^2-1$: consider $f$ as a polynomial in $X$ with coefficients in $\mathbb{R}[Y]$ and write $f=(X^2+Y^2-1)g+r$, where $\deg_Xr\le 1$. Then $r=a+bX$, where $a,b\in\mathbb{R}[Y]$. From $f(\cos t,\sin t)=0$ for any $t\in\mathbb{R}$ we get that $r(\cos t,\sin t)=0$ for any $t\in\mathbb{R}$, that is, $a(\sin t)+b(\sin t)\cos t=0$ for any $t\in\mathbb{R}$. This gives us that $a^2(\sin t)=b^2(\sin t)(1-\sin^2t)$ for any $t\in\mathbb{R}$. But $a,b$ are polynomials and the last relation implies that $a^2(Y)=b^2(Y)(1-Y^2)$ and this is enough to deduce $a=b=0$ (why?).
(2) We show that $x$, the residue class of $X$ in $\mathbb{R}[X,Y]/(X^2+Y^2-1)$ is irreducible and does not divide $1+y$ and $1-y$, the residue classes of $1+Y$ and $1-Y$. (Note that in $\mathbb{R}[x,y]$ we have $x^2=(1+y)(1-y)$.)
Edit. If $x=z_1z_2$, then, by using (4) (see below) we get $N(x)=N(z_1)N(z_2)$ $\Leftrightarrow$ $Y^2-1=N(z_1)N(z_2)$. Now we have the following cases:
(i) $\deg N(z_1)=0\Leftrightarrow z_1\in\mathbb R^*$,
(ii) $\deg N(z_1)=2$ $\Leftrightarrow$ $\deg N(z_2)=0$ $\Leftrightarrow$ $z_2\in\mathbb R^*$,
(iii) $\deg N(z_1)=\deg N(z_2)=1$. If $N(z_1)=Y-1$, then $a_1^2(Y)+b_1^2(Y)(Y^2-1)=Y-1\Rightarrow Y-1\mid a_1(Y)\Rightarrow\exists a_2\in\mathbb R[Y]$ such that $a_1=(Y-1)a_2$ and pluggin this in the foregoing equation we get $a_2^2(Y)(Y-1)+b_1^2(Y)(Y+1)=1$. Looking now at the leading coefficients of $a_2$ and $b_1$ we find that one of these is zero (false!) or the sum of their square is zero (false!).
Assume that $x\mid 1-y$. Then $N(x)\mid N(1-y)\Leftrightarrow Y^2-1\mid (Y-1)^2$, a contradiction.
(3) I've proved here all you need for this part.
(4) As one can see from $(1)$ the elements of $\mathbb{R}[x,y]$ can be uniquely written as $a(y)+b(y)x$. Define a "norm" $N:\mathbb{R}[x,y]\to\mathbb{R}[Y]$ by $N(a(y)+b(y)x)=a^2(Y)+b^2(Y)(Y^2-1)$. $N$ is multiplicative and using this we get that the units of $\mathbb{R}[x,y]$ are the non-zero elements of $\mathbb{R}$.
For $\mathbb{C}[x,y]$ we can see, via the isomorphism from part $(3)$ that the invertible elements are the non-zero elements of $\mathbb{C}$, the powers of $x+iy$ and $x-iy$, and products of the non-zero elements of $\mathbb{C}$ with the powers of $x+iy$ and $x-iy$.
Answer: There is another way to think about this problem.  Since $R:= \mathbb R[x,y]/(x^2 +y^2 -1 )$ is a smooth affine curve, it is a normal ring (i.e. integrally closed in its fraction field), and so it is factorial if and only if it has trivial class group.
Here and below I will use ideas discussed in Hartshorne, Ch.II.6, in the subsection on Weil divisors.
We may consider $U :=$ Spec $R$ as an affine open curve, and then consider its projective closure $X$.  The curve $X$ is a plane conic, and so its class group (equivalently, its Picard group) is isomorphic to $\mathbb Z$, generated by the class of any rational point (e.g. the class of the point $(1,0)$).
Now $Z := X \setminus U$ is irreducible (it is a single point of $X$, which geometrically becomes two points, namely the two points at infinity $[1:\pm i: 0]$ --- note that neither of these points is individually defined over $\mathbb R$, but their union is, and so it corresponds to a single point on $X$ with residue field equal to $\mathbb C$); this is where we use that our curve is defined over $\mathbb R$ rather than $\mathbb C$.  (In the latter case $Z$ is not irreducible, but is the union of the preceding two points, which are now both defined over $\mathbb C$.)
We now use the exact sequence of Hartshorne II.6, Prop. 6.5, namely
$$\mathbb Z \to \mathrm{Cl}(X) \to \mathrm{Cl}(U) \mapsto 0,$$
where the first arrow is defined by $n \mapsto $ the class of $nZ$.
Recalling that Cl$(X) = \mathbb Z$, and that
$Z$ corresponds to a pair of points over $\mathbb C$, this
 exact sequence can be written more explicitly as
$$\mathbb Z \to \mathbb Z \to \mathrm{Cl}(U) \to 0,$$
where the first map is multiplication by $2$.
Thus Cl$(R) = $ Cl$(U) = \mathbb Z/2$, and we see that $R$ is not a UFD.
Explicitly, we see that a maximal ideal in $R$ will be principal precisely
if its residue field is equal to $\mathbb C$ (rather than $\mathbb R$).
Thus e.g. the maximal ideal $(x,y-1)$, which cuts out the point $(0,1)$ and
has residue field $\mathbb R$, is not principal.

One can think about this more geometrically:
If the maximal ideal cutting out a point $P$ over $\mathbb R$ is principal,
then it is generated by some real polynomial $f(x,y)$.  But then the ideal $(f)$ in $R$ is a product of maximal ideals corresponding to the intersection of the curve $f = 0$ with the curve $U$.  By assumption this is just the single point $P$, with multiplicity one, and so (now passing from the affine picture to the projective picture) all the other intersections must be with the two points in $Z$.   By Bezout, the total number of intersections of $f = 0$ with $X$ is even, and we are assuming the intersection of $f = 0$ with $U$ consists of the single point $P$, so in fact the number of intersections with $Z$ must be odd.  But this set of intersections (counted with multiplicity) is symmetric under complex conjugation (since $f$ has real coefficients) and so it must be even (because the two points of $Z$ are interchanged by complex conjugation).  This contradiction shows that the maximal ideal of $P$ is not principal. (This is more or less a rewriting of the proof of Hartshorne's Prop. 6.5 in this
particular case.)

It is also easy to see what happens when we extend scalars  from $\mathbb R$ to $\mathbb C$, i.e. pass from $R$ to $S$.  The set $Z$ now becomes the union of two points, and so for any point $P$ of $U$ (now over $\mathbb C$) we can find a generator of the maximal ideal by choosing $f$ to be the equation of a line passing through $P$ and one of the two points in $Z$.  E.g. for $P = (0,1)$, we can take a generator of the ideal $(x,y-1)$ to be $(y - 1 \pm ix)$.  (Either choice of sign will do; their ratio is a unit in $S$.)
In terms of the exact sequence of class groups, $Z$ is no longer irreducible,
but the union of two points each of degree one, and so the exact sequence becomes
$$\mathbb Z \oplus \mathbb Z \to \mathrm{Cl}(X_{/\mathbb C}) \to
\mathrm{Cl}(U_{/\mathbb C}) \to 0,$$
which more explicitly is $$\mathbb Z \oplus \mathbb Z \to \mathbb Z \to \mathrm{Cl}(U_{/\mathbb C}) \to 0,$$
with the first map being given just by $(m,n) \mapsto m+n$.
Evidently this map is surjective, and so
Cl$(S) =$ Cl$(U_{/\mathbb C}) = 0.$
Answer: Let me complete  YACP's excellent answer  by  describing the units of $S=\mathbb{C}[X,Y]/(X^2+Y^2-1)=\mathbb C[x,y]$.
We will use the isomorphism $\mathbb C[U,U^{-1}]\cong \mathbb C[x,y]:U\mapsto x+iy$
First note that the units of $\mathbb C[U,U^{-1}]$ constitute  the set $(\mathbb C[U,U^{-1}])^{\times}=\bigcup _{n\in \mathbb Z} \mathbb C^*U^n$ of non zero monomials.
Translating back to $S=\mathbb C[x,y]$ we obtain $$S^{\times}=\mathbb C[x,y]^{\times}=\bigcup _{n\in \mathbb Z} \mathbb C^*(x+iy)^n$$
[Don't forget that  $ ((x+iy)^n)^{-1}=(x-iy)^n$ since $(x+iy)(x-iy)=x^2+y^2=1$]
Edit: graded rings
It might be of some interest to put the problem in a  more general perspective.
In a $\mathbb Z$-graded domain  $R=\oplus_{n\in \mathbb Z} R_n$ it is immediate that units are homogeneous and from there it is obvious that  the units of $\mathbb C[U,U^{-1}]=\oplus_{n\in \mathbb Z} \mathbb CU^n$ are $(\mathbb C[U,U^{-1}])^{\times}=\bigcup _{n\in \mathbb Z} \mathbb C^*U^n$, as stated  above.
Similarly one would compute that the units of $\mathbb Z[U,U^{-1}]=\oplus_{n\in \mathbb Z} \mathbb ZU^n$ are given by $(\mathbb Z[U,U^{-1}])^{\times}=\bigcup _{n\in \mathbb Z} \mathbb \lbrace U^n,-U^n\rbrace  $.
However in a graded ring with zero divisors, units needn't be homogeneous : for example in  the ring of dual numbers $D=\mathbb C[X]/(X^2)=\mathbb C\oplus \mathbb C[\epsilon]$, the element $1+\epsilon$ is invertible (with inverse $1-\epsilon$) although it is not homogeneous.
Comment: Dear @rschwieb: I'm sorry I misled you but it is a quite common convention: the answer by user 26857 above  uses it too.  I find it elegant and less clumsy than putting overlines on letters or putting letters between brackets in quotients (but I too like Greek letters). However,   *de gustibus non est disputandum* ...
Comment: I'm a little confused: if $\Bbb C[X,Y]/(X^2+Y^2-1)=\Bbb C[x,y]$, wouldn't that mean it's *not* a PID? I'm guessing something in that line was just written incorrectly.
Comment: @rschwieb: the line is written quite correctly. The elements $x,y$ are the classes of $X,Y$ modulo the ideal $(X^2+Y^2-1)$, so that  the ring $\mathbb C[x,y]$ is not the ring of polynomials in two independent indeterminates: $x$ and $y$ are related by the algebraic equation  $x^2+y^2=1$ .
Comment: Dear Georges : I think using $\Bbb C[x,y]$ that way is really misleading, but it could just be me. Maybe if instead of $x,y$ there were $\alpha,\beta$ instead, or something less like an indeterminate, I would have caught on. Thanks for clarifying what you meant. Regards


adding new object value into existing object value over and over again

Question: I need to write a code so that result comes out as
{ username: 'Cloud',
  species: 'sheep',
  tagline: 'You can count on me!',
  noises: ['baahhh', 'arrgg', 'chewchewchew'],
  friends: [{username: 'Moo', species: 'cow'...}, {username: 'Zeny', species: 'llama'...}]
}

but my code currently prints first as the new object added onto the existing object and when I try to add another new object onto the existing object and console.log it, it replaces the last object added and only adds the new object values.
{ username: 'Cloud',
  species: 'sheep',
  tagline: 'You can count on me!',
  noises: [ 'baahhh', 'arrgg', 'chewchewchew' ],
  friends:
   { username: 'Moo',
     species: 'cow',
     tagline: 'asdf',
     noises: [ 'a', 'b', 'c' ],
     friends: [] } }
{ username: 'Cloud',
   species: 'sheep',
   tagline: 'You can count on me!',
   noises: [ 'baahhh', 'arrgg', 'chewchewchew' ],
   friends:
    { username: 'Zeny',
      species: 'llama',
      tagline: 'qwerty',
      noises: [ 'z', 'x', 'c' ],
      friends: [] } }

Here is my code so far. I only put animal2 = animal to write that it replaces it so that when adding another new object value it adds it into that object, not the original. Do I need to have a loop here in order to have this work?
function AnimalCreator(username, species, tagline, noises) {
  var list = {
    username: username,
    species: species,
    tagline: tagline,
    noises: noises,
    friends: []
  };

    return list;

}

function addFriend(animal, animal2) {

    animal.friends = animal2;
    animal2 = animal;

}

var sheep = AnimalCreator('Cloud', 'sheep', 'You can count on me!', ['baahhh', 'arrgg', 'chewchewchew']);
var cow =  new AnimalCreator('Moo', 'cow', 'asdf', ['a', 'b','c']);
addFriend(sheep, cow);
console.log(sheep);
var llama = new AnimalCreator('Zeny', 'llama', 'qwerty', ['z', 'x', 'c']);
addFriend(sheep,llama);
console.log(sheep);

What am I doing wrong?
Answer: Your problem looks to be in addFriend(animal, animal2) where you set animal2 = animal. What I think you are trying to do is append friends which could be done like
function addFriend(animal, animal2) {
    var pastFriends=animal.friends;
    pastFriends.push(animal2);
    animal.friends = pastFriends;
}


Steps for Changing the Order of the Payment Methods on Checkout

Question: I have two payment methods: Cheque and PayFlow Pro enabled for my products. However, they are showing up on the checkout form in an undesirable order:
Pay by Cheque (selected by default)
Pay by Credit Card
I'd like to reverse those and make Credit Card the default option. This question APPEARS to be answered here, but I don't understand the answer.
Would someone kindly provide the steps needed to make this happen?
Answer: Edit the payment method and click on SETTINGS on the bottom of the page.


How can I prove that two sets are isomorphic, short of finding the isomorphism?

Question: I have a set $E \subset X$ within a metric space ($X, d$).  I want to prove that it is isomorphic to $\mathbb{R}^{n \times n}$, in the sense that there exists a continuous bijection between the two.  Because $E$ is a fairly complicated set, it would be a huge pain to actually find an exact bijection, so instead I hope to identify a sufficient suite of conditions that I can test $E$ for that will suffice to show that the two are isomorphic.
Is there some sort of known method for doing this?  Or will I have to find the exact function?
Thanks.
Comment: A continuous bijection of manifolds *is* an homeomorpism, as a consequence of the theorem of Invariance of Domain. It is important here that there be no boundaries (although this extends to manifolds with compact boundaries, iirc)
Comment: What are $E$ and $X$?
Comment: It need not be the case in general, i.e. $\Bbb Q$ is not homeomorphic/isomorphic to $\mathbb{R}$.
Comment: @JonasMeyer $X$ is $\mathbb{R}^{n \times n} \times \mathbb{R}^n$ and $E$ is a strange set within that that would take a fair amount of effort to explain.  I hope to find a test suite of conditions that applies to any $E$ we might choose.
Comment: @Clayton I don't follow: I don't believe there is a continuous bijection between $\mathbb{Q}$ and $\mathbb{R}$.
Comment: @LevDub: There isn't; that is what I was getting at. If $E\subseteq\mathbb{R}$ and $E=\mathbb{Q}$, then there doesn't exist what you're asking for. You'll be better off putting in the question what it is you have and want exactly.
Comment: @Clayton Ah, I understand now.  My question is "does there exist a condition (or set of conditions) such that $E$ and $\mathbb{R}^{n \times n}$ are isomorphic iff $E$ satisfies the condition(s)?"  So it would defeat the purpose to specify $E$.
Comment: Are you sure that you only want to show that there is a continuous bijection between the two? This does not in general imply that they are homeomorphic (or isometrically isomorphic, for that matter).
Comment: @Brad that's interesting, I didn't know that.  What's an example of a continuous bijection with a non-continuous inverse?
Comment: Would a better title for your post be "what properties characterize $\Bbb R^n$ among metric spaces"?
Comment: @LevDub The map $f:[0,2\pi)\to S^1\subset\mathbb{C}$ defined by $f(t) = e^{it}$ is continuous and bijective, but its inverse is not continuous at the point $1$.
Comment: Note that your notion of "isomorphism" is not the same as the notion of isomorphism in the category of metric spaces, which is customary called "homeomorphism".
Answer: The necessary and sufficient set of conditions for $E$ to be homeomorphic to $\mathbb R^{m}$ (in your situation $m=n^2$):

$E$ must be a topological manifold of dimension $m$
$E$ must be contractible
$E$ must be simply connected at infinity

More details here.
Comment: Perfect!  This is exactly the sort of list I was hoping existed.  Thank you.
Answer: Another less general, but easier solution is that if $E \subset \mathbb{R}^n$ is a star-shaped (or less generally convex) open set, then $E$ is homeomorphic to $\mathbb{R}^n$.
Note that the converse is not true. The idea of the proof is to expand the shape radially in such a way that the map stays continuous. More details can be found here.


Capturar dados do basic profile Linkedin

Question: Estou realizando uma integração do meu app com o Linkedin, o que ocorre é que consigo realizar a autenticação e no retorno para a Activity do meu app ele me mostrasse os dados do usuário logado.
Estou usando os códigos da API do Linkedin, porém por estar iniciando ainda no desenvolvimento eu não sei aonde e como chamar o método que recupera os dados, abaixo o meu código.
Vocês podem me ajudar nisso? Só quero saber uma maneira de pegar o nome e sobrenome do usuário logado.
Desde já agradeço.
package com.example.testeli;

import com.linkedin.platform.LISession;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.APIHelper;
import com.linkedin.platform.errors.LIApiError;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.listeners.ApiListener;
import com.linkedin.platform.listeners.ApiResponse;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import com.example.testeli.R;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        final Activity thisActivity = this;

        Button linkedin = (Button) findViewById(R.id.linkedin);

        linkedin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                LISessionManager.getInstance(getApplicationContext()).init(
                        thisActivity, buildScope(), new AuthListener() {

                            @Override
                            public void onAuthSuccess() {
                                // Authentication was successful. You can now do
                                // other calls with the SDK.

                            }

                            @Override
                            public void onAuthError(LIAuthError error) {
                                // Handle authentication errors
                            }

                        }, true);

            }
        });

    }

    // Build the list of member permissions our LinkedIn session requires
    private static Scope buildScope() {
        return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Add this line to your existing onActivityResult() method
        LISessionManager.getInstance(getApplicationContext()).onActivityResult(
                this, requestCode, resultCode, data);
    }

    public void getProfile() {
        String url = "https://api.linkedin.com/v1/people/~?format=json:(id,first-name,last-name)";

        APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
        apiHelper.getRequest(this, url, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse s) {
                onApiSuccess(s);

            }

            @Override
            public void onApiError(LIApiError LIApiError) {
                // TODO Auto-generated method stub

            }

        });

    }
}

Answer: Consegui resolver o meu problema, como dito acima eu estou usando a API do linkedin onde há uma classe chamada APIResponse, pelo que eu entendi ela já realiza todo o tratamento do JSON.
Espero que que se alguém enfrentar o mesmo problema o trecho de código abaixo possa auxiliar.
public void getProfile() {
    String url = "https://api.linkedin.com/v1/people/~";

    APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
    apiHelper.getRequest(this, url, new ApiListener() {
        @Override
        public void onApiSuccess(ApiResponse s) {
            // onApiSuccess(s);
            JSONObject json = s.getResponseDataAsJson();
            try {
                String nome = json.getString("firstName");
                String sobrenome = json.getString("lastName");
                // JSONObject nome = json.getJSONObject("lastName");
                // nome.toString();

                System.out.println(nome);
                System.out.println(sobrenome);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        @Override
        public void onApiError(LIApiError LIApiError) {
            // TODO Auto-generated method stub

        }

    });

}


"The calling thread cannot access this object because a different thread owns it" error when updating UI control from different thread in WPF

Question: I've got method which I'am calling from main thread. This method is creating a new thread. Code looks like this:
MouseCursorWallObject MouseCursorWall = null;
List<MovingRectangle> MovingRectangles = null;

DrawingImage RenderedImage;

public MainWindow()
    {
        InitializeComponent();
        PrepareObjects();
        GameLoopRun();
    }

private void GameLoopRun()
    {
        Thread thread = new Thread(() =>
        {
            while (true)
            {
                DateTime dtStart = DateTime.Now;

                Events();
                Update();
                Display();

                DateTime dtEnd = DateTime.Now;
                TimeSpan ts = dtEnd - dtStart;
                if (SkipTicks - ts.TotalMilliseconds >= 0)
                {
                    Thread.Sleep((int)(SkipTicks - ts.TotalMilliseconds));
                }
            }
        });
        thread.Start();
    }

In Display() method i'am trying update Image control. "Display()" method looks like this:
private void Display()
    {
        DrawingGroup imageDrawings = new DrawingGroup();

        // Drawing main canvas
        imageDrawings.Children.Add(DrawingObject(500, 350, 0, 0, new Uri(@"Images\gameCanvas.jpg", UriKind.Relative)));

        // Drawing mouse cursor wall
        imageDrawings.Children.Add(DrawingObject(MouseCursorWall.Width, MouseCursorWall.Height, MouseCursorWall.GetLocX, MouseCursorWall.GetLocY, MouseCursorWall.DisplayTexture));

        for (int i = 0; i < MovingRectangles.Count; i++)
        {
            MovingRectangle o = MovingRectangles[i];

            // Drawing moving object
            imageDrawings.Children.Add(DrawingObject(20, 20, o.GetLocX, o.GetLocY, o.TextureUri));
        }

        if (GamePause == true)
        {

        }
        RenderedImage = new DrawingImage(imageDrawings);

        // Image control on main UI thread
        renderImage.Dispatcher.Invoke(() =>
        {
            renderImage.Source = RenderedImage;
        });
    }

The problem is when I'am trying update Image control using Dispatcher.Invoke I'am receiving error "The calling thread cannot access this object because a different thread owns it". I was trying a lot of different options, and only one  works fine:
private void Display()
    {
        this.Dispatcher.Invoke(() => {
            DrawingGroup imageDrawings = new DrawingGroup();

            // Drawing main canvas
            imageDrawings.Children.Add(DrawingObject(500, 350, 0, 0, new Uri(@"Images\gameCanvas.jpg", UriKind.Relative)));

            // Drawing mouse cursor wall
            imageDrawings.Children.Add(DrawingObject(MouseCursorWall.Width, MouseCursorWall.Height, MouseCursorWall.GetLocX, MouseCursorWall.GetLocY, MouseCursorWall.DisplayTexture));

            for (int i = 0; i < MovingRectangles.Count; i++)
            {
                MovingRectangle o = MovingRectangles[i];

                // Drawing moving object
                imageDrawings.Children.Add(DrawingObject(20, 20, o.GetLocX, o.GetLocY, o.TextureUri));
            }

            if (GamePause == true)
            {

            }

            RenderedImage = new DrawingImage(imageDrawings);
            renderImage.Source = RenderedImage;
        });

    }

Could You explain me why second option of "Display()" method works fine, but the first one throwing exception? What I'am doing wrong?
Comment: I found that topic already.
Comment: Ok, well you may be able to get the first example to work if you .Freeze() the DrawingImage first, but you should probably create it on the UI thread (as per your second example).
Answer: Both the DrawingImage and the DrawingGroup inherit from DispatcherObject, which means that they need to be accessed from the thread on which they were created.  That is why your version where all of the work is invoked back to the dispatcher works correctly.
As pointed out by Brian Reichle, these object also inherit from System.Windows.Freezable, which you can leverage to allow cross thread access to the objects.
Comment: "... inherit from DispatcherObject, which means that they need to be accessed from the thread on which they were created." ... unless they happen to be frozen.
Comment: Thanks for Your reply! I'am going to check that now.


Clarity Design sidenav can't scroll when content exceeds view

Question: So I'm currently using the sidenav, but when the nav links exceed the view I can't scroll to see the "hidden" links unless I zoom out.
I'm using Angular 5 as a frontend framework and this is how I arranged the components:

  <students>
  </students>

Inside the students component:

    Alumnos

        {{ student.number }} - {{ student.name }}

        Agregar alumno

I'm not sure if I'm missing anything since I followed the docs and expected to get the scrolling option.
Answer: Are you using the layout correctly? More info about the layout can be found here: https://vmware.github.io/clarity/documentation/v0.11/app-layout
Please take a look at this StackBlitz: https://stackblitz.com/edit/clarity-light-theme-v11-mkudjf?file=app/app.component.html
The layout markup is:

    Header

      Content Area

       ...

The .sidenav goes after the .content-area
EDIT:
Please note that the Clarity team recommends you use Vertical Nav instead of the sidenav. The documentation for vertical nav is here: https://vmware.github.io/clarity/documentation/v0.11/vertical-nav/basic-structure/charmander
Comment: Yeah, I just made sure that the `.sidenav` is after `.content-area` inside `.main-container`, everything is used correctly. I can try using the vertical nav but I'm not sure how that will look along with the full markup.
Comment: Did you also check the `.content-container`? Could you replicate this on a StackBlitz?
Comment: If you use vertical nav, it will go in place of the sidenav (right after the content area)


Rule condition to check which language is used by the visitor?

Question: I have a multilingual website (English, Spanish).
Is there any way to create a rule condition to compare the language used by the visitor against a fixed value?
The condition would something like: if language is English then go ahead with the actions.
Answer: Seemed like a useful thing to have.
I created a patch for Rules, adding this functionality. I posted it in the Rules issue queue. That seemed better than providing the code directly here, as this way you can still use it anyway that suits you, yet it may actually get into core Rules.
Also see this question, "How do I add a new condition in Rules 2?".
Comment: I was about to do a quick write up for this functionality, yours was pretty much what i was aiming for. I'd do a +2 for adding it as a patch for Rules if I could.
Comment: Awesome that you added this as a patch to Rules.
Answer: Actually there are two ways for that:
1- The easy one :
Add new condition select Data comparison and in the parameter:

Parameter: Data to compare: [site:current-page:language], Data value: English

2- The Hard one:
/*
* Implements hook_rules_condition_info().
*/

function MODULE_NAME_rules_condition_info() {
 $conditions = array();

 $conditions['MODULE_NAME_check_current_user_language'] = array(
   'label' => t('Current user language'),
   'group' => t('YOUR GROUP NAME'),
   'parameter' => array(
     'language' => array(
       'type' => 'token',
       'label' => t('Language'),
       'description' => t('Select language that will be compared against the
user current language.'),
       'options list' => 'entity_metadata_language_list',
       'default value' => LANGUAGE_NONE,
     ),
   ),
 );

 return $conditions;
}

Then:
/*
*  Compare site current language with required language
*/

function MODULE_NAME_check_current_user_language($required_language) {
 global $language;

 return $language->language == $required_language;
}

Don't forget to clear the cache.
Answer: You can implement a new condition in a module, using the following implementation of hook_rules_condition_info().
function mymodulename_rules_condition_info() {
  return array(
    'check_current_user_language' => array(
      'label' => t('Language for current user'),
      'parameter' => array(
        'string' => array(
          'type' => 'text',
          'label' => t('Language to check'),
        ),
      ),
    ),
  );
}

function mymodule_check_current_user_language($string) {
  global $user, $language_content;

  return ($user->language == $string);
}

Comment: And what do you do when the german language is added?
Answer: One of the rules maintainers, fago, has a patch under development (started recently and marked as "needs work") that adds a variety of internationalization features to rules, including functions for checking the language of users as well as setting languages for rules themselves.
Answer: You can find this function in the I18n bundle for translating.
In rules use date comparison
Answer: You can try to accomplish this adding additional field to profile and using 2 different rules.
1st will set the value of the field, using this functions
2nd will compare the profile field value using account:profile_lang data selector
Comment: I assume this requires use of eval()?


textContentType=oneTimeCode not working for iOS

Question: Well, it used to work, but after I modified some styles and added other components, it stopped working.
This is the non-working version of the OTP:
import React, { useContext, useEffect, useState } from 'react'
import { StyleSheet, View } from 'react-native'
import { ScrollView } from 'react-native-gesture-handler'
import {SafeAreaView} from 'react-native-safe-area-context'
import styled from 'styled-components/native'
import { CodeField, Cursor, useBlurOnFulfill, useClearByFocusCell } from 'react-native-confirmation-code-field'
import SmsRetriever from 'react-native-sms-retriever'
import {Button} from '../../components/button/button'
import {Text} from '../../components/text'
import { Breakpoint } from '../../components'
import {useHttp} from '../../hooks/use-http/use-http'
import {authService} from '../../api/auth.service'
import {Auth} from '../../models/auth.model'
import { OTPScreenProps } from './otp.props'
import { extractOTP } from '../../utils/extract-otp'
import { message } from '../../utils/message-handler'
import { AuthContext } from '../../contexts/auth/auth.context'
import chevronLeftIcon from '../../assets/icons/chevron-left-icon.png'
import { TouchableOpacity } from 'react-native-gesture-handler'

const CELL_COUNT = 6

const Container = styled(SafeAreaView)`
  flex: 1;
  background-color: ${({theme}) => theme.colors.background.primary};
`

const Content = styled.View`
  align-items: center;
  z-index: 1;
  padding-horizontal: ${({ theme }) => theme.spacing[7]}px;
`

const Keyboad = styled.KeyboardAvoidingView.attrs({
  behavior: 'position'
})`
  padding-bottom: 85px;
`

const BackButtonContainer = styled.View`
  align-self: flex-start;
  padding-horizontal: ${({ theme }) => theme.spacing[7]}px
  padding-top: ${({ theme }) => theme.spacing[7]}px
  z-index: 2;
`

const BackButton = styled.Image.attrs({
  source: chevronLeftIcon
})`
  width: 12px;
  height: 21px;
  tint-color: white;
`

export const OTPScreen = ({ route, navigation }: OTPScreenProps) => {
  const phone = route.params && route.params.phone || '6203221059'
  const [firstOTPSent, setFirstOTPSent] = useState<boolean>(true)
  const { setAuth } = useContext(AuthContext)
  const [code, setCode] = useState('')
  const ref = useBlurOnFulfill({ value: code, cellCount: CELL_COUNT })
  const [inputProps, getCellOnLayoutHandler] = useClearByFocusCell({
    value: code,
    setValue: setCode,
  })
  const [sendOTP, { loading: sendingOTP }] = useHttp<{ message: string }>(
    () => authService.sendOTP(phone),
    async (_, err) => {
      if (err) message.danger('otp.sentError')
      else if(!firstOTPSent) message.info('otp.sent')
    }
  )
  const [confirmOTP, { loading }] = useHttp<Auth>(
    (otp: string) => authService.confirmOTP(phone, otp),
    async (auth, err) => {
      if (err) message.danger('otp.loginError')
      else setAuth(auth)
    }
  )

  useEffect(() => {
    if(phone) {
      sendOTP()
      setFirstOTPSent(false)
    }
  }, [])

  useEffect(() => {
    if(sendingOTP) listenToSMS()
  }, [sendingOTP])

  const listenToSMS = async () => {
    try {
      const registered = await SmsRetriever.startSmsRetriever()
      if (!registered) return
      SmsRetriever.addSmsListener(event => {
        if(event && event.message) {
          const otp = extractOTP(event.message)
          if(otp) {
            setCode(otp)
            confirmOTP(otp)
          }
        }
        SmsRetriever.removeSmsListener()
      })
    } catch (error) {}
  }

  return (
    <Container>
      <BackButtonContainer>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <BackButton />
        </TouchableOpacity>
      </BackButtonContainer>

      <ScrollView keyboardShouldPersistTaps="handled">
        <Keyboad>
          <Content>
            <Breakpoint spacing={12} />
            <Text tx="otp.confirmIdentity" color="tertiary" preset="h5" bold/>
            <Breakpoint spacing={14} />
            <Text tx="otp.enterCode" color="tertiary" preset="h5" opacity={0.7} align="center">
              <Text color="tertiary" preset="h5" bold> {phone.slice(-4)}</Text>
            </Text>
            <Breakpoint spacing={2} />
            <Button
              preset="link"
              tx="otp.again"
              textProps={{
                color: '#71A1F4',
                preset: 'h4',
                bold: true,
                opacity: 0.7
              }}
              onPress={sendOTP}
              loading={sendingOTP}
            />
            <Breakpoint spacing={16} />
            <CodeField
              ref={ref}
              {...inputProps}
              value={code}
              rootStyle={styles.root}
              onChangeText={setCode}
              cellCount={CELL_COUNT}
              keyboardType="number-pad"
              textContentType="oneTimeCode"
              onEndEditing={() => confirmOTP(code)}
              renderCell={({index, symbol, isFocused}) => (
                <View
                  onLayout={getCellOnLayoutHandler(index)}
                  key={index}
                  style={[styles.cellRoot, isFocused && styles.focusCell]}>
                  <Text style={styles.cellText}>
                    {symbol || (isFocused ? <Cursor /> : null)}
                  </Text>
                </View>
              )}
            />
            <Button
              style={{ width: '100%' }}
              onPress={() => confirmOTP(code)}
              tx="otp.login"
              disabled={code.length < 6}
              textProps={{ uppercase: true }}
              loading={loading}
            />
          </Content>
        </Keyboad>
      </ScrollView>
    </Container>
  )
}

const styles = StyleSheet.create({
  root: {
    marginBottom: 36,
    width: '75%',
    height: 55
  },
  cellRoot: {
    flex: 1,
    marginHorizontal: 5,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: '#71A1F4',
    borderBottomWidth: 2
  },
  cellText: {
    color: 'white',
    fontSize: 38,
    textAlign: 'center',
  },
  focusCell: {
    borderBottomColor: '#007AFF'
  },
});

And this is the working version:
import React, { useContext, useEffect, useState } from 'react'
import { StyleSheet, Dimensions, View } from 'react-native'
import {SafeAreaView} from 'react-native-safe-area-context'
import styled from 'styled-components/native'
import { CodeField, Cursor, useBlurOnFulfill, useClearByFocusCell } from 'react-native-confirmation-code-field'
import SmsRetriever from 'react-native-sms-retriever'
import {Button} from '../../components/button/button'
import {Text} from '../../components/text'
import { Breakpoint } from '../../components'
import {useHttp} from '../../hooks/use-http/use-http'
import {authService} from '../../api/auth.service'
import {Auth} from '../../models/auth.model'
import { OTPScreenProps } from './otp.props'
import { extractOTP } from '../../utils/extract-otp'
import { message } from '../../utils/message-handler'
import { AuthContext } from '../../contexts/auth/auth.context'
import chevronLeftIcon from '../../assets/icons/chevron-left-icon.png'
import { TouchableOpacity } from 'react-native-gesture-handler'

const CELL_COUNT = 6

const Container = styled(SafeAreaView)`
  background-color: ${({theme}) => theme.colors.background.primary};
  height: 100%;
`

const Keyboad = styled.KeyboardAvoidingView.attrs({
  behavior: 'padding'
})`
  align-items: center;
  height: ${Dimensions.get('window').height}px;
  padding: 25px;
`

const BackButtonContainer = styled.View`
  align-self: flex-start;
`

const BackButton = styled.Image.attrs({
  source: chevronLeftIcon
})`
  width: 12px;
  height: 21px;
  tint-color: white;
`

export const OTPScreen = ({ route, navigation }: OTPScreenProps) => {
  const phone = route.params && route.params.phone || '6203221059'
  const [firstOTPSent, setFirstOTPSent] = useState<boolean>(true)
  const { setAuth } = useContext(AuthContext)
  const [code, setCode] = useState('')
  const ref = useBlurOnFulfill({ value: code, cellCount: CELL_COUNT })
  const [inputProps, getCellOnLayoutHandler] = useClearByFocusCell({
    value: code,
    setValue: setCode,
  })
  const [sendOTP, { loading: sendingOTP }] = useHttp<{ message: string }>(
    () => authService.sendOTP(phone),
    async (_, err) => {
      if (err) message.danger('otp.sentError')
      else if(!firstOTPSent) message.info('otp.sent')
    }
  )
  const [confirmOTP, { loading }] = useHttp<Auth>(
    (otp: string) => authService.confirmOTP(phone, otp),
    async (auth, err) => {
      if (err) message.danger('otp.loginError')
      else setAuth(auth)
    }
  )

  useEffect(() => {
    if(phone) {
      sendOTP()
      setFirstOTPSent(false)
    }
  }, [])

  useEffect(() => {
    if(sendingOTP) listenToSMS()
  }, [sendingOTP])

  const listenToSMS = async () => {
    try {
      const registered = await SmsRetriever.startSmsRetriever()
      if (!registered) return
      SmsRetriever.addSmsListener(event => {
        if(event && event.message) {
          const otp = extractOTP(event.message)
          if(otp) {
            setCode(otp)
            confirmOTP(otp)
          }
        }
        SmsRetriever.removeSmsListener()
      })
    } catch (error) {}
  }

  return (
    <Container>
      <Keyboad>
        <BackButtonContainer>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <BackButton />
          </TouchableOpacity>
        </BackButtonContainer>
        <Breakpoint spacing={12} />
        <Text tx="otp.confirmIdentity" color="tertiary" preset="h5" bold/>
        <Breakpoint spacing={14} />
        <Text tx="otp.enterCode" color="tertiary" preset="h5" opacity={0.7} align="center">
          <Text color="tertiary" preset="h5" bold> {phone.slice(-4)}</Text>
        </Text>
        <Breakpoint spacing={2} />
        <Button
          preset="link"
          tx="otp.again"
          textProps={{
            color: '#71A1F4',
            preset: 'h4',
            bold: true,
            opacity: 0.7
          }}
          onPress={sendOTP}
          loading={sendingOTP}
        />
        <Breakpoint spacing={16} />
        <CodeField
          ref={ref}
          {...inputProps}
          value={code}
          rootStyle={styles.root}
          onChangeText={setCode}
          cellCount={CELL_COUNT}
          keyboardType="number-pad"
          textContentType="oneTimeCode"
          onEndEditing={() => confirmOTP(code)}
          renderCell={({index, symbol, isFocused}) => (
            <View
              onLayout={getCellOnLayoutHandler(index)}
              key={index}
              style={[styles.cellRoot, isFocused && styles.focusCell]}>
              <Text style={styles.cellText}>
                {symbol || (isFocused ? <Cursor /> : null)}
              </Text>
            </View>
          )}
        />
        <Button
          style={{ width: '100%' }}
          onPress={() => confirmOTP(code)}
          tx="otp.login"
          disabled={code.length < 6}
          textProps={{ uppercase: true }}
          loading={loading}
        />
      </Keyboad>
    </Container>
  )
}

const styles = StyleSheet.create({
  root: {
    marginBottom: 36,
    width: '75%',
    height: 55
  },
  cellRoot: {
    flex: 1,
    marginHorizontal: 5,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: '#71A1F4',
    borderBottomWidth: 2
  },
  cellText: {
    color: 'white',
    fontSize: 38,
    textAlign: 'center',
  },
  focusCell: {
    borderBottomColor: '#007AFF'
  },
});

Besides that I haven't changed anything else not updated anything. The only big difference I can see between these 2 versions is that I added a ScrollView, apart from that, I simply modified some styles and changed the KeyboardAvoidingView component position.
Answer: check the SMS you're sending : in my case, in french,

Veuillez saisir le code ${code} dans l'application is working
Veuillez entrer ce code dans l'application : ${code} is NOT working

I've been checking RN side for hours, and finally changing the SMS was the solution.
Comment: that worked for me as well! Thanks a lot. Seems like the code must be in the end of SMS and without any characters like `:` before it. Just took a look how my banking app SMS look like.
Comment: mmm not sure, apple's message is like `Your Apple ID code is: 123456. Do not share it with anyone. @apple.com #123456 %apple.com`


GLM conditional distribution from R GLM

Question: I want to obtain the full distribution of a Gamma (or Inverse Gaussian) distributed $y_i$ given a vector of $\bar x_i$ that have been used in the linear predictor of a coefficient. Suppose also for the Gamma GLM I have used the log-link instead of the canonical link.
Since both distributions are bi-parametric I know I can get the estimation of the mean parameter by predict(glmObj, ..., type="response") whichever distribution whichever link I have used. I'm not sure about the conditional variance. I know that $var\left(y_i\right)=\phi*V\left(\mu_i\right)$. My questions are:

Is it correct to estimate $\phi$, the dispersion parameter, as the square root of glmObj$deviance/glmObj$df.residual, regardless of the distribution and canonical link?
Is $V\left(\mu_i\right)$ dependent on the canonical link?
Comment: You can get "standard errors" (not prediction errors) from `predict` using the argument `se.fit=TRUE`. It doesn't give you their covariance, however. Any two predicted values are a function of a linear combination of regression parameters. These usually aren't independent. It is easy to compute by hand, however.
Comment: The estimate of $\phi$ from GLMs is generally not ML (it is in some cases, but usually not); indeed in some cases the ML estimate doesn't even make sense (Poisson regression for example). The package MASS includes functions for ML estimation of the parameter corresponding to $\phi$ in one or two cases (such as the Gamma). As for 'correct' -- it depends on what you mean by 'correct'.
Comment: If you want to estimate the dispersion parameter $\phi$, where $\phi\ne 1$ then u need to use the quasi-likelihood approach. For example for the poisson glm, u need something like: `glm(y ~ x, family =quasipoisson(link = "log"))`. When the $\phi=1$, then the quasi-likelihood will be the ML estimate.
Answer: 1- the estimation of phi can be obtained by
Over_disp <-  sum(residuals(glmobj, type="pearson")^2)/glmobj$df.res    which is different from the deviance
2- given Y~EF{b(theta) , a(phi)}
d( d( b(theta) ))/dtheta^2 if a canonical link is used gives the variance function
V(mu)= V(d(b(theta))/dtheta) = V(linear predictor) i.e. it does not depend upon the link.

GLM conditional distribution from R GLM


How to show one of five videos at same location after specific link selection?

Question: I have five 5 divs, on hover of those div i am displaying content in a dialogue box right to it... right to dialogue box i want to put video of respective divs..
on hover of div1 it should show 1st video, on hover of 2nd div it should show 2nd video and so on...
So how to display different videos at same place on hover of respective divs???
Following is screenshot:

Please reply as early as possible..
Thanks in advance...
Answer: If you are using one video object you can change the src property.
Haven't tested this yet, but it looks promising ...
Approach 1: store your video url's in an array
var initVideos = function(){
    var videos = ["http://urlVideo1.flv", "http://urlVideo2.flv", ...],
        videoArea = $("#videoArea"),
        divs = $("ul li div"); // or some other selector for your HTML

    // bind your hover event to the divs
    divs.hover(
        // mouseover
        function(){
            videoArea.show();
            videoArea.find("object > embed").prop("src", videos[$(this).index()]);
        },
        // mouseout
        function(){
            videoArea.hide();
        }
    );
};

// once the DOM is ready
(function(){
    initVideos();
});

demo: http://jsfiddle.net/tive/J6WQm/
To finetune this you should change src only after loading the previous event was completed.
Otherwise when you hover too fast the browser might generate too much re-flow.
Also depending on the object you use code can vary. For the moment I'm only triggering the embed object (mozzila browsers) but the object (IE) should also be triggered on param movie value.
To counter these different objects program logic people used swf object to generate that code block for you. Now this has been outdated quite some time.
Therefor a more suitable approach may be to use flashembed
Approach 2: use the href property from the links in the menu
var initVideos = function () {
    var divs = $("ul li a");

    // bind your hover event to the divs
    divs.mouseenter(
        // mouseover
        function () {
            flashembed("videoArea", $(this).prop("href"));
        });
    };

    // once all is loaded
    $(window).load(function () {
        initVideos();
    });

demo: http://jsfiddle.net/tive/Ff7Mq/
Unfortunatly this library didn't work in jsfiddle. also up to jquery 1.7 support.
Perhaps someone knows an up-to-date plugin.
EDIT: only CSS was required to make it work ^^
Comment: Its working... video is embeded... but how to show the content of respective tab in the middle dialogue box as shown in above screenshot..
Comment: Are you talking about an extra layer shown with the source information of the video? Or where do you need to fetch your video url's from?
Comment: no there is one orange border box inbetween link and video... there i want to display some information about video... there will be 5 different information of 5 videos... those also should be displayed on respective tab hover...
Comment: You would fetch the extra content with a jquery selector and pass it to another jquery selector `.html()` or `.text()`.
Comment: I've updated the second fiddle, take a look to see if this is something you require.
Comment: Principle remains the same!
Answer: I have made one simple fiddle as per your requirement. Please check below link.

http://jsfiddle.net/vvbsr/2/
Comment: This doesn't look like an answer, more like a comment.


Custom method for field

Question: I used cookiecutter django to create a project and django builder for my first app to get up and running quickly. I'm using crispy forms and I want to replace the default checkbox with an image.
I have a model with only boolean fields - I want to display images depending on the field is set true or false in the form.
I got a function which maps the column name to a image path which I can use in the template but I have no idea how to do it without adding a function call to the template
Ideally I would have a field.image method which I can insert in the src element, my function call looks like this
image_src = image_path(field.label)

And as I see the best access to the field.label is in this template.
Thats my custom template I want to use
{% load crispy_forms_field %}

  {% crispy_field field 'class' 'custom-control-input' %}

This is my forms.py
    class ProtectiveEquipmentForm(forms.ModelForm):
        class Meta:
            model = ProtectiveEquipment

        def __init__(self, *args, **kwargs):
            self.helper = FormHelper()

            self.helper.layout = Layout(
                Fieldset(
                'first arg is the legend of the fieldset',
                Field('head_protection', 'eye_protection',
                       'template="graphical_checkbox.html"),
                template="graphical_checkbox_list.html"
                ),
                ButtonHolder(
                    Submit('submit', 'Submit', css_class='button white')
                )
            )
            super(ProtectiveEquipmentForm, self).__init__(*args, **kwargs)

Answer: got if working with custom filter
from django import template
from django.template.defaultfilters import stringfilter

from .utils import name_to_image_path

register = template.Library()

@register.filter
@stringfilter
def image_uri(value):
    return name_to_image_path(value)

and then in the template {{ form.label | name_to_image_path }}
more info here:
https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/

Custom method for field


Python typing: Creating Tuple type at runtime

Question: I want to create a type that is a tuple that contains 5 floats and an int. I can do this in the following way which works nicely.
from typing import Tuple

MyT = Tuple[float, float, float, float, float, int]
t: MyT = (1.0, 1.0, 1.0, 1.0, 1.0, 5)

But if I want even more floats it will become annoying having to type the same over and over. Is there a way to create such a type in a parametrized way? I know that passing a tuple to Tuple[] works as well, i.e.
MyT = Tuple[(float, float, float, float, float, int)]
t: MyT = (1.0, 1.0, 1.0, 1.0, 1.0, 5)

Therefore, I tried the following.
tup = ((float, ) * 5) + (int, )
MyT = Tuple[tup]

t: MyT = (1.0, 1.0, 1.0, 1.0, 1.0, 5)

But this fails type checking with mypy. I guess it is because the tuple that is passed to Tuple[] is created only at runtime? Is there a similar way that would work?
Tested using Python 3.8.6 and MyPy 0.782.
Comment: You can use `Tuple[float, ...]` to accept any number of numeric values.  (See [here](https://stackoverflow.com/q/43957034/3282436) regarding whether to use `int`/`float` for the type parameter.)  It doesn't make sense to create type hints at runtime since they are designed for linters to validate pre-runtime.
Comment: it assumes all are float. there is int in the type.
Comment: Note, passing a tuple doesn't work "as well", it's already what you are doing here: `Tuple[float, float, float, float, float, int]`, i.e., the commas make the tuple, not the parentheses in `Tuple[(float, float, float, float, float, int)]`. In any case, what is it that you are trying to avoid, exactly? Why would you have to type this over-and-over, it looks like you are already using an alias, wouldn't you just use the alias over and over?
Comment: Does this answer your question? [Specify length of Sequence or List with Python typing module](https://stackoverflow.com/questions/44833822/specify-length-of-sequence-or-list-with-python-typing-module)
Answer: There is no way to automate the process of creating a tuple type hint or to create a tuple type where the number of items is parameterizable: you need to write out all five float types manually like you did in your first example.
Instead, I recommend you create a class instead:
class MyT:
    def __init__(self, a: List[float], b: int) -> None:
        self.a = a
        self.b = b

You can express this class more compactly using dataclasses if you prefer:
from dataclasses import dataclass

@dataclass
class MyTVersion2:
    a: List[float]
    b: int

Using either a class or dataclass should let you directly support storing a variable number of floats while also making the structure of your data easier for others to understand.
If it's important that you use specifically a tuple, I think the only options you have are to:

Settle for manually writing creating a new type alias for each kind of tuple you want to use.
Settle for something like Tuple[Any, ...]. Doing Tuple[float, ...] may also actually work for your specific example -- iirc mypy considers ints to be a subtype of floats.


Descriptive Statistics: Should I exclude an outlier?

Question: In my study that I am writing up for university:
There were a total of 204 participants, 96 female (47.1%) and 108 male (52.9%). The participants were aged between 20 and 125.
The problem I have is 125 is older than the oldest verified person. Do I include this in my descriptive statistics, and in the general data analyses, or do I exclude from descriptive and data analyses?
Tips would be most welcome!
Comment: It sounds as if that you know that the value is wrong. You surely would have noticed a person of that age in your survey. Perhaps it's facetious; perhaps it's a slip for 25. If I were you, I'd replace it with missing.
Comment: The survey was conducted over the web, so there was no face to face interaction. How would you justify it with 'missing'?
Comment: The value is wrong and you don't know what value is right; so you enter missing. Let's play a child-like game: my height in 4 metres. Do you believe my height? What height would you enter for me if you trusted the rest of the data on me? I'll readily buy an argument that the entire observation should be struck if someone appears to be messing with the survey.  You'll find that's what happens by default with many programs unless you apply multiple imputation.
Answer: You should also look at the rest of that person's data---does it fall within the expected min/max for the questions that you asked? Did they give the same response to every question? Is there an obvious pattern of responding going on? Without knowing what you asked, it's hard to give more specific guidance. But because you are at university, and your sample is likely all university students, I think it's likely the 125 is not accurate. I would just treat age as missing (at minimum), and examine whether that participant's whole row should be discarded. If you want to really impress your teacher, you could run your analyses (depending on what you're running) both including and excluding that person, to see how influential that person is, e.g. https://onlinecourses.science.psu.edu/stat501/node/337


Basic & quick question about confidence interval (novice)

Question: I'm writing a research proposal and I need to include an estimation of what kind of sample size would be adequate.
I've used a calculator, and I get the result that with a 95% confidence interval and 5% confidence level, the sample size should be at least 384. I don't know my population but I know that it's very large, and I've read that if that's the case, the population size is irrelevant and the answer will always be 384.
Is this correct, and do I need to explain this logic in a research proposal? Are a 95% confidence interval and a 5% confidence level adequate for most studies? (clinical trial in question).
I know the questions are very basic - I'm a complete beginner. Would be so grateful for any help.
Comment: I think what I'm trying to do here is to find out how many people are needed for the study so the results are valid (/significant?). I've got to where I am now by using the "determine sample size" calculator on http://www.surveysystem.com/sscalc.htm
Comment: If you are the OP, please register & merge your accounts (you can find information on how to do
this in the **My Account** section of our [help]), then you will be able to
edit & comment on your own question.
Answer: Caveat: I am answering the question I think you're asking. It's somewhat unclear, so this may be inaccurate.
The calculator you are using is asking for the confidence interval for a proportion - for example, "87% of Respondents are X +/- 3%". That "3" is what goes in the confidence interval section. It appears you put in "5" there, and yes, for arbitrarily large population that number will continue to be 384 (you can prove this to yourself by putting different population values into the calculator).
However, I have a couple concerns:

Do you know your population is actually "very large"? What is your population? "Very large" isn't well defined.
You haven't talked about your actual study at all. We cannot answer for you if that's correct for "most studies" because it will very much depend on what you're actually asking. You should have most of your analysis plan already in place before you start trying to calculate your needed sample size.
Sample size calculations are often somewhat tricky - do you have an advisor or someone else who could talk you through this?


Mutate question to label data in three categories

Question: I have data in a numerical format and I would like to label them into three levels - "low", "med", "high" based on their quantile

low, <50% pencentile
med, 50% < 75% pencentile
high, > 75% pencentile

This is my R output
 quantile(data$crim)
       0%       25%       50%       75%      100%
 0.006320  0.082045  0.256510  3.677083 88.976200

I use mutate to label them, below is my R code. I got the "high" for all data.
 newdata<-mutate(data, crim.lev = ifelse(crim %in% 0:0.26, "low",
                                           ifelse(crim %in% 0.27:3.68, "med",
                                                   "high")))

Please let me anything I missed, or other method to do this. Thanks.
Answer: I suggest cut is a better fit here. It only calculates the quantiles once, does not do row-by-row comparisons (as in the case of case_when), and no nested-ifelse.
quantile(mtcars$disp, c(0, 0.5, 0.75, 1))
#    0%   50%   75%  100%
#  71.1 196.3 326.0 472.0

mtcars %>%
  mutate(lev = cut(disp, c(-Inf, quantile(disp, c(0, 0.5, 0.75, 1))[-1]),
                   label=c("low", "med", "high"))) %>%
  select(disp, lev)
#     disp  lev
# 1  160.0  low
# 2  160.0  low
# 3  108.0  low
# 4  258.0  med
# 5  360.0 high
# 6  225.0  med
# 7  360.0 high
# 8  146.7  low
# 9  140.8  low
# 10 167.6  low
# 11 167.6  low
# 12 275.8  med
# 13 275.8  med
# 14 275.8  med
# 15 472.0 high
# 16 460.0 high
# 17 440.0 high
# 18  78.7  low
# 19  75.7  low
# 20  71.1  low
# 21 120.1  low
# 22 318.0  med
# 23 304.0  med
# 24 350.0 high
# 25 400.0 high
# 26  79.0  low
# 27 120.3  low
# 28  95.1  low
# 29 351.0 high
# 30 145.0  low
# 31 301.0  med
# 32 121.0  low

The use of -Inf is because cut is typically left-open, and its only alternative is right-open (so either the min or the max will be omitted ... so I replace the min with something that should be below the actual values).
Answer: We can use case_when with quantile function to divide data into groups. Using it with built-in mtcars dataset on mpg column.
library(dplyr)

mtcars %>%
  mutate(group = case_when(mpg < quantile(mpg,0.5) ~ 'low',
                      between(mpg, quantile(mpg, 0.5), quantile(mpg, 0.75))~'med',
                      TRUE ~ 'high'))

#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb group
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4   med
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4   med
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1   med
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1   med
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2   low
#6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1   low
#7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4   low
#8  24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2  high
#....

Answer: That's what cut() is designed for. Example:
res <- cut(iris$Sepal.Length, breaks=c(0, quantile(iris$Sepal.Length)), labels=seq(0, 1, .25))
head(res)
# [1] 0.25 0.25 0.25 0.25 0.25 0.5
# Levels: 0 0.25 0.5 0.75 1

Comment: This assumes all data is positive, otherwise it will produce mis-leading results.
Comment: @r2evans Yes, that was perhaps a good thing to note.


RGL surface plot from data frame

Question: I've created a nice plot using scatter3d() and Rcmdr. That plot contains two nice surface smooths. Now I'd like to add to this plot one more surface, the truth (i.e. the surface defined by the function generating my observations minus the noise component).
Here is my code so far:
library(car)
set.seed(1)

n <- 200 # number of observations (x,y,z) to be generated
sd <- 0.3 # standard deviation for error term
x <- runif(n) # generate x component
y <- runif(n) # generate y component

r <- sqrt(x^2+y^2) # used to compute z values

z_t <- sin(x^2+3*y^2)/(0.1+r^2) + (x^2+5*y^2)*exp(1-r^2)/2 # calculate values of true regression function

z <-  z_t + rnorm(n, sd = sd) # overlay normally distrbuted 'noise'
dm <- data.frame(x=x, y=y, z=z) # data frame containing (x,y,z) observations
dm_t <- data.frame(x=x,y=y, z=z_t) # data frame containing (x,y) observations and the corresponding value of the *true* regression function

# Create 3D scatterplot of:
# - Observations (this includes 'noise')
# - Surface given by Additive Model fit
# - Surface given by bivariate smoother fit

scatter3d(dm$x, dm$y, dm$z, fit=c("smooth","additive"), bg="white",
          axis.scales=TRUE, grid=TRUE, ellipsoid=FALSE, xlab="x", ylab="z", zlab="y")

The solution given in another thread is to then define a function:
my_surface <- function(f, n=10, ...) {
  ranges <- rgl:::.getRanges()
  x <- seq(ranges$xlim[1], ranges$xlim[2], length=n)
  y <- seq(ranges$ylim[1], ranges$ylim[2], length=n)
  z <- outer(x,y,f)
  surface3d(x, y, z, ...)
}

f <- function(x, y)
  sin(x^2+3*y^2)/(0.1+r^2) + (x^2+5*y^2)*exp(1-r^2)/2

my_surface(f, alpha=0.2)

This however yields an error, saying (translated from German since this is my system language, I apologize):
Error in outer(x, y, f) :
  Dimension [Product 100] does not match the length of the object [200]

I then tried an alternative approach:
x <- seq(0,1,length=20)
y <- x
z <- outer(x,y,f)
surface3d(x,y,z)

This does add a surface to my plot but it doesn't look right at all (i.e. the observations are not even close to it). Here's what the supposed true surface looks like (this is obviously wrong):
Thanks!

I think the problem may in fact be scaling. Here I created a couple of points that sit on the plane z = x+y. Then I proceeded to try to plot that plane using my method above:
library(car)

n <- 50
x <- runif(n)
y <- runif(n)
z <- x+y

scatter3d(x,y,z, surface = FALSE)

f <- function(x,y)
  x + y

x_grid <- seq(0,1, length=20)
y_grid <- x_grid
z_grid <- outer(x_grid, y_grid, f)
surface3d(x_grid, y_grid, z_grid)

This gives me the following plot:

Maybe one of you can help me out with this?
Comment: You asked a simillar question, for which you received a good answer, but you have *never* voted on, or accepted an answer. This will make people unwilling to help you because you give nothing back to the community. Read the [**Help**](http://stackoverflow.com/help) and the [**About**](http://stackoverflow.com/about) page to see how SO is *supposed* to work.
Comment: +1 for taking the time to edit this question. This is now a great reproducible example./
Comment: @HaskellElephant I never said anything about *my* choices. I simply pointed out that persons may be unwilling to help when they see a user has never pointed. Where do you draw that conclusion from? That aside, at the point at which I left the comment the question included no code and no reproducible example. Now I see the OP has left a great reproducible example, and has a better sense of the community because they have accepted an answer (which by their own admission solved their problem). So my comment enriched the community and the OPs experience of it. More involvement  = better.
Answer: The scatter3d function in car rescales data before plotting it, which makes it incompatible with essentially all rgl plotting functions, including surface3d.
You can get a plot something like what you want by using all rgl functions, e.g. plot3d(x, y, z) in place of scatter3d, but of course it will have rgl-style axes rather than car-style axes.

RGL surface plot from data frame


Area-preserving

Question: A diffeomorphism $\varphi: S \to \bar{S}$ is said to be area-preserving if the area
of any region R \subset S is equal to the area of $\varphi(R)$. Prove that if $\varphi$ is
area-preserving and conformal, then ϕ is an isometry.
I have two ideas for this excersise. First, i consider a parametrization $x: U \to R \subset S$ and $\bar{x}:\varphi \circ x : X(U) \to \varphi(X(U)) $ a parametrization for $\bar{S}$. We can note that if $\varphi$ is area-preserving then $A(R)=A(\varphi(R))$. Here, i can use the definition of Area with respect to its partial derivatives and then we have that
$$A(R)=\int\int_{R}||x_{u} \times x_{v}||dudv$$
But for $\bar{S}$
$$A(\varphi(R))=\int\int ||(\varphi \circ x)_{u} \times (\varphi \circ x)_{v}||dudv$$
here i'm stuck, because i'dont know how to proceed with $A(\varphi(R))$ or how to describe the partial derivatives of the composition or use the hypotesis that $\varphi$ is conformal, i'm sure that conformal does not implies that coeficients of x and $\bar{x}$ are $\lambda$ - times of another, i.e, $\bar{E}=\lambda  E, \bar{F}= \lambda F, \bar{G}= \lambda G$, so i don't know what to do here. Another idea for this is use the definition of area with respect to first fundamental form but here the only way to develop this idea is using the wrong assumption about coefficients that i was talking about. I appreciate some idea.
UPDATE
i want to be sure that this attempt is good. I will proof that
$$d\varphi_{q}(x_{u})=\bar{x}_{u}$$
where $x_{u}$ and $\bar{x}_{u}$ are the partial derivatives of x and $\bar{x}$ respectively.
Now,for $(u_{0},v_{0}) \in U$ and $q=x(u_{0},v_{0}) $ and $\alpha$ a curve defined as $x(u,v_{0})=\alpha(u)$, therefore $\alpha'(u)=x_{u}(u,v_{0})$. Now, we have that
$$d\varphi_{q}(x_{u}(u_{0},v_{0}))=d\varphi_{q}(\alpha'(u_{0}))=(\varphi \circ \alpha)'(u_{0})$$
then we have that
$$d\varphi_{q}(x_{u}(u,v_{0}))=d\varphi_{q}(\alpha'(u))=(\varphi \circ \alpha)'(u)$$ for all $u$
but now, we can note that
$$(\varphi \circ \alpha)(u)=\varphi(\alpha(u))=\varphi(x(u,v_{0})=(\varphi \circ x)(u,v_{0})=\bar{x}(u,v_{0})$$
so, finally we have that
$$(\varphi \circ \alpha)'(u,v_{0})=\bar{x}_{u}(u,v_{0})$$
and we can conclude that
$$(\varphi \circ \alpha)'=d\varphi_{q}(x_{u})=\bar{x}_{u}$$
this is enought or this proof is wrong?
Comment: Roughly speaking, due to conformality, the two Riemannian metrics are related by a multiple by a positive function. The volume elements are related by this function raised to some power (related to the manifold's dimension). Now area-preserving implies that the function has to be $1$ identically (one needs to invoke a form of the fundamental lemma of calculus of variations), so you have an isometry.
Answer: Let's say $(M,g)$ and $(\overline{M},\overline{g})$ are two Riemannian manifolds of the same dimension $n$, and $\phi:M\to \overline{M}$ is a diffeomorphism which is conformal and $n$-volume preserving (the volume being the Riemannian volume). We'll show that $\phi$ is in fact an isometry.
First, by assumption of $\phi$ being conformal, it follows that there is a smooth positive function $f:M\to (0,\infty)$ such that $\phi^*(\overline{g})=f\cdot g$. Now, for any (nice enough $n$-dimensional) region $U\subset M$, we have the volume of $U$ equals the volume of $\phi[U]$. Let us evaluate the volume of $\phi[U]$:
\begin{align}
\text{vol}(\phi[U])&:=\int_{\phi[U]}1\,dV_{\overline{M},\overline{g}}\\
&=\int_U(1\circ \phi)\cdot dV_{M,\phi^*(\overline{g})}\tag{change of variables}\\
&=\int_U1\,dV_{M,fg}\\
&=\int_U1\cdot f^{n/2}\,dV_{M,g},
\end{align}
where I have used the change of variables theorem on a Riemannian manifold, and in the final step, I used the fact that $dV_{M,fg}=f^{n/2}\,dV_{M,g}$ (this is clear from the local coordinate formula $dV_{M,g}=\sqrt{|\det g_{ij}|}\,|dx^1\wedge\cdots\wedge dx^n|$, so if you replace $g$ by $fg$, the determinant gets multiplied by $f^n$, so taking square root gives $f^{n/2}$).
So far, we have calculated the volume of $\phi[U]$ as an integral over $U$. By hypothesis, this integral is equal to the volume of $U$, i.e
\begin{align}
\int_Uf^{n/2}\,dV_{M,g}&=\int_{U}1\,dV_{M,g},
\end{align}
and this equality is supposed to hold for all nice enough regions $U$ (e.g all Borel sets $U$). If two integrals are equal for "all nice regions", then the two integrands must be identical; this is essentially the fundamental lemma of calculus of variations (in $n$-dimensions). Thus, $f^{n/2}=1$ identically on $M$, and hence $f=1$. Thus proves $\phi$ is an isometry.

Edit: Specialized version
Parametrize the surface $S\subset\Bbb{R}^3$ as you have, $x:U\subset\Bbb{R}^2\to x[U]\subset S$. Your "first fundamental form" gives you a $2\times 2$ symmetric matrix of inner products
\begin{align}
[g_{ij}]&=\begin{pmatrix}
\langle\frac{\partial x}{\partial u},\frac{\partial x}{\partial u}\rangle &
\langle\frac{\partial x}{\partial v},\frac{\partial x}{\partial u}\rangle\\
\langle\frac{\partial x}{\partial u},\frac{\partial x}{\partial v}\rangle&
\langle\frac{\partial x}{\partial v},\frac{\partial x}{\partial v}\rangle
\end{pmatrix}
\equiv
\begin{pmatrix}
E&F\\
F&G
\end{pmatrix},
\end{align}
where $E,F,G:U\to\Bbb{R}$ are smooth functions (such that the determinant $EG-F^2$ is nowhere vanishing).
Now, since $\phi$ is a diffeomorphism, you get a parametrization $\overline{x}=\phi\circ x$ of $\overline{S}$. With respect to this parametrization, as in your update, the chain rule tells you that for each $p\in U$, $\frac{\partial \overline{x}}{\partial u}(p)=d\phi_{x(p)}\left(\frac{\partial x}{\partial u}(p)\right)$, and likewise with $v$. In words, the tangent vector $\frac{\partial x}{\partial u}(p)\in T_{x(p)}S$ is mapped via $d\phi_{x(p)}:T_{x(p)}S\to T_{\phi(x(p))}\overline{S}=T_{\overline{x}(p)}\overline{S}$ to the tangent vector $\frac{\partial \overline{x}}{\partial u}(p)\in T_{\overline{x}(p)}\overline{S}$. So, we have
\begin{align}
\left\langle \frac{\partial \overline{x}}{\partial u^i}(p),\frac{\partial \overline{x}}{\partial u^j}(p)\right\rangle_{\overline{x}(p)}
&=
\left\langle d\phi_{x(p)}\left(\frac{\partial x}{\partial u^i}(p)\right), d\phi_{x(p)}\left(\frac{\partial x}{\partial u^i}(p)\right)\right\rangle_{\phi(x(p))}\\
&= \lambda^2(p)
\left\langle \frac{\partial x}{\partial u^i}(p),\frac{\partial x}{\partial u^j}(p)\right\rangle_{x(p)}.
\end{align}
The first line is by the computation we just made, and the second line is the definition of conformality.
Here, for convenience, I have set $(u^1,u^2)=(u,v)$. This is saying precisely that
\begin{align}
\begin{pmatrix}
\overline{E}&\overline{F}\\
\overline{F}&\overline{G}
\end{pmatrix}
&=\lambda^2
\begin{pmatrix}
E&F\\
F&G
\end{pmatrix}.
\end{align}
Finally, the norm of the cross product is $\|x_u\times x_v\|=\sqrt{EG-F^2}$. Put all of this together, and try to mimic what I said above.
(btw what I call $\lambda^2$ here (since this is how doCarmo writes it) is what I called $f$ in my original answer).
Comment: Hello, my problem is that I haven't studied anything about manifolds, so I don't understand what you did. Could you give me a hint or an outline of how the proof would be in the context of 3- dimensional real space? $R^{3)$
Comment: @LMOTRU whenever I say manifold, just imagine you have a 2-dimensional surface in $\Bbb{R}^3$. When I say Riemannian metric, think first fundamental form. Also, the determinant I mention is "$EG-F^2$", which is nothing but the magnitude of the cross product.
Comment: And volume Will be the área that Is the Double integral by Definition? My book Is do carmo
Comment: @LMOTRU yes. $n$-dimensional volume, as I have called it here, is simply the area, which is defined by a double integral when $n=2$ (and based on your post you seem to know this idea :)
Comment: Also, although I did the computations "abstractly" you can just as easily do each step within a parametrization and do it there with formula's you're familiar with.
Comment: I'm having trouble with the calculations specifically. I took the parameterization as I did in my attempt, and I'm still stuck trying to find the partial derivatives of

u and

v. I don't understand how to use the coefficients of the first fundamental form here
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/146510/discussion-between-peek-a-boo-and-lmotru).
Comment: @LMOTRU you don't need to evaluate any partial derivatives. You have $x_u,x_v$ and likewise with bars. From here you get your $E,F,G$ and likewise with bars. These guys are related by a positive multiple (im sure do carmo mentions something about conformality and the relationship in terms of local coordinates).
Comment: yeah, proposition 2 page 230 sec 4.2 say some like this but i am not sure that Conformal implies that these coefficientes are related by a positive multiple
Comment: that is true (especially since you're taking the two parametrizations to be the ones related to each other by composing with $\phi$), and you should verify it. If you had taken an arbitrary parametrization for $S$ and a completely unrelated one for $\overline{S}$, then it would not be the case, but you're taking $x$ and $\phi\circ x$, which is why things work out.
Comment: Exactly, and this parametrization $\varphi \circ x$ is the selected for me in my attempt. but how can i work with this? how can i get that for example $\bar{E}=\lambda E$  for $\bar{E} $ and $E$ coefficients of first fundamental form of  $\varphi \circ x$ and  x respectively? here we need partial derivatives but i dont know how to work with this here, and to take advantage of the fact that $\varphi$ is conformal. i'm sure that this can be used in some moment finding the coeffientes we use this fact but i don't know how can i use this.
Comment: @LMOTRU I just updated
Comment: Great! now, i want to know something, why $\frac{\partial  \bar{x}}{\partial u}(p)=\partial \varphi_{(x(p))}(\frac{\partial  x}{\partial  u}(p))$ this is the key question and the principal problem for me. the other things for me are so clearly.
Comment: @LMOTRU that's the chain rule/ definition of the differential as a map between tangent spaces, and you pretty much wrote it in more detail using curves in your update.
Comment: does that mean that my proof about that expression in my update is correct?
Comment: @LMOTRU yes it looks correct (a little long for my taste, but that's neither here nor there:)
Comment: A shorter proof is welcome :D I think it would help me a lot to understand these notations
Comment: @LMOTRU I would have written essentially the same thing you did, but in 2 lines. Or I would just give a "proof by knowledge" and say the equality is true (this is a very advanced proof technique:) Jokes aside, what you did is fine.
Comment: thanks a lot!! you are the best!

Area-preserving


How to correctly express a variable with two solutions?

Question: Say we have $(x+1)(x+2) = 0$.
So possible solutions of $x$ are $x=-1$, and $x=-2$;
Would it be considered correct syntax to say "$x = -1, -2$" ?
Comment: $x = -1 \land -2$ could be read as $x$ is equal to $-1$ and $-2$, which is a contradiction. Mathematics should be written in natural language with symbols as means to simplify otherwise complicated expressions.
Comment: You can write $x\in\{-1,\,-2\}$
Comment: I would write $x=-1\vee x=-2$.
Comment: Mathematical symbols are shorthand for analogous natural language sentences. I would say: "The values of $x$ that satisfy the equation $(x+1)(x+2)=0$ are $-1$ and $-2$."
Comment: The comma usually means "and". Use an "or" if you want to be precise. In this case however it is "clear from the context".
Comment: @Cleric In that case, couldn't that have been expressed as  "$x = -1 \land -2$"?
Answer: Mathematics should be written using natural language with symbols being used as a means to simplify otherwise convoluted expressions or due to conventions. For example:
"If the product of a number times itself plus three times the number plus two is equal to zero, then the number is either negative one or negative two."
is more clearly rewritten as:
"$x^2+3x+2=0$ implies $x=-1$ or $x=-2$".
This should help you view mathematics as a dialogue rather than a programming language of sorts.


Quais são as ferramentas(API's, bibliotecas, frameworks) necessárias para criação de gráficos e relatórios?

Question: Estou querendo pegar dados por exemplo de um banco de dados e desenvolver gráficos desse tipo, segue a figura abaixo:

Se possível em vários formatos em pizza, em barras etc. E depois gerar um relatório desse tipo que possar ser salvo, por exemplo no formato .pdf ou .doc:
Comment: Pedro, acabei pesquisando e vi que existe um SDK do Jasper Report. Ele é apenas um cliente de um servidor Jasper. Da uma olhada em http://community.jaspersoft.com/project/mobile-sdk-android
Comment: Pedro, você pode usar alguma das bibliotecas de gráficos open-source, tem uma lista diversa neste site: https://android-arsenal.com/tag/40. Para o relatório em formato de tabela você pode usar um `TableLayout` ou um `ListView`.
Comment: @Wakim vou dar uma olhada.. em aplicacoes pra desktop java eu usava ireport pra ter relatorios personalizados... e possivel utilizar no android?
Comment: Que eu saiba não é possível, são plataformas diferentes, não sei se o jasper reports rodaria no Android, vale a pena uma busca...
Comment: Olá, Pedro. Genericamente falando, sua pergunta não é ruim, mas para o formato do SOpt tem dois problemas; Um é que é um pouco ampla, pois vai depender muito do uso individual e gosto de cada um, pois Android é uma plataforma bem abrangente. O outro problema é que essas coisas mudam muito, e mesmo que alguém ponha uma pergunta bem completa, ela ficará desatualizada em bem pouco tempo. Não veja voto de fechamento como crítica, é apenas uma forma de organização e adequação. E em outros aspectos, suas perguntas andam melhorando, com a experiência vc pega o jeitão da coisa!.
Comment: @Bacco wryel me respondeu o que eu queria...
Comment: @PedroRangel eu já tinha visto a resposta, geralmente não voto correndo justamente para dar tempo de alguém solucionar o problema imediato para o autor. Mas há uma grande probabilidade que a resposta dada vá ficar desatualizada com o tempo, como comentei.
Comment: @Bacco de boas..
Answer: Algumas API's de gráficos/report para android:

AndroidPlot
Android GraphView
AChartEngine
ChartDroid
Google Charts (HTML 5)

API para escrever PDF dentro do android:

Android PDF Writer
iText (para aplicativos comerciais, requer licença)
Se você estiver acima da API 19, pode optar por dar uma olhada na documentação

Para escrever uma simples imagem com texto como a que você citou, você pode usar a API Bitmap do própio Android.
Comment: +1 pela sua resposta.. obrigado