Why am I getting negative means from a hierarchical clustering model fitted to binomial data using RStan

Question: Apologies in advance - I'm new to Bayesian statistical methods and may not get all the terminology correct.
I am trying to run some Bayesian analysis on survey data using the rstan package in R but I'm unsure of how to interpret my output. My aim is to generate a probability distribution for each level of data depending on the response, where the response has predictors variables and there are levels in the data.
The response data I'm inputting are binomial but the resulting probability distribution of the posterior has negative values.
My data are structured as follows:

3524 responses (N)
23 geographical areas sampled treated as levels (L) where each response is associated with an area (ll)
each area is scored 1-10 depending on it's level of deprivation and this is treated as a predictor variable (x[,1])
the age group of each responder is treated as a predictor variable (x[,2])
there are two predictor variables (D)
yes or no response to a question in the survey (y)

So for each responder I have a response (1 = yes, 0 = no), a geographical area (1-23), a level of deprivation (1-10) and an age group (1-8 where 1 is the youngest age group and 8 is the oldest).
I'm trying to fit a hierarchical logistical model as follows:
data {
  int<lower=1> D;
  int<lower=0> N;
  int<lower=1> L;
  array[N] int<lower=0, upper=1> y;
  array[N] int<lower=1, upper=L> ll;
  array[N] row_vector[D] x;
}
parameters {
  array[D] real mu;
  array[D] real<lower=0> sigma;
  array[L] vector[D] beta;
}
model {
  for (d in 1:D) {
    mu[d] ~ normal(0, 100);
    for (l in 1:L) {
      beta[l, d] ~ normal(mu[d], sigma[d]);
    }
  }
  for (n in 1:N) {
    y[n] ~ bernoulli(inv_logit(x[n] * beta[ll[n]]));
  }
}

I then run the model using the following code:
fit = stan(model_code=bern.stan, data=list(y=y, N=N, x=x, D=D, L=L, ll=ll), iter=5000)

I can print the fit as follows:
print(fit, probs=c(0.1, 0.9))

The print shows that the mean for each beta is negative (e.g., beta[2,1] where 2 is the level and 1 is the predictor variable age is -0.17). When I extract these data to plot the distribution it is negative.
My question is how can the mean and credible intervals be negative when I'm dealing with binomial data and positive predictor variables?
Comment: Betas are the logistic regression's coefficient, they have normal prior distributions thus negative values are admissible.
Answer: Probabilities cannot be negative, but as said in the comment, this is a logistic regression model, and if you transformed them using inv_logit, as your model does, they would not go outside the bounds.


What is integrating a variational equation?

Question: This continues from How to understand the largest Lyapunov exponent?
It is said that we can differentiate the equation,
$$\tau\frac{dh_i}{dt} = F_i = -h_i + \sum_{j=1}^N J_{ij} \phi(h_j),$$
against $h_j$, and get
$\frac{\partial F_i}{\partial h_j}|_{t=t_s} -\delta_{ij} + J_{ij} \phi'(h_j(t_s))$ (we denote this Jacobian as $D_{ij}(t_s)$).
This is to get the Jacobian (the first order derivative of $f$ in $x'=f(x)$).  Is this step (differentiating the right side against arbitrarily chosen variable) mathematically robust?

It is said that

Briefly, calculating the Lyapunov
spectrum involves two steps:
First, we evolve an initially orthonormal system Q in the
tangent space along the trajectory using the Jacobian D.
To this end, the variational equation $\tau$Q = D(t)Q has to
be integrated..

Why is the equation called 'variational'? (Possibly because variation methods deal with small perturbation of an integrand of an integral, or other functionals, and Q is such a perturbation.)
Is 'integrating' the equation here the same as solving the equation (and therefore get the integral curve)?

Here is the orginal paper:
Comment: Note that there is a dot in $\tau\dot Q=D(t)Q$, it partially overlaps the lower bow of the "g" above it.
Comment: Thanks for pointing that out. But then it confuses me that Q is perturbation (i.e. $dh_i$), then the left side of equ1 should be $\tau$Q, why $\dot Q$?
Comment: I see it is because if we use Taylor exp. then we have $\delta F(x)= F(x+\delta x) - F(x) = F'(x)\delta x$, not (as I had thought to be) $F(x) = F'(x) \delta x$ (I thought $F(x+\delta x) = F(x), F(x)=0$). So the left side should be $\dot {(x+\delta x)} - \dot x=\dot {\delta  x} (= \dot Q c)$, where $c$ is the representation of direction.
Comment: Yes. (You notice the problem with using $δ$ as a symbol for a difference vs. as one of the infinitesimal parameters. When in doubt, I'd use it as a number and write $x=x_0+δ·x_1+δ^2·x_2+...$ for the perturbation series.)
Comment: Right. Above I used $\delta$ for a difference. If so, more strictly, it should be $\delta F(x)= F(x+\delta x) - F(x) = F'(x)\delta x+O((\delta x)^2) \\ \quad = \frac {D(t)Qc +O((\delta x)^2)} \tau \\ \quad =\dot {(x+\delta x)} - \dot x=\dot {\delta  x} (= \dot Q c)$
Answer: For any differential equation $\dot x=F(x)$, $x_0=x_0$, the variation of the initial point $x_0+\delta·v_0$ produces a close-by solution $x(t)+δ⋅v(t)$. Here $v(t)$ will also depend on $δ$ internally. If one wants to compute the leading term of $v$, then one can use the linearized equation
$$
\dot v=\frac{F(x+δ⋅v)-F(x)}{δ}\xrightarrow{δ\to 0}F'(x)·v.
$$
(If $F$ is sufficiently smooth.) As this equation describes how variations of the initial point develop, it may be called the variational equation.
Comment: So 1) it is because the tangent Q is perturbation / variation. 2) from $\dot x=F(x)$ we can (by replacing $x$ with $x+\delta x$ and using the linearity of $\frac{d}{dt}$) deduce an equation of $\dot {\delta  x}$, i.e. $\delta F(x)$, which equals  $F'(x)\delta x$ (Taylor expansion). $\n$ Let $\delta x =\epsilon v$.//As far as I know variation equation often involves a constant like $\epsilon$ times variation (**right?**), which does not explicitly exist in the original equ of Q.
Comment: Yes. But $Q$ is more the generating matrix for all perturbations, $δx=\varepsilon\,Qc$ where the parameter vector $c$ selects the initial direction of the perturbation and $\varepsilon$ the size of the deviation from $x$.
Comment: Yes. The columns of $Q$ can be regarded as tangents/perturbations in various independent directions (or basis for tangents). $\hspace{1em}$ Why do we need $\epsilon$, which seems redundant to me, since varying the norm of $v$ would be exactly $\epsilon v$
Comment: Because it is easier to think with only one infinitesimal quantity. The idea is that $c$ or $v(0)$ is fixed and the perturbation is approximated by partial sums of the perturbation series for $ε\to 0$, $$δx=εQ_1[c]+ε^2Q_2[c,c]+....$$ Again, limits in one variable are easier to think about than simultaneous limits in multiple directions.
Comment: ..Correction: 'by replacing  with + and using the linearity of $\frac d{dt}$'.. and substracting $x$ from +


Roots of monic polynomial $f(x)\in\Bbb Z[x]$ are integers if rational [monic Rational Root Test]

Question: Suppose we have a polynomial with degree $n$ and all the coefficient are integers, with the leading coefficient $+1$ or $-1$. Are the roots only either integer or complex number?
Answer: If by "complex" you mean "non-real", the answer is no. For example, $x^2-2$ satisfies your conditions, and it has two noninteger real roots.
What is true is that any rational root must be an integer; this follows from the Rational Root Theorem, since given
$$f(x) = a_nx^n+\cdots + a_1x+a_0,\qquad a_i\in\mathbb{Z},\ a_n\neq 0,$$
if a rational number $r=\frac{p}{q}$ written in lowest terms ($p,q\in\mathbb{Z}$, $\gcd(p,q)=1$) is a root of $f(x)$, then $p|a_0$ and $q|a_n$. In particular, if $a_n=\pm 1$, then $q=\pm 1$, so $r\in\mathbb{Z}$.
That is, the roots of the polynomial you describe are either integers, or irrational.
Comment: @David Probably the remarks will prove helpful to other readers who may not be aware of this more general denotation of "irrational".
Comment: or non-real ...
Comment: @David Above, "irrational" is used not only for reals but generally, i.e. it simply means "not rational", i.e. $\not\in \mathbb Q$. This is quite common usage in university-level algebra. So there is no need to add the remark "or non-real".
Comment: @David See also my [2006/3/8 sci.math post](http://groups.google.com/group/sci.math/msg/d828f6ae6ca06d4d) where I note that if one searches books.google.com for "irrational algebraic" you'll find such usage by many eminent mathematicians: e.g. Conway, Gelfond, Manin, Ribenboim, Shafarevich, Waldschmidt (esp. in diophantine approximation, e.g. Thue-Siegel-Roth theorem, Gelfond-Schneider theorem, etc). See also other posts in that thread "Is i irrational"?
Comment: @BillDubuque Yes, that makes sense of course. In fact, all the usual definitions of "irrational" I can find are "a real number is irrational if..."; whereas here "irrational" can be interpreted in a   literal sense, that is, "not rational", as you mentioned in your first comment. Should I delete the comment?
Answer: It's  the Rational Root Test specialized to $\rm\color{#c00}{monic}$ polynomials, i.e. with leading coefficient $\color{#c00}{c= \pm1}$. By the Theorem a reduced rational root $\,r\,$ has denominator dividing lead coeff $\color{#c00}{c= \pm1}$ so $\,r\in\Bbb Z$.
The RRT is usally proved by evaluating at a reduced fraction $\rm\:a/b,\:$ clearing denominators, then noting  this implies  $\rm\:b\ |\ a^n,\:$ contra $\rm\:gcd(a,b) = 1,\:$ via unique factorization, or Euclid's Lemma.
However, it is worth remarking that this has an alternative proof by induction on degree, by constructively proving that: if $\rm\:a/b\:$ is a root of a monic $\rm\:f_n\in \mathbb Z[x]\:$ of degree $\rm\:n,\:$ then $\rm\:a/b\:$ is  a root of a monic $\rm\:f_{n-1}\in \mathbb Z[x]\:$ of degree $\rm\:n-1.\:$ Thus, by induction, $\rm\:a/b\:$ is a root of a linear monic $\rm\:x - n\in\mathbb Z[x],\:$ hence $\rm\:a/b = n\in \mathbb Z.\:$ For example, below is the reductive proof of irrationality of cube-roots to square-roots. The general case is no more difficult, see here.
THEOREM $\ $ If $\rm\ r^3\: =\: m\in \mathbb Z\ $ then $\rm\ r\in \mathbb Q\ \Rightarrow\ r\in\mathbb Z$
Proof $\quad \rm r = a/b \in \mathbb Q,\ \ \gcd(a,b) = 1\ \Rightarrow\ ad-bc \;=\; 1\;$  for some $\:\rm c,d \in \mathbb{Z}\;\;$ by Bezout.
Thus $\rm\ 0\: =\: (a-br)\: (dr^2+cr) \: =\: r^2 + ac\ r  - bdm \ $ so $\rm\ r\in\mathbb Z\ $ by the quadratic case. $\ $ QED


How can I get the ID of div inside a div wrapper. Jquery

Question: I have a div that looks like this:

and I have a function that can append in data div:
function loadStaticBar(data) {
     let pl_name= `bar-${data.title.replace(/\s+/g, '-').toLowerCase()}`
        $('#data').append(`

        `)
}

The content of loadStaticBar(data) is a key and value it's a details for charts:
{id: 453, title: 'Bar Chart Example', select: 'bar-form', xtitle: 'Values', ytitle: 'Date', …}

Now, I'm trying to get all the IDs with the class static. I have tried:
$('#data').find('.static')

And I get S.fn.init [prevObject: S.fn.init(1)] inside of this are bunch of information. How can I get the IDs of the div that containing static class like this.
ids = [line-plot, bar-plot]

Comment: Can you also give us some indication about the possible content of your `data` object that is passed into the `loadStaticBar()` function?
Comment: I updated it sir
Answer: The answer to the updated question could be:

function loadStaticBar(data) {
 let pl_name= `bar-${data.title.replace(/\s+/g, '-').toLowerCase()}`
    $('#data').append(`

    `)
}
const data={id: 453, title: 'Bar Chart Example', select: 'bar-form', xtitle: 'Values', ytitle: 'Date'};

$(function(){
 loadStaticBar(data); // create the divs first !!!
 const ids=$("#data .static").get().map(el=>el.id);
 console.log(ids);
});

As you want to receive a "proper" array instead of a jQuery object it makes sense to .get() the selected DOM elements first and then .map() them using the standard Array-method.
Incidentally, you can solve the originally posted question also without jQuery:

document.addEventListener("DOMContentLoaded", function () {
 const ids=[...document.querySelectorAll("#data .static")].map(el=>el.id);
 console.log(ids);
});

Comment: I'm getting an empty array
Comment: In case your script is placed above the `` element you should place the place the action into a `$(function(){ ... })` that runs after the DOM is loaded.
Comment: I tried your answer inside  below the body. I also updated my question. Still now getting the ids


Can a static class extension be inlined?

Question: I have a tendency (throw back to c++ days) to add inlining hints to small methods, for example:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(this IProject @this, IComponent component)
{
    @this.Components.Add(component);
}

I was wondering whether a static class extension-methods could be inlined in the first place?
Comment: Do you really need those micro-optimizations? It's not C++ days anymore, you can trust your compiler. Moreover inlining hints should normally be placed on larger methods which you think the compiler won't inline. But the outcome is probably in the nanoseconds anyway.
Comment: Isn't it better to get rid of that habbit at the first place?
Comment: The question is still perfectly valid even if we disagree with the use-case of it.
Comment: Probably not. But the attribute is there, the functionality is there. Its a legitimate question.
Comment: It's become a bad habit to question developers' judgement, especially when it comes about optimization. There are lots of cases where the slightest optimization makes a difference. C# was not made with the same mindset as C++ but that's precisely the reason to want to optimize wherever possible. Among other areas C# is now used in gaming industry where operations/calls could get as high as tens of thousands and not per second but at 60, even 90 frames per second.
Thank you for understanding.
Comment: Why would static methods be excempt from inlining?
Comment: Did not say it was not a legit question. Only that you should really rethink your scenario, in a maintenance point of view. You're probably wasting more time writing one inlining attribute than it will ever save in your program's entire life.
Answer: Static methods can be inlined. See here for information on how to check if a method is being inlined. Extension methods are no different from normal static methods; in IL they are just decorated with a System.Runtime.CompilerServices.ExtensionAttribute, so they will be treated the same by the JIT.


Laplacian operator

Question: I need to find A,$\alpha$,C $\in \mathbb{R}$ so that $u:\mathbb{R}^n \to \mathbb{R}$ of the form $u(x) = A||x||^\alpha + C $
satisfies $\Delta u(x) = ||x||^2$ and $u(0) = -1$.
This question gets very messy. I end up with terms that can potentially cancel but they both depend on A and $\alpha$ and i cannot satisfy what is required.
Comment: Consider writing the Laplacian in spherical coordinates and note that the functino $u(x) = Ar^\alpha + C$ is radially symmetric, so all terms except the $\partial/\partial r$ part of $\Delta$ vanish.
Answer: Let $v \colon \def\R{\mathbb R}\R^n \to \R$ be defined by $\def\norm#1{\left\lVert#1\right\rVert}v(x) = \norm x^\alpha = (\sum_i x_i^2)^{\alpha/2}$ we have for $1 \le j \le n$
\begin{align*}
  \partial_j v(x) &= \frac{\alpha}2\cdot\left(\sum_i x_i^2\right)^{\alpha/2-1}\cdot 2x_j\\
    &= \alpha x_j \cdot \left(\sum_i x_i^2\right)^{\alpha/2-1}\\
  \partial_j^2 v(x) &= \alpha \left(\sum_i x_i^2\right)^{\alpha/2 - 1}
         + \alpha x_j^2 (\alpha - 2)\left(\sum_i x_i^2\right)^{\alpha/2 - 2}
\end{align*}
Hence
$$ \Delta v(x) = \sum_j \partial_j^2 v(x) = \alpha\norm{x}^{\alpha - 2} + \alpha(\alpha - 2)\norm x^2 \norm x^{\alpha - 4} = \alpha(\alpha - 1)\norm x^{\alpha - 2}$$
Hence, as $u = Av + C$, we have
$$ \Delta u(x) = A\alpha(\alpha - 1) \norm x^{\alpha - 2}$$
So $\alpha = 2$, that is $\alpha(\alpha - 1) = 12$, which gives $A = \frac 1{12}$, and as $\norm 0 = 0$ we must have $C = -1$.
Answer: This is a straightforward exercise in differentiation:
$$\Delta u = \nabla \cdot \nabla u = \nabla \cdot A\alpha\|x\|^{\alpha-1}\frac{x}{\|x\|}=\nabla \cdot A\alpha\|x\|^{\alpha-2}x$$
Now by the chain rule
\begin{align*}
\Delta u &= A\alpha (\alpha-2)\|x\|^{\alpha-3}\frac{x}{\|x\|}\cdot x + A\alpha \|x\|^{\alpha-2}n\\
&= A\alpha(\alpha-2)\|x\|^{\alpha-2} + A\alpha n\|x\|^{\alpha-2}\\
&= A\alpha(\alpha+n-2)\|x\|^{\alpha-2}.
\end{align*}
To get $\|x\|^2$ we meed $\alpha=4$, and $4A(2+n)=1$. Therefore
$$A = \frac{1}{8+4n}.$$
Lastly we easily get $u(0)=-1 \Rightarrow C=-1.$

Laplacian operator


The HAYSTACK_SITECONF setting is no longer used & can be removed

Question: I'm using Haystack search (latest version) and Django 1.3.
The getting started docs say to have a HAYSTACK_SITECONF setting, but when I try to manage.py syncdb, I get the error The HAYSTACK_SITECONF setting is no longer used & can be removed.. Removing the setting then tells me that The HAYSTACK_CONNECTIONS setting is needed, but that isn't in the docs at all.
Are the docs outdated or did I mess up my install?
Answer: Your link points to a 1.2.5 beta documentation while HAYSTACK_CONNECTIONS appears to be a v2.0 alpha setting.
If you're using the development version of software you should generally expect documentation to be lacking. I personally use the stable releases that won't change on me unless I absolutely need one of the newer features (like django 1.4's new filterspecs).
http://readthedocs.org/docs/django-haystack/en/latest/tutorial.html


IE 10 missing Proxy GPO settings

Question: Is there any way to remove the users possibility to change the proxy settings from IE 10 with GPO ?
In IE 9 you had the "Disable Changing Proxy Settings" setting in \Administrative templates\Windows Components\Internet Explorer. So even if i don't have IE maintenance anymore with IE 10, i would still be able to use GPP to set proxy settings and then deny users the ability to change them with the "Disable Changing Proxy Settings". This settings is however also missing now with IE 10 ?
So how can i prevent the users from changing the proxy settings that i can now only set with GPP ?
I would like to avoid having to use something like IEAK 10 for this.
Best Regards
Answer: Microsoft wants you to use the User Configuration Preferences in GPOs {link}.
In the GPO, go to User Configuration | Preferences | Control Panel Settings, and create a new IE10 CP setting for your users.
Be aware of the green and red dashed settings though {link}
Comment: Once this is set, you can set/force disable modifications on proxy settings (Policies | Admin Templates | Windows Components | Internet Explorer | "Disable change proxy settings")
Answer: Well. Thanks for the reply, but you didn't answer my question about how to prevent the user from changing the settings after they are set with GPP.
The answer is that the "disable changing proxy settings" setting from IE 9 and earlyer versions, under \User settings\Administrative Templates\Windows Components\Internet Explorer..\, has been replaced by another settings located in the same folder but instead called "prevent changing proxy settings".
So the way to do it is to set the settings with GPP and then to enable the "Prevent changing proxy settings" setting under \User settings\Administrative Templates\Windows Components\Internet Explorer.
Regards
Martin
Answer: Would it not work just disabling the connections page in IE

GPMC > Computer Config > Admin Templates > Windows Components > Internet Control Panel > Disable the connections page

This would stop the users getting to the proxy settings.

IE 10 missing Proxy GPO settings


AoPS putnam 2003 A1 solution issue

Question: I am having problems transferring and copying the data here. Take a look at AOPS KENT MERRYFIELD ANSWER.
I don't understand. He gets to:
$$a(k-r) + (a+1)r = n$$
But how does this show that there are exactly $n$ Ways?

From AoPs link:

Let $n$ be a fixed positive integer. How many ways are there to write $n$ as a sum of
  positive integers, $
n = a_1 + a_2 + \cdots a_k$
  with $k$ an arbitrary positive integer and $a_1 \le a_2 \le \cdots \le a_k \le a_1 + 1$? For example, with $n = 4$, there are four ways: $4, 2 + 2, 1 + 1 + 2, 1 + 1 + 1 + 1$.

From Kent Merryfield answer:

There are always exactly $n$ ways. Since each $a_i$ is either $a_1$ or $a_1 + 1$, we have the inequalities $ka_1 \le n < k(a_1 + 1)$, or $a_1 \le \frac nk  < a_1 + 1$. Hence, $a_1 = \lfloor(n/k)\rfloor$. For each positive integer$ k \le n$, let $n = ak + r$, where $a$ is a positive integer and $0 \le r < k$. This is simply the division algorithm, and $a \ge 1$ since $k \le n$. We then form the sum of $(k - r)$ copies of $a$ (this is at least one, since $r < k$) and $r$ copies of $a + 1$. The sum of this string of numbers is $a(k - r) + (a + 1)r = ak + r = n$. This string of numbers is unique for each $k$, and since we can do this for each $k$, there are exactly $n$ possibilities.
Answer: First he points out that each $a_i$ must be $a_1$ or $a_1+1$. This implies that for any given number $k$ of terms, $a_1$ must be $\lfloor n/k\rfloor$. In other words, once you know the number of terms, you know what $a_1$ must be. Thus, for some $r<k$ there must be $r$ terms that are $a_1+1$ and $k-r$ that are $a_1$. (We must have $r<k$, since the first term has to be $a_1$. He then shows that there is only one choice of $r$ that gives you a solution for this value of $k$.
Finally, there are exactly $n$ possible choices of $k$. Clearly $k$ is a positive integer, and since $1\le a_1=\lfloor n/k\rfloor$, we must have $k\le n$. Thus, there is one solution for each of the $n$ possible numbers of terms: $k=1,2,\ldots,n$.
Comment: He just uses $a$ generally though  not $a_1$ ?
Comment: @Drizzy: Yes, once he's established that $a_1$ is completely determined by $n$ and $k$, he drops the subscript in order to simplify the notation and calls it simply $a$.
Comment: How can he let $n = a_1 k + r$ what is the reason he is allowed to do that?
Comment: @Drizzy: The division algorithm. When you divide $n$ by $k$, you get a quotient of $a_1$ and a remainder of $r$, where $0\le r<k$, and that means that $n-r=a_1k$, or $n=a_1k+r$.
Comment: Okay, that part seems clear. But how do you form as he says: (k-r) copies of $a_1$ ?  How to reach this conclusion?
Comment: @Drizzy: Suppose that you made each of the terms equal to $a_1$; then the sum would be $ka_1$. But $n=ka_1+r$, so you need to increase $r$ of the terms by $1$ to get a total of $n$. That will give you $r$ terms that are $a_1+1$, and the rest (i.e., the other $k-r$) will still be $a_1$.
Comment: @BrianM.Scott, $n = ka_1 + r$. How does increasing $r$ of the terms by $1$ each time get you a total of $n$?
Comment: @Lebes: You're starting with $k$ terms, each of which is $a_1$. Their sum is $ka_1$. If you now increase the last $r$ of them by $1$ each, you increase their total by $r\cdot 1=r$ to get $ka_1+r$, which is $n$.
Comment: @BrianM.Scott  Then if you increase some of them by $r$. How is it: $(k - r)$? Why the negative $r?$
Comment: @Lebes: Eh? You're not increasing any of them by $r$: you're increasing $r$ of them by $1$ each. There are $k$ of them altogether, so there must be $k-r$ that are *not* being increased. As a result you have $k-r$ that are $a_1$ and $r$ that are $a_1+1$.
Comment: @BrianM.Scott, So you are adding $a_1 + 1$ $r$ times?
Comment: @Lebes: Each of the $r$ terms $a_{k_r+1},a_{k_r+2},\ldots,a_k$ is equal to $a_1+1$. This is quite clearly, if concisely, explained in the answer quoted in the question.
Comment: @BrianM.Scott, I really do not understand Kent's answer. The steps are too vague for someone with as much knowledge as mine to pick up. Let me retry:

So he is taking $r(a_1 + 1)$? Right?
Comment: @Lebes: This really isn't the place to work through it a piece at a time. Try reading the write-up in the $2003$ solutions available [here](http://kskedlaya.org/putnam-archive/); it's a slightly different explanation of essentially the same idea and might help you. Then if you have a specific question about it, you could make it a new question.
Comment: @BrianM.Scott, I looked there, it seems better, I still do have questions: http://math.stackexchange.com/questions/1142431/how-does-the-sequence-have-n-possibilities would you mind considering the question?
Answer: There are only two admissible terms for a given starting value $a$, $a$ and $a+1$.
So $n=pa+q(a+1)=(p+q)a+q$
$p+q$ is the total number of terms in the sum. Call that $k=p+q$.
Unless all terms of the sum are equal, some are greater than the mean and some are less, but they have to differ by one. It follows that $a=[n/k]$. This also covers the case when all terms are equal.
$n=k[n/k]+q$
So $q=n-k[n/k]=n \% k$
$n=k[n/k]+n\%k$
$q$ is unique by the division algorithm applied to $n$ and $k$. There is one possible sum for each $k$ and $k$ may take on values from 1 to $n$. So there are $n$  ways for each $n$.

AoPS putnam 2003 A1 solution issue


How to render a c# code based on the client browser width

Question: I have a c# code, I need it to be implemeneted only if the client's browser width is smaller than 1200px
I tried this code:

  $(document).ready(function () {
        $("#clientScreenWidth").val($(window).width());
        $("#clientScreenHeight").val($(window).height());
    });

<input type="hidden" value=""
       name="clientScreenHeight" id="clientScreenHeight" />
<input type="hidden" value=""
       name="clientScreenWidth" id="clientScreenWidth" />

  @{
   string height = HttpContext.Current.Request.Params["clientScreenHeight"];
    string width = HttpContext.Current.Request.Params["clientScreenWidth"];

  if(width <1200)
  {
      foreach (var component in leftSideComponents)
        {
          //// Code
        }
  }

  }

but the width returned null.
Is there any one knows how to implement that ?
Thanks
Comment: Is there a reason that you decided that this should happen server-side rather than at the client? Usually a [CSS media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) would be an appropriate solution here.
Comment: are you aware that JS and C# run at different times and on differrent computers?
Comment: Thomas, yes i am aware of that, but I put this solution because stack-overflow keeps ask me to add a code
Comment: @spender

No this will not be useful for my case, because I am rendering a large number of images in specific case, and I don't want them to be rendered in all cases and then hide them by CSS
Comment: are you open to using a javascript + CSS solution? You can pass the image links to javascript and generate the HTML based on the client's screen (test the width initially and on resize and only generate HTML once) width and use some CSS to hide or show it after it has been generated.
Answer: You're going about this the wrong way. You really don't need to involve the server with this logic.
The <picture> element is your friend here:

<picture>
    <source srcset="https://interactive-examples.mdn.mozilla.net/media/examples/surfer-240-200.jpg"
            media="(min-width: 400px)">

</picture>

Here, we display a blank, transparent 1px png stand-in if the media-width is less that 400px. A properly cached image (instead of a data url) will reduce bandwidth further. If the page is loaded in this narrow configuration, the main image is never downloaded by the browser.
Run the snippet above and resize your browser until the image in the example above disappears, then reload the page and look at your devtools network panel. The image won't download until you resize above 400px.
See
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture ,
https://stackoverflow.com/a/42799282/14357 ,
https://caniuse.com/#feat=picture


Uploading a filename to mysql database

Question: I am trying to upload a file name selected through a form with a 'browse' button on the previous page. The code to do this:
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).

//inserting data order
$clip = "INSERT INTO musicdb
            (clipID, clipName, genre)
            VALUES
            ('','$filename','$name1')";

This works fine when trying to upload a file with no apostrophes in, however when trying to upload a file with an apostrophe e.g "friends' birthday" then it fails to upload to the mysql table. I think it's to do with the usage of " and ' interchangeably in the INSERT statement. I don't know which brackets $filename = $_FILES['userfile']['name'] uses by default whether its " or '.
Thanks in advance
Comment: Echo the resulting `$clip` query and you will see the problem. Quotes (apostrophes) must be escaped.
Answer: you need to escape your strings.
$filename = mysqli_real_escape_string($con, $filename);

Comment: This results in $filename being empty?
Answer: Make sure to escape any variables you are using in a SQL statement.  For reference:
http://php.net/manual/en/mysqli.real-escape-string.php
Answer: for the quotes use this for example
addslashes($str);

Comment: when you add slashes you will also have strip slashes. if i remember correctly.
Comment: exactly you need when you want to display the $str to use it
Answer: First Replace apostrophes with another character(which not used in generally) From Requested file Name.
Then Insert into MySQL table.

Uploading a filename to mysql database


Usar label no lugar do href

Question: Tenho o seguinte css
* {
    margin: 0;
    padding: 0;
}
ul {
    display: block;
    list-style: none;
    border: rgb(0,0,0) 1px solid;
}
ul li {
    display: inline-block;
    width: 50px;
    height: 50px;
    text-align: center;
    border: rgb(0,0,0) 1px solid;
}
ul li a {
    display: none;
}
ul li label {
    display: block;
    width: 80%;
    height: 80%;
    margin: 0 auto;
    margin-top: 3px;
    border: rgb(0,0,0) 1px solid;
    background-color: rgb(200,200,200);
}
ul li a:hover + label {
    outline: rgb(33,180,208) 4px solid;
    background-color: #F00;
    border-color: #CCC;
}

E o html

    linkA

    linkB

    linkC

Meu objetivo é esconder o href e usar o label em forma de bloco para dar um estilo ao link.
Porém quando clico no label não está disparando o href.
Onde estou errando?
Comment: Porque não aplicas o estilo diretamente no link em vez disso?!
Comment: A tag  não é uma elemento rotulável, então a label não consegue referencia-lo, a lista dos elementos rotuláveis pode ser obtida aqui https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Form_labelable
Comment: Você pode ou utilizar o css diretamente no link, ou através de Javascript disparar o gatilho do click no link ao clicar no label.
Comment: verdade. mas para efeito didático, porque não funcionou  no link como acontece com type text?
Comment: entendi: obrigado
Answer: Coloca o estilo no link.
ul li a {
display: block;
width: 80%;
height: 80%;
margin: 0 auto;
margin-top: 3px;
border: rgb(0,0,0) 1px solid;
background-color: rgb(200,200,200);
}
ul li a:hover + a {
outline: rgb(33,180,208) 4px solid;
background-color: #F00;
border-color: #CCC;
}

Comment: Muito Obrigado!

Usar label no lugar do href


How to set an expiration date for Firestore documents

Question: How can I add a future date and time to a firestore document and add a function when that time expires? For example today I create a document and record that time and then I want to register that fifteen days later the publicado field will be false. It's possible?
I am creating a document in firestore in the following way:
component.ts
import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../../services/firebase.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

forma: FormGroup;

constructor( fb: FormBuilder, private fs: FirebaseService ) {
  this.forma = fb.group ({
    fechaCreacion: [ firebase.firestore.FieldValue.serverTimestamp() ],
    publicado: [ true ],
  })
}

agregarAviso() {
  this.fs.addAviso(this.forma.value);
}

firebase.service.ts
constructor( private afs: AngularFirestore ) {}

addAviso(aviso){
  this.afs.collection('avisos').add(aviso);
}

As a result I get the following:
Answer: Firestore doesn't have a concept of a TTL (time to live) for documents.  Documents exist forever until some code directly deletes them.
You could write some code to periodically query for documents that should be expired, and you will have to accept that they may finally be deleted after the timestamp, by up to the amount of time your process runs periodically.  You will likely want to run this on a backend you control, with a scheduler that you control, using the Firebase Admin SDK.
Comment: Okay. I think I have not raised my approach well. What I try is not to delete the document but rather to update it. So for example is it possible to update the `published` field to` false` after some time? This is what I do now to update it at that moment: html `(ngModelChange) =" updatePublicated (warning.id, warning, $ event)"` ts: `updatePublicated (key, obj, e) {
     this.fs.updatePosted (key, e);
   }`
Comment: service: `updatePublicated (key, published) {
     this.afs.doc ('warnings /' + key) .update ({published});
   }
Comment: There is no scheduled work at all in Firestore.  You still have to do what I'm suggesting in my answer.


AND no SQL (Firebird)

Question: Tenho o seguinte código:
UPDATE PRODUTOS SET categoria = '001' WHERE marca = '1774'

Porém há mais de 400 marcas.. pensei em usar AND no where para fazer com várias marcas de uma vez, porém não vai, e com uma marca só vai. Há alguma maneira de encurtar isso pra não fazer 1 por 1?
Comment: Não seria `OR` (marca = 1 OR marca=2 OR ...) ou até mesmo `IN` (marca IN (1, 2, ...))?
Comment: Se usar o AND... uma marca pode ser dois valores diferentes ao mesmo tempo?
Answer: Utilize a clausula IN
UPDATE PRODUTOS SET categoria = '001' WHERE marca IN ('1774', '1775', '1776')

Você pode também utilizar um sub-select ali para retornar o código das marcas que deseja, por exemplo, se você possuí uma tabela só de marcas:
UPDATE PRODUTOS
   SET categoria = '001'
 WHERE marca IN (SELECT CODIGO
                   FROM MARCAS
                  WHERE TIPO = 1)

AND no SQL (Firebird)


Find the probability that exactly $2$ urns remain empty, given that not every box receives a ball.

Question:
$10$ indistinguishable balls are placed in $5$ distinguishable urns.
Find the probability that exactly $2$ urns remain empty, given that not every box receives a ball.

So, this is a conditional probability that can be written as $\text{P(exactly $2$ urns remain empty/at least $1$ box remains empty)} = P(A|B) = \dfrac{P(A \cap B)}{P(B)}$
To choose the $2$ urns that remain empty we have $\displaystyle \binom{5}2$ ways and we have $\displaystyle \binom{7+3-1}{3-1}$ ways to put a ball in every other urn.
But I don't know how to calculate the above probability. Any help please? Thank you
Comment: You should clarify:  how are the balls placed in the urns?  The obvious thought would be that each ball has an equal probability of going in any of the urns, independently of all the other balls.  But that interpretation is not compatible with the Stars and Bars computation you appear to have done (though I don't understand why you wrote $7+3-1$ instead of $10-1$).  The Stars and Bars patterns are not equally probable.
Comment: In my (only slightly tongue-in-cheek) opinion, anyone who teaches probability by putting indistinguishable balls in urns should reconsider their choices in life.
Answer: Number of ways to distribute all balls in the urns is clearly given by $5^{10}$.
Now suppose if $a_1$ balls go in the first urn, $a_2$ balls go in the second urn and so on and $a_5$ balls go in the fifth urn , we have $$a_1+a_2+a_3+a_4+a_5=10$$
whose number of solutions by stars and bars is given by $\displaystyle \binom{10+5-1}{5-1}=\binom{14}{4}$.
Now suppose no urns remain empty, so we force the condition $a_i \geq 1 $ for all $i$ where $1\le i \le 5$.
So if we assume $a_1=b_1+1, a_2=b_2+1$ and so on so that we have $b_i \geq 0$ for all $i$.
So we have our new equation as $$b_1+b_2+b_3+b_4+b_5=5$$
whose number of solutions by stars and bars is given by $\displaystyle \binom{5+5-1}{5-1}=\binom{9}{4}$.
So this was the number of ways of distributing the balls so that no urn remains empty, so that means the number of ways in which atleast one urn remains empty is $\displaystyle \binom{14}{4}-\binom{9}{4}$.
Therefore the probability that atleast one urn remains empty is $$\displaystyle \dfrac{\binom{14}{4}-\binom{9}{4}}{5^{10}}$$
For computing the probability that exactly $2$ urns remain empty, let $a_4=a_5=0$ and force $a_1,a_2,a_3 \geq 1$, so by similar reasoning we have the equation $$b_1+b_2+b_3=7$$
whose solution by stars and bars is given by $\displaystyle \binom{7+3-1}{3-1}= \binom{9}{2}$. But we could let any two $a_i's$ to be $0$, so we multiply by $\displaystyle \binom{5}{2}=10$, so it's probability becomes $$\dfrac{\binom{5}{2}\binom{9}{2}}{5^{10}}$$
So by dividing the above two probabilities, we get out final answer as $\displaystyle \dfrac{\binom{5}{2}\binom{9}{2}}{\binom{14}{4}-\binom{9}{4}}=\dfrac{72}{175}$.
Answer: I don't see why it would matter that the urns are labeled. I doubt that the question can be answered by just counting the number of outcomes because they do not have equal probabilities. Throwing 10 balls randomly (i.e. selecting urns with probability 1/5 for each ball, independently of where other balls end up)  into 5 urns gives the following multiplicities of the 30 different outcomes:
<code> 0^0 1^0 2^5 | 4536/390625
 0^0 1^1 2^3 3^1 | 12096/78125
 0^0 1^2 2^1 3^2 | 12096/78125
 0^0 1^2 2^2 3^0 4^1 | 9072/78125
 0^0 1^3 2^0 3^1 4^1 | 4032/78125
 0^0 1^3 2^1 3^0 4^0 5^1 | 12096/390625
 0^0 1^4 2^0 3^0 4^0 5^0 6^1 | 1008/390625
 0^1 1^0 2^2 3^2 | 6048/78125
 0^1 1^0 2^3 3^0 4^1 | 3024/78125
 0^1 1^1 2^0 3^3 | 2688/78125
 0^1 1^1 2^1 3^1 4^1 | 12096/78125
 0^1 1^1 2^2 3^0 4^0 5^1 | 18144/390625
 0^1 1^2 2^0 3^0 4^2 | 1512/78125
 0^1 1^2 2^0 3^1 4^0 5^1 | 12096/390625
 0^1 1^2 2^1 3^0 4^0 5^0 6^1 | 6048/390625
 0^1 1^3 2^0 3^0 4^0 5^0 6^0 7^1 | 576/390625
 0^2 1^0 2^0 3^2 4^1 | 1008/78125
 0^2 1^0 2^1 3^0 4^2 | 756/78125
 0^2 1^0 2^1 3^1 4^0 5^1 | 6048/390625
 0^2 1^0 2^2 3^0 4^0 5^0 6^1 | 1512/390625
 0^2 1^1 2^0 3^0 4^1 5^1 | 3024/390625
 0^2 1^1 2^0 3^1 4^0 5^0 6^1 | 2016/390625
 0^2 1^1 2^1 3^0 4^0 5^0 6^0 7^1 | 864/390625
 0^2 1^2 2^0 3^0 4^0 5^0 6^0 7^0 8^1 | 108/390625
 0^3 1^0 2^0 3^0 4^0 5^2 | 504/1953125
 0^3 1^0 2^0 3^0 4^1 5^0 6^1 | 168/390625
 0^3 1^0 2^0 3^1 4^0 5^0 6^0 7^1 | 96/390625
 0^3 1^0 2^1 3^0 4^0 5^0 6^0 7^0 8^1 | 36/390625
 0^3 1^1 2^0 3^0 4^0 5^0 6^0 7^0 8^0 9^1 | 8/390625
 0^4 1^0 2^0 3^0 4^0 5^0 6^0 7^0 8^0 9^0 10^1 | 1/1953125
</code>
This uses multiset notation: i^u(i) means there are u(i) urns which have i balls
.
So the probability of having exactly 2 empty urns is
1008/78125 +756/78125 +6048/390625 +1512/390625 +3024/390625 +2016/390625 +864/390625 +108/390625 = 22392/390625.
The probability of having no empty urns is
4536/390625 +12096/78125 +12096/78125 +9072/78125 +4032/78125 +12096/390625 +1008/390625 = 40824/78125.
The probability of having at least one empty urn is 1-40824/78125 = 37301/78125.
My interpretation of "given that.." is that one asks for the conditional probability in the Bayesian sense, and 22392/390625/(37301/78125) = 22392/186505 = 0.120061... is the result.


prove cross ratio of 4 point on a circle is invariant

Question: The text which I was reading said that
if we assume points
$\displaystyle O_{1} ,O_{2} ,A,B,C,D$ on a circle then it's cross ratio is
$\displaystyle R( O_{1} A,O_{1} B;O_{1} C,O_{1} D)=R( O_{2} A,O_{2} B;O_{2} C,O_{2} D)$
please explain what does the above mean(by expressing in ratio) and give its proof.
Comment: You can refer EGMO chapter 9.
Comment: EGM0=Euclidean Geometry for Mathematical Olympiads...
Answer: The cross ratios you are giving are cross ratios of pencils of four lines (four lines passing through the same point). The definition of the cross ratio of lines $(L_1,L_2,L_3,L_4)$ is based on the theorem saying that whatever the line cutting the pencil, the (ordinary) cross ratio of intersection points $(I_1,I_2,I_3,I_4)$ has always the same value.
See for example this reference.
The value of the cross ratio of 4 lines can also be computed "intrinsically" by using angles as given for example here, with their notations:
$$(\sin(cMa)/\sin(cMb))/(\sin(dMa)/\sin(dMb))$$
Consider the following figure (using your notations):

The two cross ratios are the same because the four angles involved in each one are the same (and therefore their sines as well). This comes from the classical theorem saying that, in a circle, inscribed angles subtended by the same arc are equal (for example the two angles $\alpha$ are equal because they are both subtended by arc $AB$).
Comment: But this is a circle not a straight line. Why does it work here? I think this deserves an explanation.
Comment: @wilsonw The OP means [**cross ratios of pencils of lines**](https://ljk.imag.fr/membres/Bill.Triggs/pubs/isprs96/node30.html), a generalisation of simple cross ratios of points on a same line. This a number attached to the pencil of four lines in a certain order, just as the ordinary cross-ratio is a number attached to four aligned points ranked in a certain order.
Comment: I think that also means the OP's equation is the result of a wrong definition?
Comment: @wilsonw I don't see it as a definition but as a property , consequence of a definition coming frome elsewhere, as I have explained.
Comment: Oh, you are right. I understand finally whats happening now.


Why don't professional squash players give hard serves?

Question: I find it odd that in Squash championships, players don't put much energy into the serve. It seems to me that their serve is about half the speed of their fast shots during the game. Is there any rule preventing them from doing so? Or is there another disadvantage?
Answer: The problem with hard serves is that the ball bounces back too high and far from the back wall. This gives the returner too much space and allows them to either make a kill shot or put the server into a tough position right away.
Squash is a game where ball position is very important, often more so than power. A good squash serve hits high on the side wall and lands softly in the back corner so the returner must play a defensive shot.


Low latency packet processing with shared memory on Linux?

Question: If I was to receive UDP packets on Linux (and I didn't mind changing some of the source code) what would be the fastest way for my application to read the packets?
Would I want to modify the network stack so that once a UDP packet is received it is written to shared memory and have the application access that memory?
Would there be any way for the stack to notify the application to react, rather than have the application continuously poll the shared memory?
Any advice/further resources are welcome- I have only seen:
http://www.kegel.com/c10k.html
Comment: Sorry, but are you sure, that the normal way of reading UDP packets via recvfrom(2) etc. is not fast enough? Changing the Linux source creates quite a maintenance burden.
Comment: possible duplicate of [Is zero-copy UDP packing receiving possibly on Linux?](http://stackoverflow.com/questions/7450001/is-zero-copy-udp-packing-receiving-possibly-on-linux)
Comment: You are announcing latency requirements without providing numbers, so right off the bat your question can't be answered.  Step one needs to be to measure your existing latency problems and report them.  Then identify the best solution (hint: the syscall used to read the data is almost never the problem -- look to changing hardware instead).  This question just reeks of premature optimization.
Comment: You will be extremely luck to shave even a μSec from the latency of using a std select / recvfrom loop.  UDP over internet is 10s mSec or ~1 mSec within the server room fabric.  You are looking in the wrong place.
Comment: @SegFault unless it directly outputs the packet data to memory using zero copy, then it's not as fast as I would like. I'm not concerned about maintenance- just implementation.
Answer: If latency is a problem and the default UDP network stack does not perform as you wish, then try to use different existing (installable) network stacks.
Example, try UDP Lite, compare to the standard UDP stack, this particular stack does not perform any checksum on the UDP datagram, thus reducing latencies at the cost of providing corrupted datagram to the application layer.
Side note: you do not need to have a "polling" mechanism. Read the manual of select (and it's possible derivative like pselect or ppoll), with such API, the kernel will "wake up" your application as soon as it has something to read or write in the pipeline.


Module to easily insert link to other content into textarea?

Question: Title pretty much says it all. I want a button or something next to the textarea that will let you link selected text to a particular node.
I am guessing that I should be using the WYSIWYG module with a particular editor, and happy to hear suggestions as to which combination.
Answer: CKEditor with CKEditor Link does the trick.
Comment: Thanks for that. Only problem is CKEditor. I think I will write my own module that works for plain textareas.
Answer: Well it's not a button, but node_link creates links to a given node number.
Comment: Not exactly what I'm looking for as I want it to be as painless as possible for the end user, but thanks anyway.
Answer: How about Linkit?
"Linkit provides an easy interface for internal and external linking with editors and fields by using an autocomplete field. Linkit links to nodes, users, managed files, terms and have basic support for all entities by default.
Linkit has three major advantages over traditional linking"
https://www.drupal.org/project/linkit


Solr filter-query vs main-query

Question: Solr docs state that filter queries, unlike the main query, do not influence the document score. What does this mean exactly, preferably with an example.
Answer: A FilterQuery ONLY stores document IDS. This makes it very fast to apply the filter to include/exclude documents. Good examples of this are when filtering products from search based on Country, Product Type, Availability, etc.
A normal query can perform the exact same function, but it has a very complex scoring system to determine "relevance". I believe the documentation is indicating that scoring is only done on the Main Query, not on the Filter Query. This should also increase query speed.
So, I can query for:
description:Kohler AND productType:Toilet

Or I can query for:
description:Kohler
with a FQ of productType:Toilet

The results would be the same, but the scores would be different. Also, if you get many different queries throughout the day that are for productType:Toilet, the FilterQuery would be cached making the overall query time faster.
Comment: So if for example at indexing there is term boosting on "productType", the results can be sorted differently if productType is set in a FilterQuery instead of the main Query, such that if it is in the Query, those documents with a higher productType score will be at the top, while if it is in a FilterQuery those docs with a higher productType score might be at the bottom because score is not applied since it is in a FilterQuery. Am I understanding you right?
Comment: Correct. However, if you put productType in the main Query as an AND clause, you wouldn't get back any other productTypes anyway. So this may be of limited value. But, you what you said means you understand how it works.
Comment: Yes you have a point, because I was incorrectly assuming an FTS on productType as well (therefore more than one productType could potentially be returned, but usually there is no FTS on *Type). Thanks.
Comment: I suppose this scoring will be relevant when you have a composite query with OR'ed sub-queries for fields with different scores.
Answer: fq is intended for a fixed list of values. If you search on q=sunroof+stereo and fq=Mustang solr will do text analysis on the q parameter since q=sunroof+stereo and q=stereo+sunroof will return the same result set. But when filtering the search via fq there is no analysis applied to the fq param and it's assumed all returned documents will match the fq so there is no need for it to modify the score of the docs that match.

Solr filter-query vs main-query


Question related to symmetry in distances

Question: My dataset represents products and evaluation of every product by users. E.g., I might have:
<code>{
    {'Customer':'John Doe', "likes":['Apple':'1', 'Orange':'3']},
    {'Customer':'Jane Doe', "likes":['Apple':'5', 'Orange':'3']}
}
</code>
Our solution implements a simple Euclidian distance to determine how similar tastes two users have. However, this  similarity is calculated based on a given vector against which we need to calculate. Suppose we want to find people that like apples. The given vector might look as following
<code>{'Customer':'Apple liker', 'likes':['Apple':3]}
</code>
The distance for both John Doe and Jane Doe will be 2. Is there a way to differentiate the fact that even though they have the same distance, Jane really likes apples?
Answer: First, the differences in your example will not both be 2; one will be -2 and the other +2 because John prefers oranges while Jane prefers apples.
But suppose the values were 1, 3 and 3, 5.  Then the distances would be equal if you used simple distances.  But that's easy to change.  The simplest method would be to square the values.  Then 1, 3 would change to 1, 9 while 3, 5 would change to 9, 25 and that would capture "really liking" apples.  That might be too extreme; you could use the 1.5 power if you prefer.


Debian etch source list

Question: I've an webserver that is still debian etch.
My problem is I need to upgrade some packages but I can't find a source for debian etch anywhere.
I have the following:
<code>###### Debian Main Repos
deb http://ftp.ie.debian.org/debian/ etch main
deb-src http://ftp.ie.debian.org/debian/ etch main

deb http://security.debian.org/ etch/updates main contrib
deb-src http://security.debian.org/ etch/updates main contrib
</code>
but my main repos don't seem to exist anymore.
I know I need to upgrade to lenny but the docs recommend you update to latest etch first before doing a dist-upgrade.  Where can I find the latest etch source?
Answer: Have you tried the mirrors on the archive list?
Comment: +1 Updates for *Etch* have been [discontinued as of February 2010](http://www.debian.org/releases/etch/).
Answer: try with mirrors from here http://debian.org/distrib/archive

Debian etch source list


Problem with solving square root integral

Question: I want to ask, I have an example of an integral equation with roots like this :
$$\int \sqrt[3]{x^{2}}\,\operatorname{d}x = \int x^{2/3}\,\operatorname{d}x$$
What if this?
$$\displaystyle\int \sqrt[3]{\sqrt{\sqrt{x^{2}}}}\,\operatorname{d}x = {?}$$
Comment: That's the integral of $x^{2/(2*2*3)}$.
Answer: You can easily rewrite your term as
$$\sqrt[3]{\sqrt{\sqrt{x^{2}}}} = (((x^2)^{1/2})^{1/2})^{1/3}=x^{2\cdot (1/2)\cdot(1/2)\cdot(1/3)}=x^{1/6}=\sqrt[6]{x}$$
Be aware that you will lose your $x<0$ part when doing so. If that's the matter, consider
$$\sqrt[3]{\sqrt{\sqrt{x^{2}}}} = \sqrt[3]{\sqrt{|x|}} = |x|^{1/6}$$
And then, split your integral by definition of $|x|$:
$$|x|=\begin{cases}x,&\text{for }x\geqslant 0\\
-x,&\text{for }x<0\end{cases}$$
Answer: $$\int \sqrt[3]{\sqrt{\sqrt{x^2}}}\ dx=\int |x|^{\frac12\cdot \frac13}\ dx=\int |x|^{1/6}\ dx $$$$ =\begin{cases}\int x^\frac 16dx\text{, if }x\geq0\\ \int (-x)^\frac 16dx\text{, if }x<0\end{cases} = \begin{cases}\dfrac{x^{1+\frac 16}}{1+\frac 16}+C\text{, if }x\geq0\\ -\dfrac{(-x)^{1+\frac 16}}{1+\frac 16}+C\text{, if }x<0\end{cases}$$
$$=\boxed{\dfrac67x\sqrt[6]{|x|}+C}$$


Operador ternário retorna error 500

Question: Eu queria que na condição sempre que o input text for igual a um valor desative o input radio, mas retorna sempre error 500 ao executar na página:
$y = 0;
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
    $property = ($rows_cursos["Descricao"] === "1 Desinfetante de Surpeficies" || $rows_cursos["Descricao"] === "Saco/Caixa c/ Cotonetes") : "disabled" ? "required";
    $tabela1 .= '
';
    $tabela1 .= ' <input type="text" readonly="true" size="20" name= "Produto['.$y.']" class= "Produto" value="'.$rows_cursos['Descricao'].'">	';
    $tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Ok" '.$property.'>	';
    $tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Não Ok" '.$property.'>	';
    $tabela1 .= '
';
    $y++;
}

Comment: Esse codigo funciona sem o operador ternário?
Comment: @Bruno Romualdo sim funciona, o problema é quando adiciono `:"disabled"?"required"`
Comment: não se esqueça de marcar uma resposta como correta, e aconselho que enquanto estiver aprendendo algo novo sempre pesquise e escreva você mesmo o código pois assim você grava melhor e pode ajudar outros quando precisarem.
Answer: Erro 500 é um erro interno do servidor. Para saber onde está o erro você precisa ativar o log de erros no servidor ou ativar o display errors no script, colocando o seguinte código no inicio:
error_reporting(E_ALL);
ini_set('display_errors', 1);

No seu caso o erro está no operador ternário. É um erro muito comum trocar a posição do : com o ?. Da documentação:

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Alterando a linha 5 do seu código deve resolver o erro 500.
$property = ($rows_cursos["Descricao"]==="1 Desinfetante de Surpeficies" || $resultado_cursos["Descricao"]==="Saco/Caixa c/ Cotonetes") ? "disabled" : "required";

Uma dica é pensar na expr1 como uma pergunta. Isso faz lembrar que no final tem o ponto de interrogação.
Answer: Ta errado a ordem amigo, operador é assim:
condição ? resultado_verdadeiro : resultado_falso

você colocou o ? no lugar do :.

Operador ternário retorna error 500


VScode. Cannot connect to Extensions market place

Question: My Setup
Mac osx : Catalina 10.15.5
VS code
Version: 1.51.0
Commit: fcac248b077b55bae4ba5bab613fd6e9156c2f0c
Date: 2020-11-05T18:14:40.758Z (4 days ago)
Electron: 9.3.3
Chrome: 83.0.4103.122
Node.js: 12.14.1
V8: 18.104.22.168-electron.0
OS: Darwin x64 19.5.0

My Problem
I cannot connect to Extensions market place using vscode, here is the error message
If I open developer tools (F1 > Toggle Developer Tools) and inspect the request to marketplace it says net::ERR_ACCESS_DENIED
But I can copy out that request as curl (right click -> copy and curl) and it works fine from my terminal
curl 'https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery' \
  -H 'X-Market-User-Id: f8427084-f361-48f0-b662-fabf315667cf' \
  -H 'Accept: application/json;api-version=3.0-preview.1' \
  -H 'Referer: ' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Code/1.51.0 Chrome/83.0.4103.122 Electron/9.3.3 Safari/537.36' \
  -H 'X-Market-Client-Id: VSCode 1.51.0' \
  -H 'Content-Type: application/json' \
  --data-binary '{"filters":[{"criteria":[{"filterType":8,"value":"Microsoft.VisualStudio.Code"},{"filterType":10,"value":"py"},{"filterType":12,"value":"4096"}],"pageNumber":1,"pageSize":50,"sortBy":0,"sortOrder":0}],"assetTypes":[],"flags":946}' \
  --compressed

Also if I open (F1 > Toggle Developer Tools) and go to the console tab and try to do any other fetch e.g
await fetch("https://randomuser.me/api/") then I get the same error (so it looks like my vscode is having a problem connecting to the internet in general)
Things that didn't work:

Restart Mac
Completely remove vscode :
https://stackoverflow.com/questions/42603103/how-to-completely-uninstall-vscode-on-mac#:~:text=Just%20drag%20VS%20Code%20from,click%20on%20the%20Remove%20button.
Change DNS: https://github.com/microsoft/vscode/issues/79604

Workaround:
Using the VScode insider build works fine, I can search and install extensions no problem (https://code.visualstudio.com/insiders/)
Any help greatly appreciated.
Thanks
Answer: I fix this question by change the http proxy,
you can open the vscode setting page and search 'proxy',
change the Http:proxy to your proxy or not set, and then test
hope helpful to you:)


How to define extension for SectionedFetchResults with Key (String) and Result (NSFetchRequestResult)

Question: I have SectionedFetchResults defined like this:
private var consumption: SectionedFetchResults<String?, MedicationConsumption>

MedicationConsumption have variable quantity. I need to write extension for consumption that, it will have function totalQuantity. I have tried various way on extending it, but without any luck.
How to write extension on SectionedFetchResults, that it will return totalQuantity??
1st extension which is not working:
extension SectionedFetchResults where Result == NSManagedObject {
    var totalQuantity: Int { /* Code here */ }
}

2nd extension which is not compiling:
extension SectionedFetchResults<String, NSFetchRequestResult>.Element {
    var totalQuantity: Int { /* Code here */ }
}

Source code:
static var fetchRequest: NSFetchRequest<MedicationConsumption> {
    let result = MedicationConsumption.fetchRequest()
    result.sortDescriptors = [NSSortDescriptor(keyPath: \MedicationConsumption.date, ascending: true)]
    result.predicate = NSPredicate(format: "(medication.type == 1)")
    return result
}
@SectionedFetchRequest(fetchRequest: Self.fetchRequest, sectionIdentifier: \MedicationConsumption.group)
private var consumption: SectionedFetchResults<String?, MedicationConsumption>

// Use case scenario
var body: some View {
    List(waterConsumption) { section in
        VStack {
            Text("\(section.totalQuantity)")
        }
    }
}

MedicationConsumption: NSManagedObject
extension MedicationConsumption {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<MedicationConsumption> {
        return NSFetchRequest<MedicationConsumption>(entityName: "MedicationConsumption")
    }

    @NSManaged public var date: Date?
    @NSManaged public var group: String?
    @NSManaged public var quantity: Double
    @NSManaged public var medication: Medication?
}

Answer: I assume it can be like

for Grand Total for response:

extension SectionedFetchResults where Result == MedicationConsumption {
    var totalQuantity: Double {
        self.reduce(0) { sum, section in
            section.reduce(into: sum) { $0 += $1.quantity }
        }
    }
}

for total in Section

extension SectionedFetchResults.Section where Result == MedicationConsumption {
    var totalQuantity: Double {
        self.reduce(0) { $0 + $1.quantity }
    }
}

Tested module in project


cmd abrindo junto do .py executavel

Question: Estou praticando criação de aplicações usando python, E estou tentando dar um jeito do Promt não abrir em segundo plano toda vez que executo a aplicação, alguém pode me ajudar com isso (ainda sou leigo no assunto)
Comment: Sua questão precisa de mais exclarecimentos, quais bibliotecas, qual código está usando, mas geralmente se está usando Pyinstaller `--noconsole` deve resolver.
[Como não perguntar](https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%c3%83o-fazer-perguntas?cb=1)
Answer: Para que o prompt de comando não abra junto ao seu arquivo .py executável, você pode transformá-lo em um arquivo executável (.exe) usando a ferramenta pyinstaller.
Para fazer isso, instale o pyinstaller usando o pip install e em seguida, execute o seguinte comando para criar um arquivo executável a partir do seu arquivo .py:
pyinstaller --onefile nome_do_seu_arquivo.py
Isso criará um arquivo executável .exe na pasta "dist" na raiz do seu projeto. Agora você pode clicar neste arquivo para executar sua aplicação sem o prompt de comando sendo aberto.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

cmd abrindo junto do .py executavel


How do you do a SELECT nonExistentColumn in Entity Framework 5?

Question: I have a query that does:
SELECT "string", Field, Field2, etc.

I want to mimic this in Entity Framework so that it can go along with the results of a query:
LINQ...
select new
{
    "STRING", //this is what I want to add to this.
    shows.ShowId,
    shows.Title,
    episodes.EpisodeId,
    episodes.EpisodeTitle,
    genres.GenreDescription,
    showTypes.ShowTypeDescription,
    directors.Name,
    episodes.SeasonEpisode
};

If I try to add a simple string there, I get:
'Anonymous type projection initializer should be simple name or member access expression'
Comment: Is there any problem with your code?
Comment: yes. 'Anonymous type projection initializer should be simple name or member access expression'
Answer: Try
select new
{
    value = "STRING", //this is what I want to add to this.
    shows.ShowId,
    shows.Title,
    episodes.EpisodeId,
    episodes.EpisodeTitle,
    genres = genres.GenreDescription,
    showTypes.ShowTypeDescription,
    directors.Name,
    episodes.SeasonEpisode
};

Comment: what if I want the header text of genres.GenreDescription to be "genre" instead of "GenreDescription?"
Comment: just like the first one. `GenreDescription = genres.GenreDescription`.
Comment: Sorry, I misunderstood your comment first. You want `genre` but i thought reverse one. Please try now


Isomorphism class of vector bundle over $S^2$ and the Chern character

Question: Let $V$ be a complex vector bundle over $S^2$. Suppose that

The rank of $V$ is $1$;
$\int_{S^2}\text{ch}(V)=1$.

I've seen it written that these two facts determine $V$ up to isomorphism.
Question 1: Why is this true?
Question 2: Does something like this hold for bundles over $S^n$ (possibly with a restriction the rank)?
Thoughts: I guess in question 1, the integral $\int_{S^2}\text{ch}(V)$ is really just $\int_{S^2}c_1(V)$, where $c_1$ is the first Chern class. However, I had the impression that this could only determine the bundle up to stable isomorphism classes.
Answer: In general, complex vector bundles over spheres are not determined by their Chern character or Chern classes. For example, there is a non-trivial rank two complex vector bundle $E \to S^5$ which necessarily has $c_1(E) = 0$, $c_2(E) = 0$, and $\operatorname{ch}(E) = 2$ (i.e. $\operatorname{ch}_1(E) = 0$ and $\operatorname{ch}_2(E) = 0$); see this answer. However, rank $n$ vector bundles on $S^{2n}$ are determined by $c_n$ (or equivalently, $\operatorname{ch}_n$), see the second lemma on page $212$ of May's A Concise Course in Algebraic Topology.
Comment: Where can I find a proof without using $K$-theory?
Comment: @warzasch: I don't mention K theory in my answer, so I'm not sure what you mean. Are you referring to the last sentence?
Comment: Yes, I mean the proof in May's book.
Comment: @warzasch: There is a one-to-one correspondence between isomorphism classes of rank $n$ vector bundles on $S^{2n}$ and elements of $\pi_{2n-1}(U(n))\cong\pi_{2n-1}(U)\cong\mathbb{Z}$. We also have $H^{2n}(S^{2n};\mathbb{Z})\cong\mathbb{Z}$. One can show that $c_n:\pi_{2n-1}(U(n))\to H^{2n}(S^{2n};\mathbb{Z})$ is a group homomorphism, so it is either the zero map or injective (in which case $c_n$ determines the bundle up to isomorphism). So all you need to do is show that there is a rank $n$ bundle with non-zero $c_n$. If you can do that without K theory, you'll have the proof you desire.
Answer: Since $S^2$ has dimension 2, the only non-trivial term in the Chern character is $c_1(V)$. The fact that you can catalogue complex line bundles over $S^2$ by this Chern number can be seen by means of sheaf cohomology.
Consider the exponential (sheaf) exact sequence
$$
0\rightarrow \mathbb{Z}\rightarrow C^\infty_\mathbb{C} \overset{\exp(2\pi i\cdot)}{\rightarrow} (C^\infty_\mathbb{C})^*\rightarrow 0
$$
where $(C^\infty_\mathbb{C})^*$ denotes the sheaf of complex valued local functions that never vanish. This sequence gives rise to a exact sequence of cohomology groups
$$H^1(S^2,C^\infty_\mathbb{C})\rightarrow H^1(S^2,(C^\infty_\mathbb{C})^*) \rightarrow H^2(S^2,\mathbb{Z})\rightarrow H^2(S^2,C^\infty_\mathbb{C})$$
and since $S^2$ admits smooth partitions of unity, the sheaf $C^\infty_\mathbb{C}$ is soft and thus $H^1(S^2,C^\infty_\mathbb{C})=H^2(S^2,C^\infty_\mathbb{C})=0$. Therefore you conclude
$$H^1(S^2,(C^\infty_\mathbb{C})^*)\simeq H^2(S^2,\mathbb{Z})$$
Now, the LHS can be realized by means of Cech cohomology as those cocycles/transition functions that uniquely determine your complex line bundle. The RHS is, as you know from topology, $\mathbb{Z}$. It can be shown that the connecting morphism corresponds precisely with assigning to each (isomorphism class of) line bundle on the LHS, the first Chern class on the RHS.
I suggest you check out Well's Differential Analysis on Complex Manifolds,  Chapter III, Section 4: Complex Line Bundles, for a more detailed and careful account of the idea I exposed.
Now in the setting of holomorphic line bundles, it is not usual that the holomorphic and smooth classification of line bundles agrees. This happens to be true for the sphere $S^2$. And holomorphic line bundles over the sphere are all stable (in the sense of slope or Mumford--Takemoto stability).


PHP only shows in foreach

Question: New to PHP, I'm trying to do an exercise which consists on making a simple dynamic website with people information, linked to a local database.
But I'm stuck at a point where I can only show anything through a foreach loop.
My database looks like this (with more people of course) :
<?php

function getAllPerson() {
$list_person = array();

$person1 = array(
"id" => 0,
"surname" => "John",
"name" => "Doe",
"img" => "https://randomuser.me/api/portraits/men/64.jpg");
$liste_person[0] = $person1;

return array($personne1);
}

function getPerso($person_id) {
$list_person = getAllPerson();
return $list_person[$person_id];
}

And my page :
<?php
require_once 'model/database.php';
$id = $_GET["id"];
$person = getPerso($id);
$list_person = getAllPerson();
require_once 'layout/header.php'; ?>

<?php echo $person['name'] ?> <?php echo $person['surname'] ?>

                <img src="<?php echo $person['img'] ?>" alt="<?php echo $person['name'] ?> <?php echo $person['surname'] ?>" class="pull-left thumbnail">

But nothing works (there is more html code but I wanted to keep it short here)..
But when I do a foreach and put the article in :
<?php foreach ($list_person as $person) : ?>

Everything shows, but the 4 persons at the same time (which is logical, it's a foreach).
And I have to admit I don't know how to make it an independent page for every different "id" there is. Can you help me with that? Keep it simple please!
Thank you very much!
Comment: what's the id you are calling ? `id=??`
Comment: It's the "id" in the database, which stands for the person's number in the array.
Comment: What you mean by "PHP only shows in foreach" ? are you trying to display  the info for only one particular id ?
Comment: Yep, that's it. I only put one id in the database, but there could supposedly be 100. There is a homepage with a foreach loop for every "id" that links to a single profile page, the one I'm stuck with.
Comment: Are you representing N users like this $liste_person[n] = $personN ?
Comment: Hm, I don't get the question, sorry !
Comment: You may wanna consider using [classes](http://phpio.net/s/377s).
Answer: Alright, my problem was waaaay off, and I wasn't looking at the right place. The code was clean, my only problem was the $_GET['id'] was pointing to nowhere... Hassan Ahmed was right. I just forgot to make my page dynamic by changing the page name depending on the person I was looking at, so it could not show anything.
Thanks a lot for your answers though, I could understand more some things by practicing with what you gave me !
Answer: I made it short check this if you can use it :
function getAllPerson($id = null) {

$list_person = array();

   $person1 = array(
      "id" => 0,
       "surname" => "John",
       "name" => "Doe",
       "img" => "https://randomuser.me/api/portraits/men/64.jpg");

   $person2 = array(
       "id" => 1,
       "surname" => "Sam",
       "name" => "Parker",
       "img" => "https://randomuser.me/api/portraits/men/65.jpg");

    $list_person[0] = $person1;
    $list_person[1] = $person2;

   if($id == null){
       return ($list_person);
   }
   else{
    return $list_person[$id];
   }
}

Now you can call this function in your page
<?php $person = getAllPerson(1); ?>

<?php if(!empty($person)) { ?>

<?php echo $person['name'] ?> <?php echo $person['surname'] ?>

            <img src="<?php echo $person['img'] ?>" alt="<?php echo $person['name'] ?> <?php echo $person['surname'] ?>" class="pull-left thumbnail">

<?php } ?>

You can use the same function, if you want to get all the users, just leave the argument field empty : like getAllPerson().
Comment: Thanks, I'm getting closer: the rest of the section doesn't disappear, but the print_r($person) now shows the complete array, and what it contains doesn't want to show on screen...
The id in "function getAllPerson($id = null)" seems to be unused in its scope. Do I need to define it ?
Comment: Thats what i mentioned, You can pass an id to load specific person, i you dont pass an id you will get all the person.
Comment: My problem is more in the "why doesn't it appear"... It seems to be the core of my problem, I've tried numerous solutions, but it always comes back to this: what is in the database just doesn't want to show.
Comment: @Solomai what you are trying to display ? , If you want to display the person with id : 1 just call the function getAllPerson(1), you will only get that person. similarly if you want to display person with id 20 call function  getAllPerson(20)
Comment: I'm trying to display the information I should get with a . But it just doesn't work on my side ! ^^
Comment: first load $person = getAllPerson(xx), then try to print with $person['id'], $person['name'] etc

PHP only shows in foreach


ORA-01427: single-row subquery returns more than one row with update

Question: I have an update statement, at first it worked with some data, but after a while I've been having issues with some regiters  , I got the following error:
ORA-01427: single-row subquery returns more than one row . I thought it was the IN because the query might return repeated IDs, so I put a DISTINCT but I kept getting the same error, does anyone have any idea what could it be?
The query below:
 UPDATE
        TABLE_DETAIL DET
    SET
        DET.ACCEPTED=?,
        DET.VALUE_ACCEPTED=(SELECT RES.VALUE FROM TABLE_RES RES WHERE RES.MYT=DET.MYT AND RES.RAD=DET.RAD AND RES.ITEM=DET.ITEM),
    WHERE
        DET.ID
    IN (
        SELECT
            DISTINCT DET_I.ID
            FROM TABLE_DETAIL DET_I, TABLE_RES RES_I, TABLE_REC REC
            WHERE
                DET_I.MYT = ?
            AND
                REC.TEMP
                NOT IN (
                    SELECT DISTINCT TEMP
                    FROM
                    TABLE_IMAGES WHERE CODE=?)
            AND RES_I.USER = ?
        )

Comment: It's the `DET.VALUE_ACCEPTED=(SELECT RES.VALUE FROM...` sub-query that causes trouble.
Answer: You don't need SELECT DISTINCT with IN.
The proximal cause of your problem is this code:
    DET.VALUE_ACCEPTED = (SELECT RES.VALUE FROM TABLE_RES RES WHERE RES.MYT=DET.MYT AND RES.RAD=DET.RAD AND RES.ITEM=DET.ITEM),

It isn't really possible to say how to fix it.  The error code seems pretty clear:  More than one row is returned by this query.
You can add WHERE rownum = 1 if you want an arbitrary value.  Or an aggregation function in the SELECT.
Comment: I checked this, I queried that select using the real values and I get only one row, the IN I put the DISTINCT returns two values, and with that I used it to query that select in the update and it's only one row
Comment: @Alex . . . Add `and rownum = 1` to the subquery and see if the problem goes away.


Effecient way for finding values of one dataframe in another

Question: I have the following dataframe (RES1):
    "sequence" "support"
"1" "<{OV50}>"   0.286
"2" "<{OV148}>"  0.121

And additional dataframe (SRC2):
  "sequenceID" "transactionID" "eventID" "items"
"1" 42207993       1577          1        "OV50"
"2" 42207993       6048          2        "OV11"
"3" 42207993       1597          3        "OV148"
"4" 57237976       12423         1        "OV56"
"5" 57237976       12589         2        "OV148"

I would like to get the following output dataframe (OUT3):
  "sequenceID" "transactionID" "eventID" "items"  "Exist" "Co"
"1" 42207993       1577          1        "OV50"     1
"2" 42207993       6048          2        "OV11"     0
"3" 42207993       1597          3        "OV148"    1       0.67
"4" 57237976       12423         1        "OV56"     0
"5" 57237976       12589         2        "OV148"    1       0.5

For Each row in SRC2 the "Exist" column in OUT3 will be '0' if there is no value at all in RES1. For instance, OV11 doesn't appear in RES1 at all so its value is 0.
At the last value of sequenceID - the amount of '1' values is divided by the number of the same sequenceID and is added to "Co" column. In line 3 the there were 3 lines of sequenceID = 42207993 number of '1' are 2 so 2/3 = 0.67.
I would like to find the most efficient way to do it because each of the dataframes is very big dataframe.
Comment: Just do `SRC2$items <- as.character(SRC2$items)` before we do the `setDT`
Comment: Are the `data.frames` or `matrices`?  `data.frame` cannot have duplicate row names
Comment: Hi @akrun, you can relate them as matrices and afterwards I'll do the transformation if it helps. Some of them are dataframes while others are txt files.
Comment: Hi @akrun, the row name was fixed. Thanks for the comment.
Comment: I get an error: > setDT(SRC2)[, Exist := +(items %chin% gsub('[^[:alnum:]]+', '', RES1$sequence))]
Error in items %chin% gsub("[^[:alnum:]]+", "", RES1$sequence) :
  x is type 'integer' (must be 'character' or NULL)
Comment: I am guessing that you have factor column 'items'.  Can you convert it to `character` before doing the operation.  Also, please test with the data I showed in the post.
Comment: Your solution is perfect, How can I transform the 'items' (which are column in dataframe) into character?
Comment: It is not clear.  What if `OV195` occurs after `OV197`?  I think a new question with this and expected output makes it more clear.
Answer: One option would be using data.table.  We convert the 'data.frame' to data.table (setDT(SRC2)), remove the punctuation characters in 'sequence' column of 'RES1' using gsub, check whether it is present in the 'items', coerce the logical vector to binary by wrapping with + and assign (:=) the output to a new column 'Exist'.  Grouped by 'sequenceID', we divided the sum of 'Exist' by the nrow  (.N), round, convert to 'character' and assign it as 'Co'.  Then, we get the row index (.I) of those elements that are not the last row per each 'sequenceID' and assign those to ''.
library(data.table)#v1.9.6+
setDT(SRC2)[, Exist := +(items %chin% gsub('[^[:alnum:]]+',
           '', RES1$sequence))]
i1 <- SRC2[, Co:= as.character(round(sum(Exist)/.N, 2)) ,
            sequenceID][, .I[1:(.N-1)], sequenceID]$V1
SRC2[i1, Co:= '']
SRC2
#   sequenceID transactionID eventID items Exist   Co
#1:   42207993          1577       1  OV50     1
#2:   42207993          6048       2  OV11     0
#3:   42207993          1597       3 OV148     1 0.67
#4:   57237976         12423       1  OV56     0
#5:   57237976         12589       2 OV148     1  0.5

data
SRC2 <- structure(list(sequenceID = c(42207993L, 42207993L,
 42207993L,
 57237976L, 57237976L), transactionID = c(1577L, 6048L, 1597L,
 12423L, 12589L), eventID = c(1L, 2L, 3L, 1L, 2L),
 items = c("OV50",
 "OV11", "OV148", "OV56", "OV148")), .Names = c("sequenceID",
 "transactionID", "eventID", "items"), class = "data.frame",
 row.names = c("1", "2", "3", "4", "5"))

RES1 <- structure(list(sequence = c("<{OV50}>", "<{OV148}>"),
 support = c(0.286,
 0.121)), .Names = c("sequence", "support"),
 class = "data.frame", row.names = c("1", "2"))

Comment: Thanks, Worked perfect (I did it simultaneously before your previous comment. I added another issue in the end of question body.
Comment: @Avi I didn't find any updates in your question body
Comment: @Avi Can you post that as separate question as it involves some splitting.


find the probability the black marble is from box A and the blue one is from C

Question:
(HMMT 2000 Guts Round #43) Box A contains 3 black marbles and 4 blue marbles. Box B has 7 black marbles and 1 blue marble. Box C has 2 black marbles, 3 blue marbles, and 1 green marble. Person A closes their eyes and picks two marbles from 2 different boxes. If it turns out that A gets $1$ black and 1 blue marble, what is the probability that the black marble is from box A and the blue one is from C?

My question is at the bottom.

We assume the process is equivalent to uniformly choosing 2 distinct boxes and then independently and randomly choosing a marble from each box (!)
Let the colours black, blue, and green be denoted by the numbers 1,2,3. A has 3 black and 4 blue marbles, B has 7 black and 1 blue, and C has 2 black, 3 blue, and 1 green. Consider the sample space $\Omega := \{\{(m_1,b_1),(m_2,b_2)\} : b_i \in \{A,B,C\}, m_i \in \{1,2,3\}, i = 1,2, b_1\neq b_2\}$. Here, the $b_i$'s in a pair refer to the boxes chosen. Let $X = \{\{(m_1,b_1),(m_2,b_2)\} \in \Omega : (m_1 = 1 \wedge m_2 = 2)\},Y = \{\{(m_1,b_1),(m_2,b_2)\} \in \Omega : (m_1 = 1 \wedge m_2 = 2 \wedge b_1 = A \wedge b_2 = C)  \}.$
For $R\neq S \in \{A,B,C\},$ let $P_{R,S} = \{\{(m_1,b_1),(m_2,b_2)\} \in \Omega : b_1 = R \wedge m_2 = S\}.$ We want to find $P(Y | X) = P(Y\cap X)/P(X)$. To find $P(X),$ we first find $P(X\cap P_{A,B}) , P(X\cap P_{A,C}) , P(X\cap P_{B,C})$. Now $P(X\cap P_{A,B}) = P(X | P_{A,B}) \cdot P(P_{A,B}). P(P_{A,B}) = P(P_{A,C}) = P(P_{B,C}) = 1/3,$ since every pair of two distinct boxes is selected with equal probability (by (!)). Now $P(X | P_{A,B}) = 3/7\cdot 1/8 + 4/7\cdot 7/8 = 31/56.$ Similarly, $P(X | P_{A,C}) = 3/7\cdot 3/6 + 4/7\cdot 2/6 = 17/42, P(X|P_{B,C}) = 7/8\cdot 3/6 + 1/8\cdot 2/6 = 23/48.$ Thus $P(X) = 1/3(31/56+17/42+23/48) = (483/1008).$ To find $P(Y\cap X),$ we find $P(Y\cap X \cap P_{A,B}), P(Y\cap X \cap P_{A,C}), P(Y\cap X \cap P_{B,C})$. $P(Y\cap X \cap P_{A,B}) = P(Y\cap X \cap P_{B,C}) = P(\emptyset) = 0.$ Now  $P(Y\cap X \cap P_{A,C}) = P(Y\cap X | P_{A,C}) P(P_{A,C}) = 1/3 \cdot (3/7\cdot 3/6) = 1/14.$ So the desired probability is $\dfrac{24}{161}$. This is different from the solution on HMMT.org, which is $120/1147$.

Did I make a mistake somewhere, and if so, where and how can I get the correct answer?
Answer: The simplest way is to make an array.
Since the probabilities of choosing each box is equal, we can tabulate conditional probabilities of drawing black-blue in that order given we have chosen the indicated boxes
\begin{array}{| c | c | c | c | c | c |}\hline \\Combo &AB & BA & AC & CA & BC & CB \\\hline Black-Blue &\frac37\frac18 & \frac78\frac47 & \frac37\frac36 &\frac26\frac47 & \frac78\frac36 & \frac26\frac18 \\ \hline \end{array}
$$Pr =\dfrac{\frac37\frac36}{\frac37\frac18 + \frac78\frac47 + \frac37\frac36 +\frac26\frac47\ + \frac78\frac36 + \frac26\frac18 }=\frac{24}{161}$$
Comment: Wow! You make this look so easy. +1.
Comment: @InanimateBeing: Thanks, glad you like it !$\quad$:)


ANOVA with Error term

Question: I am looking for help to create a model for the following data:
I'd like to understand if the abundance of a certain microbial group (dependent continuous variable QUANTITY) found in soils is been affected by land-use, seasonality and their interaction. For each land-use (factor LAND-USE with 2 levels: forest and pasture), I have 3 different sites (factor SITE with 6 levels: F1, F2, and F3 for FOREST and P1, P2, and P3 for PASTURE). At each site, I collected soil samples in 5 points (factor POINT). Therefore, POINT is nested in SITE and SITE is nested in LAND-USE. In the end, I have 5 points per site and 15 per land-use, totaling 30 points in the study. However, each point was sampled twice (factor SEASON with 2 levels: DS and RS), during the dry and rainy seasons.
My dataframe looks like this:
SEASON LAND-USE SITE POINT QUANTITY
DS FOREST F1 F1_1 300.00
DS FOREST F1 F1_2 330.00
DS FOREST F1 F1_3 530.00
DS FOREST F1 F1_4 670.00
DS FOREST F1 F1_5 80.00
DS FOREST F2 F2_1 600.00
DS FOREST F2 F2_2 630.00
DS FOREST F2 F2_3 780.00
DS FOREST F2 F2_4 900.00
DS FOREST F2 F2_5 1,000.00
...
RS PASTURE P3 P3_1 800.00
RS PASTURE P3 P3_2 730.00
RS PASTURE P3 P3_3 980.00
RS PASTURE P3 P3_4 550.00
RS PASTURE P3 P3_5 700.00

I am not interested in the site or point itself. I just need to know the effects of land-use and seasonality. However, I am not sure how to code site and point in the error term using AOV.
For example, what's the difference in the following codes? I know this is a very basic question, but even after reading a series of tutorials, I still do not understand which one I should choose in this case.
aov(QUANTITY ~ Season * Land-use + Error(Site), archaea)
aov(QUANTITY ~ Season * Land-use + Error(Point), archaea)
aov(QUANTITY ~ Season * Land-use + Error(Site/Point), archaea)

I would appreciate any advice. If there is anything that I should clarify, please let me know!
Comment: The term 'use" is not clear to me. Further, what is the purpose of your study - season or use (or combined effect). Also, I can not understand "use " - is it use as pasture or intensity of pasture ? How do you quantify season for the analysis proposed.
Comment: Hi Subhash! My purpose is to understand the effect of season, land-use, and their interaction. I wrote "Use" in the model, but it's actually the variable "Land-use", with the levels forest and pasture. I am not studying the intensity of pasture itself, only both systems.
Comment: I am not sure what you meant with "How do you quantify season for the analysis proposed". Can you explain to me?
Comment: @Biomol: First, please add new information to the original Q as an edit, so all information is in one place. That will increase the probability of a good answer.  Second: For season, it is continuous or a factor? Which values can it take? 1,2,...,12 for month, say, or "spring", summer", ... ? Same for other variables.
Comment: Thank you @kjetilbhalvorsen. I made all the alterations in the original text. About season, it's a factor with two levels (DS and RS). All other independent variables are factors too.
Answer: This looks like a split-plot design, see for instance Split Plot Design? lmer analysis  or  Can I test the effect of Block in a split plot design in R?.  The modern way to analyze this in R is to use the package lme4, although if your design is perfectly balanced aov might work.
Since you have Point nested within Site, the correct specification should be the analog of your third one:
lme4::lmer(QUANTITY ~ Season * Land-use + (1 | Site/Point),
           data=archaea)

where the term (1 | Site/Point) means a random constant for each Site, and for Point within Site.  This will give correct estimates also in the case of unbalanced data, something aov will not.
If you will post your data I will have a look.

ANOVA with Error term


How do you use Data Analysis Expression (DAX) to Rank number based on Week number of Year?

Question: I am looking to Dense Rank Amount of Clicks based on the week number of each year using Power BI.
The problem that I am running into is that the weeknumber is the same in the next year... and I cannot seem to get the DAX to sequence in a row correctly. Any ideas on what the DAX script would look like is appreciated.
[CODE]
             The output would look something like this:
<code>         YearNumber WeekNumber NumberOfClicks RankNumClicks
           2020          1             362        8
           2020          1             325        9
           2020          1             421        5
           2020          1             224        12
           2020          1             125        14
           2020          1             440        2
           2020          1             321        11
           2020          2             224        12
           2020          2             136        13
           2020          2             423        4
           2020          2             110        15
           2020          2             431        3
           2020          2             521        1
           2020          2             324        10
           2020          3             368        7
           2020          3             412        6
           2020          3... and so on.

      Here is what I think the DAX script should be like and what I have so
         far: (Please note that I used SalesAmount for number of clicks
         testing):
     Ranking =
     VAR WeekNumberOfYear = ISFILTERED( DimDate[WeekNumberOfYear] )
     VAR FiscalYear = ISFILTERED( DimDate[CalendarYear] )

     RETURN
     IF( ISBLANK( 'FactInternetSales'[SaleAmounts] ), BLANK(),
     IF(FiscalYear,
     RANKX( ALLSELECTED( DimDate[CalendarYear] ),
       'FactInternetSales'[SaleAmounts], , DESC, Dense ),
     IF( NOT(  WeekNumberOfYear),
        RANKX( ALLSELECTED(DimDate[CalendarYear] ),
            'FactInternetSales'[SaleAmounts], , DESC, Dense ),
         BLANK())) )
</code>

[/CODE]
Comment: Can you share your DAX code with us, so we can see what you did?
Comment: If the problem that you're having is related to multiple years, can you add some data to your expected results to show what should be happening in these weeks from different years?
Comment: Create a new column that concats year and week (201219), then rank on that, that will separate the weeks and year
Answer: You can use newly introduced Hierarchy Slicer (go to Options and Settings, select Options, then Preview features under GLOBAL and check Hierarchy slicer).

Then, you can easily filter data based on specific Year/Week.

Hope this helps.


Hiding regions for a node page without creating a unique twig file for that node?

Question: In Drupal 7 I could hide regions as reactions to certain conditions with Context; Here is a pseudocode to explain what I actually did with this module:

If $node = 1;
Than programmatically hide $region = sidebar;

In Drupal 8 for some reason, at least in this era, this functionality has been removed from the module. You can no longer hide regions as a reaction to whatever condition.
Hiding regions is still possible with CSS but it should be noted that programmatically hiding regions is better than CSS hiding as it is more swift and sound, as well as more elegant.
What I've tried instead:
Given the fact Context 8 doesn't include that functionality, I tried to use CSS to hide the region in the given node; I knew from Drupal 7 that if you are inside an node and go to the DOM tree, you can see a unique node class that will serve you in such a particular CSS action (hiding a region in a particular node).
In my Drupal 8 site I went to the DOM but didn't quite find such a class (as appears in Drupal 7 sites).
Therefore I tried using what worked for me in Drupal 7 wondering if from any case it just no longer appear in the DOM. I went to my CSS file and added:
.page-node-364 .region-sidebar-first {display: none !important}

It didn't work, nor similar tryings such as:
#node-364 .region-sidebar-first {display: none !important}
.node-364 .region-sidebar-first {display: none !important}
.364 .region-sidebar-first {display: none !important}

And so forth...
Other actions on that node class variations (neglecting region-sidebar-first) also didn't work even with !important declarations on the CSS and what I tried seemed just to be invalid.

I flushed all caches after each try.

Why I'm confused:
What I did saw at DOM and used as a class didn't cause any effect (.364 as mentioned above):

My question:
Due that Context isn't the solution this time, and that seemingly, no usable id or class appears in DOM, I thus ask professional themers here if it is even possible to hide regions for a node in Drupal 8, solely through the CSS, without creating a unique twig file to that particular node.
Comment: How about hiding the block(s) that are in that region for that particular page? will this do?
Comment: There are many blocks there appearing for diff CTs and nodes. It will be problematic and inflexible in that case.
Comment: If you can't find a solution in context, why not hide the region in a page preprocess hook? The node is already preloaded. You can check the node id and unset the variable of the region.
Comment: Must say I never used hooks before (are you sure it is suited to Drupal 8? I heard that in D8 there is something that replaces it). Nonetheless, it sounds an elegant solution; You are most welcome to detail of it in an answer.
Answer: 4k4 suggestion to use the preprocess_page Drupal-function can be done like this:
Preprocess functions go in your themes themeName.theme file, you may need to create this file if your theme does not have one - be sure to clear the Drupal cache after adding or changing code in this file.
function theme-name_preprocess_page(&$variables) {
  // Set the node ID if we're on a node page.
  $nid = isset($variables['node']) ? $variables['node']->id() : '';

  // Unset a region for one node ID.
  if ($nid == '7') {
    unset($variables['page']['sidebar_second']);
  }

  // Unset a region for multiple node ID's.
  if (in_array($nid, ['1','2','3'])) {
    unset($variables['page']['sidebar_first']);
  }
}

If you would rather use CSS (not a bad technique at all), you can add path classes to body also from theme-name.theme, but this time via the preprocess_html function:
use Drupal\Component\Utility\Html;

function theme-name_preprocess_html(&$variables) {
  // Add path classes to body.
  $path = \Drupal::request()->getPathInfo();
  $path_args = explode('/', $path);
  if (count($path_args) >= 3) {
    $variables['attributes']['class'][] = 'path-' . Html::cleanCssIdentifier(ltrim($path, '/'));
  }
}

Comment: You have to replace HOOK with your extensions machine name, i.e. your theme or module name, as in themename_preprocess_page()
Comment: What is the error message?
Comment: Oh, well this just means there are two functions with the same name: business_preprocess_page(), take the contents of the function you are using from the answer and place it inside the existing business_preprocess_page() declaration (I assume this is on line 33, if you added the second one on line 229), a text editor that has line numbers helps, better still and IDE that warns of duplicates etc, like PHPStorm - delete the duplicate. PHP does not allow duplicated function names.
Comment: Jeff, the first solution works fine but my theme seems not to fit to it, so I tried solution 2 (adding a node class to each node); Please see the attached images --- The solution seems not to work even though there is no error...
Comment: Well if you remove a whole region then I assume you will need to compensate for that by changing the layout, usually by CSS or changing the classes etc in the layout (if using something like Bootstrap etc). You'd need to clear the cache, otherwise I can't say why it might not be working other than maybe that is the front page? In which case there will already be a class - usually path-frontpage or similar.
Comment: I need that all nodes will have a numerical class... I do "drush cr" after each change... Sadly, I don't have a numerical class (or id) to non-front nodes even now... :\ I did for example #364 or .364 td {background: red !important} and nothing happened.
Comment: Sounds like you need a class based on the Node ID in the node template, so that's another question.
Comment: So there is nothing else you can suggest adding to Preprocess alone? Can I check something from the Adapative-theme code? Can you please edit the answer and say what should I take from AT and where to paste it exactly in node.html.twig ? Thanks anyway,
Comment: Like I said, it's another/new question, answering in comments hides a valuable question/answer from other users, since it's not relevant to this question.
Comment: Oh for a moment I thought you mean "class" in the programmatic sense... Well, about a week ago I did ask such a question in D.O but its sad to see only one follower - Myself... You are more than welcome to answer there: drupal.org/node/2780331
Answer: Go to your theme's folder and in your themename.theme file:
function themename_preprocess_page(&$variables) {
  $variables['nid'] = str_replace('/node/', ' ', \Drupal::service('path.current')->getPath());
}

Then in templates folder edit page.html.twig (if you don't have one, copy the one from core /core/themes/bartik/templates and copy it to your theme's templates folder).
Find {{ page.sidebar_first }} and change it to:
{% if nid not in [364, 367] %}{{ page.sidebar_first }}{% endif %}
clear/flush cache to see changes.
Answer: Here are some ways to do this:
The first way: Reuse class visually-hidden
<?php
use Drupal\node\NodeInterface;
function YourTheme_preprocess_region(&$vars) {
  if ($vars['region'] == 'sidebar_first') {
    if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
      $nid = $node->id();
      if (in_array($nid, ['1', '2'])) {
        $vars['attributes']['class'][] = 'visually-hidden';
      }
    }
  }
}

this way very simple. You just need use function hook_preprocess, don't need add css, don't need override twig template. But I don't like this way because region is hidden. But server need process to render this region.
The second way: unset region before render.
<?php
function YourTheme_preprocess_page(&$vars) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
    $nid = $node->id();
    if (in_array($nid, ['1', '2'])) {
      unset($vars['page']['sidebar_second']);
    }
  }
}

In this case. You may be need override twig template, but better for performance.
Comment: May I ask what is the purpose of the second condition && $node instanceof NodeInterface? I'm wondering because I notice on some pages routeMatch() will return an array (one item, the node id), not the node object. Is this why?


hiding taxonomy terms on term page

Question: I'm struggling theming the taxonomy-term page and since i'm not really getting anywhere, i now embedded two blocks (created with views) in my taxonomy-term.tpl.php. Now, that views is showing everything the way I want it, I don't want the term page itself output its data.
That's why I'm trying codes like
<?php hide($content); ?>

But that won't do the trick. How can I just show the Blocks from Views instead of the content taxonomy provides itself?
Thanks!
Answer: Use Display Suite to manage your display and show/hide fields for Taxonomy terms. You can actually display nothing. Then add the blocks in there.
Second option is alter taxonomy term page.tpl.php - a function that you need to add in template.php within your theme directory.
This is a function for templating pages for content types or terms. Second part defines page--taxonomy--term.tpl.php suggestion. It worked for me.
<?php
/**
* Add / modify variables before the page renders.
*/
function YOURTHEMENAME_preprocess_page(&$vars) {
// custom content type page template
  // Renders a new page template to the list of templates used if it exists
  if (isset($vars['node']->type)) {
// This code looks for any page--custom_content_type.tpl.php page
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
    if(arg(0) == 'taxonomy' && arg(1) == 'term') {
        $tid = (int)arg(2);
        $term = taxonomy_term_load($tid);
        if(is_object($term)) {
           $vars['theme_hook_suggestions'][] = 'page__taxonomy__'.$term->vocabulary_machine_name;
        }
  }
}
?>

I hope it helps. A while ago, I've been looking for this solution for days!

hiding taxonomy terms on term page


Continuous functions and restrictions to a countable domain

Question: Let $I$ a compact set and $f\in\mathcal{C}([0,1]^I)$.
Then exists $J\subset I$, countable or finite, such that:
if $x,y\in [0,1]^I$ such that $x\big|_J=y\big|_J\Rightarrow f(x)=f(y)$.
Comment: Technical note: the domain is countable-dimensional, not countable.
Comment: Clearly, if $J$ is a dense subset of $I$, then $x|_J=y|_J$ implies $x=y$, so $f(x)=f(y)$.   Therefore, if not true, there cannot be a countable dense subset of $I$. Not sure if that helps.  (That assumes that $[0,1]^I$ means the set of continuous functions from $I$ to $[0,1]$, not the set of all functions.)
Answer: The result is true for the set of all functions from $I$ into $[0,1]$ (not only the continuous ones).
Claim. For any open subset $U\subset [0,1]^I$ there exists $J\subset I$ countable so that $x\in \overline U$ and $x|_J=y|_J$ imply $y\in \overline U$.
Find a maximal pairwise disjoint family of standard basic nonempty open subsets of $U$, by the Hewitt-Marczewski-Pondiczery theorem this family is countable, let us call it $(U_n)$. For each $n$, let $J_n$ be the set of non-trivial coordinates in the basic open set $U_n$. It should be clear that $J=\bigcup_n J_n$ satisfies the requirements of the claim.
Let $\{ V_n:n\in\mathbb N\}$ be a countable base of $\mathbb R$. For each n, we can find a countable subset $J_n$ of $I$ satisfying the conclusion of the Claim with respect to the open set $f^{-1}(V_n)$. Now, we claim that   $J=\bigcup J_n$ is the required set. Suppose $x|_J=y|_J$ and $f(x)\ne f(y)$ then there are   disjoint open sets $V_n, V_m$ so that $f(x)\in V_n$ and $f(y)\in V_m$. This implies that $x\in f^{-1}(V_n)=U_n$ and $f^{-1}(V_m)=U_m$,  the sets $U_n, U_m$ are disjoint. But by the claim $y\in U_m$ and $x|_{J_m}=y|_{J_m}$ implies $x\in \overline{U_m}$ which is impossible.
Comment: Where have you used that $I$ is compact? If $[0,1]^I$ is all functions, then the only topology I know on that set is essentially the $I$-index product topology on $[0,1]$, which depends only on the cardinality of $I$ and not the topology of $I$.
Comment: @ThomasAndrews. I didn't use the compactness. (It is not necessary). I suppose as you mentioned it before that the OP had in mind the set of continuous functions from $I$ into $[0,1]$. So there is, probably, an easier proof in that case.
Comment: What is... "maximal pairwise disjoint family of standard basic nonempty open subsets"?
Comment: You're assuming that the OP's $I$ is the unit interval. What if it's a compact space of cardinality greater than $2^\omega$?