Expected value of modified geometric distribution

Question: I am trying to find the expected value of $X$, where $X$ is the number of orders a customer will make in a lifetime.
Assuming that there is a $p=.1$ chance of the customer placing an initial order, and then (given that the customer places that initial order) a $p=.9$ chance that the customer places an order after that (and each additional time the customer places an order after that as well. NB it is dependent — i.e. if the customer doesn't place an order, then he won't place any additional orders).
So I have it set up like this:

$X = \#$ of orders a customer places
$O = \#$ of orders a customer places after the first one
$E[X] = 0.1(E[O] + 1) + 0.9(0) = 0.1 + 0.1 \cdot E[O]$
$P(O = 0)$ = $0.1$
$P(O = n)$ = $0.1 \cdot 0.9^n$ for $n > 0$
So,
$$
E[O] = \sum_{k=0}^\infty k \cdot P(O=k) = 0.1 \sum_{k=0}^\infty k \cdot 0.9^k = 9 \>,
$$
leaving us with $E[X] =  0.1 \cdot (9 + 1) = 1$.

EDITED: using a shifted geometric distribution with $p=0.1$ for $O$
Is that correct? If not, where am I going wrong?
Comment: How do you know that someone is a customer if they don't place an initial order?
Comment: Just assume that out of a population of X's, 10% of them will place an initial order. Does that answer your question? (in the actual scenario, we're assuming a customer has already made an order, order 0, and now there's a .1 chance he places a second order, and a .9 chance that if he places a second, he will place a third, and a .9 chance that if he places a third, he will place a fourth…etc)
Comment: OK. I think my answer below works for that scenario. The expected number does not include order 0 of course.
Answer: This looks like a shifted geometric distribution with an initial coin toss. i.e. with probability 0.9, there are no purchases, and with probability 0.1, there is a purchase, with the possibility of a geometric number of further purchases. You are looking at the number of failures before the first success (i.e. refusal to purchase) - which is anything from 0 up.
$E(X)=0.9 \cdot 0 + 0.1 \cdot (1+9)=1$
The expectation of a shifted geometric $p$ is $(1-p)/p$, where $p=0.1$ in this case. That's the probability that a person ceases to be a customer. Once they're in the system, you expect 9 purchases (after the initial one.)
Thanks to Cardinal for a helpful comment. So yes, you got it right!
Comment: Regarding your answer: Conditional on the first success, do you not want the number of failures (purchases) *before* the first success (no purchase)? That is the geometric on the set $\{0,1,\ldots\}$ not $\{1,2,\ldots\}$ and so the expected value of this r.v. would be $\mu = 0.9/0.1 = 9$, yielding $\mathbb E X = 1$ as @Isaac has calculated in his question.
Comment: The geometric probability $p$ is the probability of a "success" and you are looking for the number of purchases until the first decision to purchase no more - so $p$ is the probability of not buying - which is 0.1, if I understood correctly.
Comment: Yes. That's correct. It is the shifted geometric. I'll fix my answer.
Comment: (+1) This method of proof, in particular, is one of my favorites and accords much more closely with one's intuition than other approaches. Even for finding the mean of the standard geometric distribution, this sort of "one-step" analysis allows for a quick proof that can easily be made rigorous and avoids the need of manipulating infinite series or generating functions.
Comment: Why do you expect 10 purchases? I expect 90 purchases (E[O], as written above). We agree on the expression for E[X], just not E[O]. Is mine incorrect above?
Comment: Ah, I see that you're modeling O as a geometrically distributed random variable with p=.1. I think it should be (1-.1)/.1 = 9, because we're looking for the # of orders before the first time the person does not order. This means E[X] = 1. Does that seem correct?
Comment: Does my edited question above correctly calculate it? I used a shifted geo dist instead of the unshifted one, as I do NOT want to count the total number of trials, just the total number of "failures" (e.g. orders). Leaving the answer to be E[X] = 1? Thanks again for your help. I haven't done probability for over a year now, and I sorely miss it. Very glad it came up at work today!
Comment: Thanks, all, for your help. I miss this sort of thing quite a bit.


Apply a product discount if orders are picked up

Question: I have a Drupal Commerce site where customers get to choose whether to ship the order, or if they want to come and pick it up. Picking up is free, obviously.
This part works already, and I don't need help with.
There is an additional discount that should apply to one specific product only when the customer comes to pick up his order. There could be other products in the order besides the one specific product, and those products would not be discounted. This discount would be applied if "picking up" is specified during the check out process.
I'm having a bit of trouble getting the event/conditions right: it seems to me that no shipping method has been picked when the sell price is calculated.
Menno
Comment: Will you provide some option like dropdown to let user select how he/she want to get delivered ?
Comment: Have you tried the [Commerce Pickup](https://drupal.org/project/commerce_pickup) module?
Comment: The free versus pickup part already works; I need to figure out how to apply the additional discount for pickup.
Answer: Aren't the shipping methods themselves using rules? I would try to edit the rule for the Pickup shipping method and see if I could add the discount from the Actions of that Rule.
If you know how to use Rules Components, you could further encapsulate this so all the discount-related stuff was in a separate Rule Component.


Find $\iint_Ay\,dA$, where $A$ is defined by $z=x+y^2$,$0\le x\le 1$ and $0\le y\le2$

Question: Can anyone help me to find the $\iint_Ay\,dA $ where $A$ is defined by $z=x+y^2$ and $0\le x\le1$ and $0\le y\le2$
What I was thinking to do is to put $y=\sqrt{z-x}$ but I am not sure that I am doing right because I cannot find the limits of the integral.
Comment: Always start by drawing a picture.Consider what sections of the surface looks like for x = const.
Answer: Running the following code in Mathematica:
<code>z[x_, y_] := x + y^2
dA = Sqrt[1 + D[z[x, y], x]^2 + D[z[x, y], y]^2];
Integrate[y*dA, {x, 0, 1}, {y, 0, 2}]
</code>
we can get the following results:
<code>(13 Sqrt[2])/3
</code>


Ubuntu Mail Server unreachable

Question: I have been trying to setup a mail server in ubuntu using this tutorial: http://flurdy.com/docs/postfix/index.html
I have completed the basic configurations (I havent reached the extend part yet)
So, I have used telnet and the following works:

send email to gmail
send mail to itself
forward the mail it receives (I have forwarded the mail I receive to an external account for testing purposes, so the above step forwards the email to another gmail account)

So my problem is I cannot send mail from gmail, I get '530 530 5.7.1 Invalid Address'.
All of what I have tried is:

I have tried pinging my mail server from another pc on the same network, cant find the server.
I disabled the router's firewall, forwarded the port and set up my mail server as an exposed host.
Disabled shorewall on my mail server.
Changed the shorewall policies to allow everything in.

At each of the above steps I tried sending an email from gmail to my mail server and I still get the same error.
I am really not sure what is happening, and am clueless of what to do.
Comment: Is your fqdn well configured?
Do you have a reverse host configured?
Comment: Thank you for kind of pointing me in the right direction. I had problems with the fqdn as well as the MX/SPF records
Answer: I just browsed through the link you gave and your question also mentions that - "I have tried pinging my mail server from another pc on the same network, cant find the server."
So it must be a DNS problem. On command line type
nslookup <your mail server fully qualified domain name>

like
nslookup mail.yahoo.com

If you get proper IP address of server then try using
dig -t mx <mail domain name>

like
dig -t mx yahoo.com

If you see IPs in both nslookup and dig then fine, else it is confirmed DNS problem.
Comment: Thank you also for kind of pointing me in the right direction. I had problems with the fqdn as well as the MX/SPF records. I am able to find the server now, however now the emails are bouncing back saying: Connection timed out.
Answer: Look in /var/log/mail.log to see exactly what the mail server is doing; paste the relevant entries in your question if they don't make sense to you.  Also, copies of your config files would probably help.
Comment: which config files do you need me to post?they are the same as the ones on the link (tutorial) posted above
Answer: Why cant you try out this :-http://jitamitra.blogspot.com/2009/03/configure-postfix-postfixadmin-dovecot.html
I found this is very easy way of configuration,Once you done you can customize it as you need, Just have look at this.

Ubuntu Mail Server unreachable


Is $M(L)=\left\{w \in L \mid \forall v \in \Sigma^+,vw \notin L\right\}$context-free?

Question: $L$ is a context-free language.
We define $M\left(L\right)=\left\{w \in L \mid \forall v \in \Sigma^+,vw \notin L\right\}$ .
It seems like $M\left(L\right)$ is the set of strings in $L$ which are not the suffix of other strings in $L$.
I've tried to solve it by using the CFG but failed. Can anyone gives some tips please?
Answer: I think $M\left(L\right)$ is not necessarily a context-free language, and I have found a counterexample for my homework this week:
$$L:=\left\{0^{i}1^{j}2^{k}\mid i,j,k\in\mathbb{N}^{+},i=j\lor j\neq k\right\}$$
where its corresponding $M\left(L\right)$ can be verified to be:
$$M\left(L\right) = \left\{0^{n}1^{n}2^{n}\mid n\in\mathbb{N}^{+}\right\}$$
which is obviously not context-free.
Are you also in the class of 2023(Fall)FLA@NJU? If so(or you are also doing your homework), please give a citation of this tips for the need of Academic Integrity.


Necessary topological conditions for all Caratheodory functions to be measurable

Question: If $(S,\Sigma)$ is a measurable space, and $X$ and $Y$ are topological spaces, then a function $f:S \times X \rightarrow Y$ is called a "Caratheodory function" if $s \mapsto f(s,x)$ is measurable (with respect to the Borel $\sigma$-algebra on $Y$) for each $x$ in $X$ and $x \mapsto f(s,x)$ is continuous for each $s$ in $S$. It is well-known that every Caratheodory function is measurable with respect to the product $\sigma$-algebra $\Sigma \otimes \mathcal{B}_X$ on $S \times X$ and the Borel $\sigma$-algebra on $Y$ when $X$ and $Y$ are metrizable spaces and $X$ is separable.
I would like to examine what happens when $X$ and $Y$ are not necessarily metrizable. I have in mind the particular example that every Caratheodory function is measurable if $Y$ is $\mathbb{R}^n$ and $X$ is $\mathbb{R}^+_\ell$ or $\mathbb{R}^+_u$ (i.e. $[0,\infty)$ equipped with the lower or upper limit topologies), for example by the construction used in this question.
I can prove every Caratheodory function is measurable under the assumptions (strictly weaker than $X$ is separable metrizable and $Y$ is metrizable) that $X$ is second countable and $Y$ is perfectly normal. To see this, suppose $f$ is a Caratheodory function; it suffices to show $f^{-1}(F)$ is measurable for any closed set $F \subset Y$. Since $Y$ is perfectly normal, every closed subset is $G_\delta$, so there is a countable sequence of open sets $V_1,V_2,\dots$ whose intersection is $F$; then using normality we can construct open sets $W_1,W_2,\dots$ such that $F \subset W_i \subset \overline{W_i} \subset V_i$ for each $i$ (incidentally, the existence for every closed set $F$ a countable collection of open sets, each containing $F$ and for which the intersection of their closures is $F$ implies the space is perfectly normal, and therefore is an equivalent characterization of perfect normality; see this question). Then if $\{U_1,U_2,\dots\}$ is a countable base for $X$ and $\mathcal{X}$ is a countable dense subset of $X$ (which can be obtained, for example, by picking an element from each $U_i$), we have
$$f^{-1}(F) = \bigcap_{i\in \mathbb{N}} \,\bigcup_{j \in \mathbb{N}} \, \bigcap_{x \in \mathcal{X} \cap U_j}\{s \in S\,|\, f(s,x) \in \overline{W_i}\} \times U_j,$$
which shows $f^{-1}(F)$ is in $\Sigma \otimes \mathcal{B}_X$.
Frustratingly, this does not cover the case I mentioned earlier, as the lower/upper limit topologies on $\mathbb{R}$ are not second countable (they are separable and first countable, but not second countable). Are there ways to relax the conditions on the topologies of $X$ and $Y$ to account for this case? Is it possible to give nice necessary conditions on the topologies of $X$ and $Y$ for all Caratheodory functions to be measurable?
Answer: Well, after thinking some more, I've found weaker topological conditions on $X$ that cover these other cases, so I'm answering my own question if for no other reason than to put down my thoughts. I'm not totally satisfied with this answer, but it at least works.
If $X$ is a topological space, let $\mathcal{M}(X,X)$ denote the set of all (Borel) measurable functions from $X$ to $X$, which we equip with the topology of pointwise convergence, and let $B_f(X)$ denote the subset of measurable functions $h$ whose images are finite sets. I'm going to say a topological space $X$ "has sequentially-approximable self-maps" if the smallest sequentially closed set in $\mathcal{M}(X,X)$ containing $B_f(X)$ is, in fact, all of $\mathcal{M}(X,X)$ (i.e. the transfinite sequential closure of $B_f(X)$ is $\mathcal{M}(X,X)$).
Note that this is equivalent to saying that just the identity map is in the transfinite sequential closure, as if $f:X \rightarrow X$ is any other measurable function, then $h \circ f$ is in $B_f(X)$ if $h$ is, and if we let $\{B_f^\alpha(X)\}_{\alpha \in \text{Ord}}$ denote the transfinite sequence of sequential closures of $B_f(X)$, then transfinite induction shows that $h \circ f$ is in $B_f^\alpha(X)$ if $h$ is (as if $h_n \rightarrow h$ pointwise, then $h_n \circ f \rightarrow h \circ f$ pointwise), and so if the identity map is in the transfinite sequential closure of $B_f(X)$ (i.e. $B_f^{\omega_1}(X)$, where $\omega_1$ is the first uncountable cardinal), then so is $\text{id} \circ f = f$.
Now, I claim that if $(S, \Sigma)$ is a measurable space, $X$ is a topological space which has sequentially-approximable self-maps, and $Y$ is a perfectly normal topological space, then every Caratheodory function $f: S \times X \rightarrow Y$ is measurable. To see this, for any $h:X \rightarrow X$, let $f_h(s,x) = f(s,h(x))$. We will show that $f_h$ is measurable for all $h$ in $B_f^\alpha(X)$ by transfinite induction. For the base case, we note that if $F$ is any Borel subset of $Y$ and $h$ is any function in $B_f(X)$, then
$$f_h^{-1}(F) = \bigcup_{x \in \text{im } h} \{s\in S\,|\, f(s,x) \in F\} \times h^{-1}(B_x),$$
where $B_x$ is any Borel subset of $X$ whose intersection with $\text{im }h$ is precisely the points in $\text{im }h$ which are topologically indistinguishable from $x$ (i.e. we can take $B_x = \{x\}$ if singletons are Borel in $X$; otherwise for each $y$ in $\text{im }h$ which is distinguishable from $x$, there is either an open or closed set containing $x$ and not $y$, so the intersection of these sets for every $y \in \text{im }h$ distinguishable from $x$ gives a set satsifying the requirements of $B_x$). This expresses $f_h^{-1}(F)$ as a finite union of measurable sets, since $s \mapsto f(s,x)$ is measurable for each $x$, $\text{im }h$ is finite, and $f(s,x) \in F$ if and only if $f(s,y) \in F$ when $x$ and $y$ are topologically indistinguishable, as $x \mapsto f(s,x)$ is continuous for each $s$, and therefore must send indistinguishable points to indistinguishable points, and the set $F$ is Borel in $Y$, and therefore contains or is disjoint from each indistinguishability class. Thus, $f_h$ is measurable, and since $h$ was arbitrary, we, in fact, have that $f_h$ is measurable for all $h$ in $B_f^0(X)$. Now, suppose $\alpha$ is a successor ordinal, $f_h$ is measurable for all $h$ in $B_f^{\alpha-1}(X)$, and $h$ is in $B_f^\alpha(X)$. Then there is a sequence $\{h_n\}_{n \in \mathbb{N}}$ in $B_f^{\alpha-1}(X)$ such that $h_n \rightarrow h$ pointwise. Then, since $x \mapsto f(s,x)$ is continuous for each $s$ in $S$, we have that $f(s,h_n(x)) \rightarrow f(s,h(x))$ for each $s$ in $S$ and $x$ in $X$. Thus, $f_{h_n} \rightarrow f_h$ pointwise, and since $Y$ is perfectly normal, this means $f_h$ is measurable (see Cristian Paris's answer and my comment here). On the other hand, if $\alpha$ is a limit ordinal, and we assume that $f_h$ is measurable if $h$ is in $B_f^{\beta}(X)$ for any $\beta < \alpha$, if $h$ is in $B_f^{\alpha}(X)$, then $h$ is in $B_f^{\beta}(X)$ for some $\beta < \alpha$, and so $f_h$ is measurable. Thus, the induction is complete, and so since the identity map is in $B^{\omega_1}_f(X)$, we have $f_{\text{id}} = f$ is measurable, which is what we wanted.
Now I want to note that this encompasses all of the situations I discussed in my question, i.e. that second countable spaces necessarily have sequentially-approximable self-maps, but that so do $\mathbb{R}_\ell^+$ and $\mathbb{R}_u^+$. So first we show that second countable spaces necessarily have sequentially-approximable self-maps. Suppose $\{U_1,U_2,\dots\}$ is a countable base for a topological space $X$. Then for every subset $S \subset \{1,\dots,n\}$, let
$$U^n_S = \left(\bigcap_{i \in S} U_i \right) \cap \left(\bigcap_{i \in S^c} U_i^c \right),$$
where complementation is done in $\{1,\dots,n\}$ or $X$ accordingly. Then, for each $n$, $\{U^n_S\}_{S \subset \{1,\dots,n\}}$ is a (finite) Borel partition of $X$; we will define functions which are constant on these sets which converge to the identity map. For each natural $n$ and set $S \subset \{1,\dots,n\}$ for which $U^n_S$ is nonempty, let $x^n_S$ be a point in $U^n_S$ (any point suffices). Then let $f_n:X \rightarrow X$ be the function which is constant and equal to $x^n_S$ on $U^n_S$ for each $S \subset \{1,\dots,n\}$ (which is valid since $\{U^n_S\}_{S \subset \{1,\dots,n\}}$ is a partition of $X$). Note that $f_n$ has finite image (its image is $\{x^n_S\}_{S \subset \{1,\dots,n\}}$), and that, for any $F$, $f_n^{-1}(F)$ is a union of some subcollection of $\{U^n_S\}_{S \subset \{1,\dots,n\}}$, which means $f_n$ is measurable. Thus, we will have shown $X$ has sequentially-approximable self-maps if $f_n \rightarrow \text{id}$ pointwise. To see this, fix any point $x$ in $X$ and any open set $V$ containing it; we will show $f_n(x)$ is in $V$ for sufficiently large $n$, which shows that $f_n(x) \rightarrow x$, which is what we want. There's an $i$ such that $x \in U_i \subset V$ since $\{U_1,U_2,\dots\}$ is a base for the topology of $X$. Thus, for $n \geq i$, we have that $f_n(x) = x^n_S \in U^n_S$ where $S$ is the subset of $\{1,\dots,n\}$ such that $x$ is in $U^n_S$. Since $U^n_S$ must be a subset of $U_i$ (since $n \geq i$, it must be a subset of $U_i$ or of $U_i^c$, and since it contains $x$, an element of $U_i$, it must be a subset of $U_i$), we have that $f_n(x)$ is in $U_i$ for all $n \geq i$, so $f_n(x)$ is in $V$ for all $n \geq i$. Thus, $f_n(x) \rightarrow x$ for all $x$ in $X$, and so we are done.
Finally, we show that $\mathbb{R}_\ell^+$ and $\mathbb{R}_u^+$ have sequentially-approximable self-maps as well. For each natural $n$, let $f_n^\ell$ be the function which is equal to $k/n$ on the interval $[(k-1)/n,k/n)$ for $k$ in $\{1,\dots,n^2\}$ and is zero on $[n,\infty)$, and similarly let $f_n^u$ be the function which is equal to $(k-1)/n$ on the interval $((k-1)/n,k/n]$ for $k$ in $\{1,\dots,n^2\}$ and is zero on $\{0\} \cup (n,\infty)$. Then $f_n^\ell$ is in $B_f(\mathbb{R}_{\ell}^+)$ and $f_n^u$ is in $B_f(\mathbb{R}_u^+)$ for every $n$, and it is easy to see that $f_n^\ell \rightarrow \text{id}$ pointwise in $\mathbb{R}_{\ell}^+$ and $f_n^u \rightarrow \text{id}$ pointwise in $\mathbb{R}_u^+$.
I'm still not completely satisfied with this answer, as it somehow feels like it was reverse engineered to account for the $\mathbb{R}_\ell^+$ and $\mathbb{R}_u^+$ cases. Nonetheless, it does give sufficiently weak topological conditions to cover the cases I was concerned about.


Likelihood between two functions

Question: I have a function $f(x)$ describing a physical process, and a function $g(x)$ that tries to approximate it. I can clearly see by eye when the two functions are close enough, but I would like a mathematical tool to do it in a reproducible way.
For now, I am using as a figure of merit $\int_0^b \left | f(x) - g(x) \right | dx$, where $b$ is chosen suitably (my functions are even, positive and are equal to 1 apart from a small area around the origin). The result is normalised to $\int_0^b \left | f(x) - 1 \right | dx$. My -arbitrary- level of acceptance is when this value is equal to 0.05.
Unfortunately this procedure doesn't agree well with what my eye would the me. For example these two functions:

are considered "alike" ($f(x)$ in blue and $g_1(x)$ in yellow. $\Gamma_1 = 1$, $\Gamma_2 = 0.508$, $s=0.01$), while these two:

are not ($f(x)$ in blue and $g_2(x)$ in yellow. $\Gamma_1 = 1$, $\Gamma_2 = 1.5$, $s=0.01$). I have read of some other methods to estimate the likelihood between two functions, but couldn't find a suitable one. I guess an ideal method would be a measure of my procedure mixed with a measure of the distance between the curves in every point, but I haven't found anything like it.
For completeness, the function $f(x)$ I'm using is:
$f(x) = 1 - \frac{\eta + \mu}{2\mu} e^{(-\eta+\mu) |x|} - \frac{-\eta + \mu}{2\mu}e^{(-\eta-\mu) |x|}$
where $\eta=-\frac{\Gamma_1 + \Gamma_2}{2}$ and $\mu=\sqrt{\frac{(\Gamma_1 - \Gamma_2)^2}{4} - s \Gamma_1 \Gamma_2}$. The two functions I am comparing it to are $g_1 (x) = 1 - e^{-\frac{\Gamma_1 + \Gamma_2}{2} |x|} \left ( \cos ( \sqrt{s \Gamma_1 \Gamma_2} |x|) + \frac{\Gamma_1 + \Gamma_2}{2\sqrt{s \Gamma_1 \Gamma_2}} \sin ( \sqrt{s \Gamma_1 \Gamma_2} |x|) \right )$ and $g_2 (x) = \left ( 1-e^{-\frac{\Gamma_1}{2}|x|} \right )^2$. The only constraints on the parameter are $s>0$, $\Gamma_1>0$ and $\Gamma_2>\Gamma_1/2$.
Answer: Seeing as these are empirical distributions, you should aim to use the ks.test function in R. It is the Kolomogrov-Smirnov test and it can be used to measure the distance between two curves, namely the Empirical Distribution Function of the sample and a reference Cumulative Distribution Function. It is a measure of distance by measuring for a difference in location and shape, which seem appropriate in this case. It may be a little more sensitive compared to the eyeball test, but it is not nearly as sensitive as Anderson Darling and Shapiro Wilks tests. To use the KS test, it is simply ks.test(fx, gx) can can be used for two sample tests.
Comment: Thank you for the answer! I had actually seen this test, but I was put off by the fact that they seem to work for probability distributions. I am comparing two functions depending on time. Would that still work? In principle, I could build an histogram from them, and then compare them, but seems a bit involved...
Comment: @SamueleGrandi I see your conundrum. Here is the link to another similar question. http://math.stackexchange.com/questions/760819/is-there-any-statistical-method-to-compare-two-curves . I thought these were to gamma distributions, not to arbitrary functions.
Comment: thank you very much for your help. The answer in the link you provided is the same procedure we are using at the moment. It has some issues, but overall it's a good measure. Thanks again!

Likelihood between two functions


Filter by taxonomy in Views table

Question: I have a vocabulary Area for classifying maths problems, with two parent terms (Pure and Applied) and appropriate child terms (Geometry, etc.) under each. Problems (a content type) are tagged with the appropriate areas of mathematics that they cover.
I also have a table page defined in Views with filter criteria Type (= Problem) and Area (exposed), for listing all the problems.
The problem I have is as follows: If someone selects `Applied Mathematics', nothing appears, because Problems are only tagged with the child terms.
How can I get all the Problems to show up?
In Drupal 7 I should add!
Comment: Tell us your view settings.  Which filters and contextual filters? Is it a page or block?
Answer: If you look at the default Taxonomy Term view provided with views, you'll see that it has a contextual filters Content: Has taxonomy term ID (with depth) and Content: Has taxonomy term ID depth modifier. Both are needed. If you look at the description for the Depth field for the first filter you'll see the following:

The depth will match nodes tagged with terms in the hierarchy. For example, if you have the term "fruit" and a child term "apple", with a depth of 1 (or higher) then filtering for the term "fruit" will get nodes that are tagged with "apple" as well as "fruit". If negative, the reverse is true; searching for "apple" will also pick up nodes tagged with "fruit" if depth is -1 (or lower).

In your case fruit is applied and apple is, for example, Geometry. So if you specify a depth of 1 or higher you should get the behaviour you want.

Filter by taxonomy in Views table


How to connect Node.js app properly to Cassandra node?

Question: I have two Cassandra nodes hosted on two IPs. Now, when I am connecting to one of those nodes via cassandra-driver in Node.js from Windows, I am getting 'connection timed out' and 'host unreachable' kind of errors. However, I am able to connect to those nodes via CQLSH from outside of their network.
Am I doing something wrong? Here is the sample code.
var cassandra = require('cassandra-driver');

var uuid = require('uuid')
var client = new cassandra.Client({ contactPoints: ['(PUBLIC IP Here) X.X.X.X:9042'], localDataCenter: 'datacenter1', keyspace: 'ksks' });

function getAllPersons() {
    var query = 'SELECT * FROM person';
    return new Promise((resolve, reject) => {
        client.connect(function (err) {
            if (err) return console.error(err);
            else {
                client.execute(query, function (err, result) {
                    if(err)  {
                        reject([])
                    }
                    else {
                        if(result.rows.length) {
                            resolve(result.rows);
                        }
                        else {}
                            reject([])
                    }
                });
            }
        });
     });
}

In the cassandra.yaml, I have these values:
listen_address: 10.0.0.4
native_transport_port: 9042
rpc_address: 10.0.0.4
rpc_port: 9160
api_port: 10000
api_address: 10.0.0.4

What do I need to change? The nodes are working fine and can CQLSH to each other (from remote networks as well).
Comment: Your best bet is to wireshark the connection
Answer: If you are using a public IP to access the cluster remotely your configurations are not correct.
This table might help you figure out the correct IPs in the scylla.yaml:
https://docs.scylladb.com/operating-scylla/procedures/cluster-management/ec2_dc/#ec2-configuration-table
Do NOT use Ec2Snitch unless you are on AWS. The table is just a reference.


Symfony 3 functional test: authenticate user of own User class

Question: I'd like to run functional tests on a section of my website which requires authentication. I found a solution for Symfony 2.x here. However, this does not work for Symfony3 as this line is now deprecated:
self::$kernel->getContainer()->get('security.context')->setToken($token);

My question is, how do I go around this and make it work with Symfony3? Thank you.
Answer: In Symfony 3, the SecurityContext was split into the TokenStorage and the AuthorizationChecker. Thus, you need to use the security.token_storage service:
self::$kernel->getContainer()->get('security.token_storage')->setToken($token);

However, a simpler approach would be to switch to HTTP Basic auth in your tests and configure the logged in user as described in http://symfony.com/doc/current/cookbook/testing/http_authentication.html.


Correct my sketch of proof about the convexity of the "natural" power tower on $[1,\infty)$

Question: Hi I want to show the following fact :
Problem :
Let $x\geq 1$ and $n\geq 1$ a natural number and define:
$$f(x)={}^{2n}x=\underbrace{x^{x^{⋰^{x}}}}_{2n\text { times}}$$
Then we have :
$$f''(x)\ge 0$$

My sketch of proof for $x\ge y\geq 1$ :
We suppose by induction that $k\geq 2$ a natural number :
$${}^{k-1}x+{}^{k-1}y\geq {}^{k-1}\left(\frac{x+y}{2}\right)*2$$
Or :
$${}^{k-1}x\ln\left(\frac{x+y}{2}\right)+{}^{k-1}y\ln\left(\frac{x+y}{2}\right)\geq{}^{k-1}\left(\frac{x+y}{2}\right)*2\ln\left(\frac{x+y}{2}\right)$$
Now we want show that :
$${}^{k-1}x\ln\left(\frac{x+y}{2}\right)+{}^{k-1}y\ln\left(\frac{x+y}{2}\right)\leq {}^{k-1}x\ln\left(x\right)+{}^{k-1}y\ln\left(y\right)$$
Or :
$${}^{k-1}x\ln\left(\frac{\frac{x}{y}+1}{2}\right)+{}^{k-1}y\ln\left(\frac{\frac{y}{x}+1}{2}\right)
\ge 0$$
As we have suppose that the function $g(x)=^{2n-1}x$ is convex on the interval $I=[1,\infty)$ (we use Jensen's definition +continuity) next we use Karamata's inequality with $g(x)$ to have the  inequalities :
$$x\ln\left(\frac{\frac{x}{y}+1}{2}\right)\ge 0$$
And
$$x\ln\left(\frac{\frac{x}{y}+1}{2}\right)+y\ln\left(\frac{\frac{y}{x}+1}{2}\right)
\ge 0$$
It works because the function $g$ is also increasing . Conclude by induction . Obviously log convexity implies convexity also .
We are done

My natural question is :

Is my strategy correct ?

Thanks in advance .
Comment: I do not understand the above definition of $f(x)$. What does this notation mean in usual terms ?
Comment: @Peter Good question see Rucker https://mathworld.wolfram.com/PowerTower.html .
Comment: See https://math.meta.stackexchange.com/a/34055/42969 for some better ways to typeset a "left exponent", for example `{}^{2n}x`
Comment: Shouldn't the induction hypothesis be that ${}^{2n-2}x$ is convex?
Comment: @MartinR Second good question !  No because I use also the convexity in the odd case and because obviously $\ln$ decreases only one exponent . Unfortunetaly it's not the case on the entire interval $(0,1]$ . Thanks for pointing out this kind of ambiguity.:-).
Comment: @MartinR thanks again for the helps see the question edited .
Comment: @MartinR Woopsie thanks !
Comment: @MartinR No problem sir !
Answer: For $x>0$, define recursively $f_n(x)$ by $f_0(x) = 1$ and $f_{n+1}(x) = x^{f_n(x)}$ for every $n \ge 0$. Hence, $f_1(x)=x$, $f_2(x)=x^x$, $f_3(x)=x^{(x^x)}$ and so on.
We prove by recursion that for every $n \ge 0$,
$$\forall x \ge 1,~f_n(x) \ge 1 \text{ and } f_n'(x) \ge 0 \text{ and } f_n''(x) \ge 0.$$
When $n=0$, these large inequalities are equalities.
Let $n \ge 0$ and assume that the inequalities above hold. Then for every $x \ge 1$,
$$f_{n+1}(x) = \exp(f_n(x)\ln x) \ge \exp(0) = 1,$$
$$f_{n+1}'(x) = \Big(f_n'(x)\ln x + f_n(x)\frac{1}{x} \Big) f_{n+1}(x) \ge (0+1) \times 1  = 1 \ge 0,$$
\begin{eqnarray*}
f_{n+1}'(x)
&=& \Big(f_n''(x)\ln x + 2f_n'(x)\frac{1}{x} - f_n(x)\frac{1}{x^2} \Big) f_{n+1}(x) + \Big(f_n'(x)\ln x + f_n(x)\frac1x \Big) f_{n+1}'(x) \\
&=& \Big(f_n''(x)\ln x + 2\frac{f_n'(x)}{x} - \frac{f_n(x)}{x^2} \Big) f_{n+1}(x) + \Big(f_n'(x)\ln x + \frac{f_n(x)}{x} \Big)^2 f_{n+1}(x) \\
&=& \Big(f_n''(x)\ln x + 2\frac{f_n'(x)}{x} + \frac{f_n(x)^2-f_n(x)}{x^2} + f_n'(x)^2\ln^2 x + 2f_n'(x)\ln x \frac{f_n(x)}{x} \Big) f_{n+1}(x) \\
&\ge& 0,
\end{eqnarray*}
which shows the inequalities for the integer $n+1$.
Hence for every $n \ge 0$, the function $f_n$ is non-decreasing and convex on $[1,+\infty[$.


Detele() - Play Framework - Compilation error

Question: Introdução
Estou fazendo um CRUD na minha aplicação, tudo está perfeito porém meu delete está dando erro na hora de compilar
Erro

Task.java
package models;

import java.util.*;
import java.util.*;
import play.db.ebean.*;
import play.data.validation.Constraints.*;
import javax.persistence.*;

@Entity
public class Task extends Model{

    @Id
    public Long id;

    @Required
    public String tarefas;

    public static Finder find = new Finder(Long.class, Task.class);

    public static List<Task> all() {
        return find.all();
    }

    public static void create(Task task) {
        task.save();
    }

    public static void delete(Long id) {
        find.ref(id).delete();
    }

}

Controller
package controllers;

import play.*;
import play.mvc.*;
import play.data.*;
import play.data.Form;
import views.html.*;
import models.*;

public class Application extends Controller {
    static Form<Task> taskForm = Form.form(Task.class);

    public static Result index() {
        return redirect(routes.Application.tasks());
    }

    public static Result tasks() {
        return ok(views.html.index.render(Task.all(), taskForm));
    }

    public static Result newTask() {
        Form<Task> filledForm = taskForm.bindFromRequest();
        if(filledForm.hasErrors()){
            return badRequest(
                    index.render(Task.all(), filledForm)
            );
        }else{
            Task.create(filledForm.get());
            return redirect(routes.Application.tasks());
        }
    }

    public static Result deleteTask(Long id) {
        Task.delete(id);
        return redirect(routes.Application.tasks());
    }
}

Comment: Poderia colocar o erro em texto?
Comment: como assim erro em texto?
Comment: Em algo que não seja imagem
Answer: Estudando o Ebean pelo site, notei o uso do Singleton Ebean e a rotina deveria ficar assim:
public static void delete(Long id) {
    Ebean.delete(Ebean.find(Task.class,id));
}

Answer: Troque isso:
public static Finder find = new Finder(Long.class, Task.class);

Por isso:
private  static Finder<Long, Task> find = new Finder<Long, Task>(Long.class, Task.class);

O Finder cria um localizador (find) para a entidade do tido tipo informado com o ID do tipo informado.
Você também pode tentar usar:
find.byId(id).delete();
Vêja esse exemplo: Play 2.3.5 Master-Detail
Comment: OK, vou editar minha resposta.
Comment: É legal explicar, ainda que brevemente, porquê seu código resolve o problema. O guia [answer] tem mais detalhes.


Separar fones fixos de móveis para acrescentar nono dígito

Question: Eu tenho uma planilha com quase 60 mil linhas, com 3 colunas:
Nome | Fone 1 | Fone 2
Nas duas colunas fone tenho números de telefones fixos e móveis e para mim a lógica é simples: Fone fixo é um número MENOR que 8 digitos. Na lógica a fórmula  é "se o número for menor que tal; coloque o nono dígito; se não só copie o número". Mas, não estou conseguindo
=SE((F1>E4);D4&" "&E4;D4&" 9"&E4)
Onde "D4" é o código de área.
Alguém pode me ajudar?
Comment: Como assim "não funciona"? O que exatamente acontece de errado? Você deve informar o erro que está acontecendo.
Answer: O telefone celular antigo também tem 8 dígitos, por isso está tendo essa dificuldade.
Faça da seguinte maneira:
=SE(F1<55555555;D4&" "&E4;D4&" 9"&E4)

Sendo o F1 o númro do celular.
Sugiro porém, após ter esses dados, copiar e colar valores e utilizar a formatação condicional, deixando somente os número, sem espaços.
[>9999999999]"("##") "#-####-####; "("##") "####-####

Answer: Solução
Você pode utilizar Regex como função do VBA para validar isto.
Regex
Habilitar o Regex no Excel

RegEx precisa ser habilitado, Habilite o modo Desenvolvedor
Na aba 'Desenvolvedor', clique em 'Visual Basic' e a janela do VBA irá abrir.
Vá em 'Ferramentas' -> 'Referências...' e uma janela abrirá.
Procure por 'Microsoft VBScript Regular Expressions 5.5', como na imagem abaixo. E habilite esta opção.

Expressão
A expressão para encontrar números de celular é a seguinte: ^[6|7|8|9](?:\d{7}|\d{3}\s*-\s*\d{4})$
Em que encontra números que começam com 6,7,8 e 9 e possuam 7 dígitos após iniciar com estes números ou 3 dígitos - (hífen) 4 dígitos.

Obs.: Em São Paulo os números que iniciam com 5 são híbridos entre telefonia fixa e móvel. (teleco). Portanto, não há uma regra clara para os números que iniciam com 5.

O demo do Regex101 pode ser visto e o Debuggex também.
UDF (User Defined Function) no Excel VBA
Código
Primeiro insira esta função em um módulo.
Function ValidarCelular(Myrange As Range) As String
    On Error GoTo ErrHandler:
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim strOutput As String

    strPattern = "^[6|7|8|9](?:\d{7}|\d{3}-\d{4})$"

    If strPattern <> "" Then
        strInput = Trim(Myrange.Value)
        strReplace = "9" & strInput

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With
            If regEx.test(strInput) Then
                ValidarCelular = regEx.Replace(strInput, strReplace)
            Else
                ValidarCelular = Myrange.Value
            End If
    End If
Exit Function
ErrHandler:
    ' Tratamento de Erro
    ValidarCelular= CVErr(xlErrNA)
    On Error GoTo 0
End Function

Resultado
O teste foi feito com dados de validação na coluna A e inserindo a função =ValidarCelular(A1) na coluna B.

Explicação Código

Cria a função ValidarCelular com MyRange como variável de entrada, ou seja, uma célula de variável de entrada.
Adiciona o padrão da Regex em strPattern
A entrada do Regex é strInput, que utiliza a função Trim() para remover os espaços em branco no início e fim.
O strReplace é a string que substituirá o que está na célula, caso seja um número de celular. Adicionando o número 9 na frente com "9" & strInput


ssreflect: elementary algebraic simplification

Question: Having this lemma
Lemma my_lemma n : n %/ 4 * 4 + n %% 4 * 5 - n %% 4 * 4 = n.
Proof.
  (* ? *)
  (* n %/ 4 * 4 + n %% 4 = n. *)
  symmetry. apply: divn_eq n 4.
Qed.

How can I convert n %% 4 * 5 - n %% 4 * 4 to n %% 4? Then in will be a piece of cake.
Answer: To solve this problem, the idiomatic approach in ssreflect is to do rewrite using all the theorems about arithmetic at hand.  This requires a little search.  I suggest you use the Search command extensively.
The first hurdle is that your formula contains (A + B - C) which is not the same thing as (A + (B - C)), because of the special behavior of truncated subtraction.  To convert between the two, you can look for a theorem.  I typed the following Search Command.
Search (_ + _ - _).

Among the theorems that were listed I was satisfied with addnBA (associativity between addition and subtraction), but this lemma has a side condition, which I want to prove first.  So I use the following rewrite command.
rewrite -addnBA; last first.

Here I want to factor out the multiplication in the comparison.  I look for a theorem containing this pattern with the following Search command.
Search _ (_ * _ <= _ * _).
Please note the first _ pattern in this Search command, it is important, if you don't include it, only some of the interesting theorems are listed, and the one we want won't appear.  The one I want is leq_mul2l
I perform this proof in the following manner:
by rewrite leq_mul2l orbC.

After rewrite leq_mul2l the statement is an _ || _ statement (boolean disjunction), and the right hand side is obviously true modulo computation (in ssreflect), by commuting this boolean disjunction, I make so that the goal can be solved directly without further ado.
Now, we come to distributivity of multiplication over subtraction.  Here search commands are more tricky to use, because distributivity laws are treated with a keyword.
Search (_ * (_ - _)).

Does not give any useful result, but there is useful documentation in ssrnat about naming patterns.  It tells us that when subtraction is a secondary operation, then B is likely to appear in the theorem name.  Here we want a theorem that about natural numbers, so it should be in ssrnat, so I attempt the following.
Search "B" in ssrnat.

This tells me that there are some theorems whose statement relies on concepts like left_distributive and right_distributive.  You can understant this concepts by printing them.
Print right_distributive.

In the long run, you tend to remember the names of theorems you use often, so in my case, I knew I was going to use mulnBr, because the subtraction is on the right of a multiplication, and we are working with natural numbers.  The math-comp library is designed with a strong attention to regularity of naming.
So we can now finish the modification in the following manner:
rewrite -mulnBr muln1.

and you can finally apply the lemma you wanted to apply.
The full script is as follows:
Lemma my_lemma n : n %/ 4 * 4 + n %% 4 * 5 - n %% 4 * 4 = n.
Proof.
symmetry.
rewrite -addnBA; last first.
  by rewrite leq_mul2l orbC.
rewrite -mulnBr muln1.
apply: divn_eq n 4.
Qed.

Comment: `rewrite -leq_mul2l` gives an error:

`((_ == 0) || (_ <= _))
does not match any subterm of the goal`

We need to use `rewrite leq_mul2l`.
Comment: @Yves What a great writeup, I added the link to it to the Mathcomp wiki: https://github.com/math-comp/math-comp/wiki/Search#examples (I hope you don't mind)
Comment: Also, a tad shorter proof: `rewrite -addnBA; last by rewrite leq_mul2l orbC.
by rewrite -mulnBr muln1 -divn_eq.`
Comment: I am still upset that we cannot use just `Search` to find all the relevant theorems.  It has been annoying me for a long time, but I still don't see how to get a single tool that will assist newcomers in a satisfactory way.


Change NSString to int value?

Question: I am having trouble trying to run this test due to an error on the first line of this code that states:

Incompatible pointer to integer conversion initializing 'int' with an
  expression of type 'NSString *'

- (IBAction)Button:(id)sender
{
  int x = TramNumber.text;
  if (x < 9)
  {
     Tramresult.text = [NSString stringWithFormat:@"lol"];
  }
  else
  {
    NSLog (@"x is less than 9!");
  }
}
@end

Please help. I am on iOS and running xCode 5.1.1 if that helps.
Comment: I suggest you use `NSInteger` and not `int`. `int` 32 bit and `NSInteger` a typedef for the systems native bit size, so 64 on 63 bits CPU en 32 on 32 bits systems.
Comment: Trivially reproducible: `int x = (NSString*)nil;` So *why* does the compiler warn about that?
Answer: You are representing NSString value wrong.
Use this code sample to solve your problem:
int x = [TramNumber.text intValue];

To represent int value from your textfield.
Answer: int x = [TramNumber.text intValue];

You just need to convert NSString to int.
Answer: You cannot assign text as an integer.
You should cast NSString to int like this:
int x = [TramNumber.text intValue];

Answer: Just try this:
NSString *code = dic[@"code"];
int statusCode = [code intValue];

NSLog(@"%d",statusCode);

if(statusCode==1)//........cont...

Change NSString to int value?


How to set HTML content into an iframe

Question: I have a HTML string

  Hello world

and I want to set it to an iframe with JavaScript. I am trying to set the HTML like this:
contentWindow.document.body.innerHTML

or
contentDocument.body.innerHTML

or
document.body.innerHTML

but IE gives "Access is denied." or "Object does not support this property or method." or "Invalid final element to the action." errors.
Here is my full code:
<!DOCTYPE html>

This is iframe:

Your browser does not support iframes.

Comment: Why you not load a page it works very well? why you want to use a string to load? let me know
Answer: You could use:
document.getElementById('iframe1').contentWindow.document.write("Hello world");

Here's a jsFiddle, which works in all major browsers.
Note that instead of contentDocument.write you should use contentWindow.document.write: this makes it work in IE7 as well.
Comment: I needed to use open/close to get it working in chrome:
iframe.contentWindow.document.open('text/htmlreplace');
iframe.contentWindow.document.write(content);
iframe.contentWindow.document.close();
Comment: If you don't want to append, you can do it with `document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);`
[(source)](https://stackoverflow.com/a/8322025/1717828).
Comment: note, if you are reading and writing in and out iframe, you will need to write document.getElementById('iframe1').contentWindow.document.write("");
to have empty string reading like this
var iframe_html = document.getElementById('iframe_exe_uploader').contentWindow.document.body.innerHTML;
Answer: var htmlString="Hello world";
var myIFrame = document.getElementById('iframe1');
myIFrame.src="javascript:'"+htmlString+"'";

With html5 you'll be able to use the srcdoc attribute.
Answer: The innerHTML is a bit tricky especially in IE, where elements like thead are read-only and cause a lot of trouble.
Based on the documentation on msdn you might try documentMode which provides a innerHTML property.
myIFrame = myIFrame.contentWindow ||
    myIFrame.contentDocument.document ||
    myIFrame.contentDocument;
myIFrame.document.open();
myIFrame.document.write('Your HTML Code');
myIFrame.document.close();

this might only work in IE.

http://msdn.microsoft.com/en-us/library/ie/ms535862(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ie/ms533897(v=vs.85).aspx
Answer: In 2023, the correct answer to this problem is to use the srcdoc attribute of the  element. I can be done straight in your HTML file or with javascript:
document.getElementById('iframe').srcdoc = "Hello world!";

Answer: How about document.documentElement.innerHTML. But do know that everything in the page will be replaced even the script that does that.
For an iframe it would be like this myIFrame.contentWindow.document.documentElement.innerHTML
Comment: Thanks for your answer, but if I use this code ie say this error: "Invalid final element to the action."
Answer: I have a problem with 'origin' with the answers here. This is how it's work for me:
const frame1 = document.createElement('iframe');
frame1.name = 'frame1';
//not have to set this style,just for demo
frame1.style.position = 'absolute';
frame1.style.height = '800px';
frame1.style.top = '100px';
frame1.style.left = '100px';
frame1.style.background = 'white';

document.body.appendChild(frame1);
const frameDoc =
  frame1.contentWindow || frame1.contentDocument.document ||
  frame1.contentDocument;

frameDoc.document.write('<title></title>Hello world');
frameDoc.document.close();

Answer: try it:
$('iframe').load(function() {
    $(this).contents().find('body').append("Hello world");
});

update:
$(function(){
    $('iframe').load(function() {
        $(this).contents().find('body').append("Hello world");
    });
})

Comment: An answer using vanilla JS was expected, this example uses jQuery.

How to set HTML content into an iframe


Best approach to detect iPad Safari user

Question: What is the best approach to add code for detecting an iPad Safari user. I mean should we use
1. CSS (through link media..)
2. JS (through navigator object)
I have heard that using user-agent string is not the best way to detect iPad, because of inconsistencies.
Please suggest. Thank you.

I also have a follow-up question;
Actually the code to detect desktop/iPad is going to be part of JSP (and not static HTML files)...Now in my app, there are 200+ pages..So where exactly should I be adding the code for detection and how exactly should I add it? I mean do I have to update somewhere in the servlet web.xml file..
Sorry for mixing the 2 questions..But just added here as both are related questions..
Comment: @hmthur The main question still is **"What exactly do you want to acieve by it"**.
Comment: It totally depends on your use case. What exactly do you want to acieve by makingthis distiction? What about Android tablets?
Comment: That is what I am trying to detect..1) Device: iPad and 2) Browser: Mobile Safari..
Comment: I want to apply different styles (through seperate CSS) for both desktop/iPad..
Comment: Please also see my updated follow-up question
Comment: changelog's answer contains what you need when styling. As of your JSP page, you have to search which file sets the header for the generated pages.
Answer: You always have iPad in the user-agent.
However, if you're targeting iPads so that you can show things differently, then CSS media queries are definitely the way to go forward.
See here how ZeptoJS detects iPad in JS.
To target iPad in both orientations, do this:
<code><link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css">
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css">
</code>
Comment: Heheh, I don't own one, so: no. You can't run other browsers on iPads? BTW, I've seen instances of older iPads with UA strings containing iPhone instead of iPad.
Comment: Browser sniffing is usually not a good idea. I know special iPad sites I can use by changing the UA string in Firefox and Chrome. ;)
Comment: That's right. iOS version 3.2 reports iPad as being an iPhone. Didn't know about that one! However, I've got a feeling that you don't have lots of users on 3.2 at this point.
Comment: From what I understand, detecting through UA would not be 100% correct..Also through CSS, what code should I use to detect both iPad as well as orientation in a single statement..like I want to use seperate ipad_portrait.css and ipad_landscape.css . Please suggest.
Comment: I've added an example on how to target iPad on each orientation.
Comment: @changelog - you miss the point. Browser UA strings can be configured to look like Mobile Safari on iPad when they aren't. Using the UA string to "detect" the browser or platform is a bad strategy.
Comment: I have a question on using the media thing to detect...I mean when we use device-width, how can we be 100% sure that it is an iPad..For example, another tablet say Xoom may also satsify the width criteria..So is the media thing 100% reliable to detect ipad?


Is every connected metric space with at least two points uncountable?

Question: As the topic, how to prove that every connected metric space with at least two points uncountable? Of course i know the definition that a countable set mean there is a bijection between the set and the positive integer. Connected is opposite of disconnected where the set can partition into two disjoint open sets.
Comment: For me, the main point is that a metric (or topological) space $X$ is connected if and only if the [intermediate value theorem](http://en.wikipedia.org/wiki/Intermediate_value_theorem) is valid on $X$; see user49521's answer.
Comment: So far I'm the only person who's up-voted this question.  That often gets neglected.
Comment: @HendrikVogt But if the set X contains exactly 2 points, is the intermediate value theorem still valid?
Comment: @Mathematics: No, at least not if $X$ is a metric (or more generally a Hausdorff) space. And that's the point! The intermediate value theorem is not valid, and $X$ is not connected. (Take $f(x_0)=0$ and $f(x_1)=1$; then $f$ is continuous(!) and doesn't take the intermediate values in the open interval $(0,1)$.)
Comment: @HendrikVogt o i see. So is it always true that a connect sets always consist either infinitely many points or just singleton?
Comment: @Mathematics: Yes, that true for any metric space.
Comment: @HendrikVogt O, thx! As when i am learning about connectness of metric space, the lecturer didn't mentioned about it and didn't notices that. BTW, why the condition requires "at least two points", is it to avoid the singleton?
Comment: @Mathematics: Yes, it avoids a singleton, and also the more pathological case of the empty space containing no points at all (which is connected by definition!).
Answer: Let us have another proof.
Since $X$ has at least two elements, let us choose $x_0,x_1\in X$, $x_0\neq x_1$. Define $f:X\rightarrow [0,1]$ by
$$
f(x):=\frac{d(x,x_0)}{d(x,x_0)+d(x,x_1)},\text{ for all }x\in X.
$$
Clearly, $f$ is continuous and
$$f(x_0)=0\text{ and }f(x_1)=1.$$
Since $X$ is connected and the continuous image of connected space is connected (so called intermediate value theorem), it follows that
$$
f(X)=[0,1],
$$
which shows that $X$ is uncountable because $[0,1]$ is uncountable. This proves the result.
Comment: @Saugata Honestly, defining the function $f$ as you did is unnecessarily obfuscating for the person just learning the subject. Taking $f(x)= d(x,x_0)$ and then showing $f(X)$ contains an closed interval of $\Bbb{R}$ suffices.
Comment: i have a question, how do we know that $f(x)$ is continuous
Comment: f is continuous because x-->d(x,x_0) and x-->d(x,x_1) are continuous with d(x,x_0)+d(x,x_1)>0. That these functions are continuous follows from the triangle inequality satisfied by the metric.
Comment: But if the set X only have 2 points, then is it still continuous? Also $f(X)$ seems $\ne[0,1 ]$ if $X$ has only 2 points
Comment: That $f(X)=[0,1]$ follows from the fact that X is connected.
Answer: Not only must $X$ be uncountable, its cardinality must be at least $2^\omega=\mathfrak c$.
Let $\langle X,d\rangle$ be a metric space, and suppose that $|X|<2^\omega$. Fix $x,y\in X$ with $x\ne y$, and let $r=d(x,y)>0$. Let $D=\big\{d(x,z):z\in X\big\}$; $|D|\le|X|<2^\omega=|(0,r)|$, so there is a real number $s\in(0,r)\setminus D$. Show that $B_d(x,s)$ is a non-empty clopen subset of $X$ whose complement is also non-empty, and conclude that $X$ is not connected.
Comment: @Ricky: In normal mathematical contexts (like this one) I follow normal mathematical practice and take AC for granted.
Comment: Shouldn't the correct symbol be $\aleph_0$? $\omega$ is an ordinal number.
Comment: This will prove that $\: |X| \not< \mathfrak{c} \:$. $\;\;$ It would take the Axiom of Choice to then conclude that $\: \mathfrak{c} \leq |X| \:$.
Comment: What is $2^{\omega}=c$? What do $\omega$ and $c$ mean?
Comment: @Mathematics: $\omega$ is the cardinality of $\Bbb N$ (or any other countably infinite set); $2^\omega=\mathfrak c$ is the cardinality of $\Bbb R$.
Comment: $\omega$ is the cardinality of the natural numbers. $\frak{c}$ is the cardinality of the real numbers. The statement $2^\omega = \frak{c}$ means that the power set of the natural numbers has the same cardinality as the real numbers. Whether or not there are infinities between the cardinality of the natural numbers and the cardinality of the real numbers depends on the axioms you choose, but Brian is saying that the size of $X$ is always at least $\frak{c}$, so even if there are smaller uncountable infinities, $X$ must in fact be at least the size of the real numbers.
Comment: @Mathematics If you're not familiar with $\omega$ and $c$, you can argue as follows instead. Observe that since $X$ is countable, so is $D$,but $(0,r)$ is not, so there is a real number $s \in (0,r) \backslash D$; proceed as above.
Comment: @Kenny: It's also the first infinite cardinal, just as $\omega_1$ is the second infinite cardinal. In general $\omega_\xi=\aleph_\xi$, and I prefer the omega notation, since $\omega_\xi$ is not only a cardinal, but a specific set of that cardinality.
Comment: @BrianM.Scott The problem Kenny was most likely trying to point out is that $2^\omega=\omega$ by the standard ordinal exponentiation. That's why you should use $2^{\aleph_0}$. I believe I've seen this mistake in other posts of yours.
Comment: @user2345215: It is not a mistake. The context makes it obvious that the arithmetic here is cardinal arithmetic. This is a standard notation, and I prefer it.
Answer: This is perhaps a generalisation of the method of user49521's answer above. Suppose now that $X$ is no longer a metric space but a normal space with at least two points that is connected. Call those two points $x_0$ and $x_1$. Then the Urysohn Lemma gives the existence of a continuous function $f : X \to [0,1]$ such that $f(x_0) = 0$, $f(x_1) = 1$. Now because $X$ is connected its image is also connected. Connected subsets of the reals are intervals and so we conclude that $X$ surjects via $f$ onto some interval that has cardinality $\mathfrak{c}$, so that $|X| \geq \mathfrak{c}$.
Comment: Yes, you are right. Since the problem was posed for a metric space, instead of invoking the Urysohn Lemma, I constructed a Urysohn function explicitly.


Compact and open sets

Question: How to solve this question?
Let $X$ be a Hausdorff space and $\{K_n\}$ a familly of decreasing compact non empty compact sets, Let $K=\bigcap_{n\in\mathbb{N}} K_n$ and let $\Omega$ be an open set $$K\subset \Omega\Rightarrow \exists n_0\in\mathbb{N},\forall n\in \mathbb{N}, K_n\subset \Omega$$.
If I suppose by contradiction that $K\subset \Omega$ and $$\forall n_0\in\mathbb{N},\exists n\in\mathbb{N}, n\geq n_0 ~\text{and}~ K_n\not\subset \Omega$$.
That is
$$\forall n_0\in\mathbb{N},\exists n\in\mathbb{N}, n\geq n_0, \exists x\in K_n ~\text{and}~ x\in E\setminus \Omega$$
How to continue? Is there any other method?
Comment: It suffices to find *one* $n_0$ with $K_{n_0} \subseteq \Omega$, then the same will hold for all $K_n$ with $n \ge n_0$ by decreasingness.
Answer: If not, then we have an open set $\Omega$ containing $K$ such that $$\forall n \in \mathbb{N}: K_n \nsubseteq \Omega$$
and then we can thus define $C_n = K_n\setminus \Omega = K_n \cap( X\setminus \Omega)$ and all $C_n$ are non-empty (by the non-inclusion) and decreasing (as the $K_n$ are) and compact, $C_n$ being closed in $K_n$.
But then $\cap_n C_n \neq \emptyset$ by a standard fact on families of closed sets (by Hausdorffness of $X$) with the f.i.p. in a compact space ($C_0$).
But any $p \in \cap_n C_n$ is in all $K_n$, hence in $K$, but not in $\Omega$ contradiction.
Comment: where is $n_0$ ? whay you have $\forall n$??
Comment: see my edit @Henno Brandsma
Comment: @PolineSandra Because if the $K_n$ are decreasing, if you have an $n_0$ with $K_{n_0} \subseteq \Omega$ we automatically have that all $K_n$ with larger index are a subset too: $K_n \subseteq K_{n_0}$. So **one** $K_n$ inside $\Omega$ suffices, and my proof starts from the contrary assumption (**no** $K_n$ is) etc.
Comment: my problem is why you write $$\forall n\in\mathbb{N}, K_n\not\subset \Omega$$ by contradiction we have $\forall n_0\in\mathbb{N}, \exists n\in\mathbb{N}$
Comment: we have $\exists n_0 , \forall n$ so the negation is $\forall n_0,\exists n$
Comment: @PolineSandra $\exists n_0 \forall n \ge n_0$ is the same as $\exists n_0$ here. So only one quantifier needed.
Comment: i don't understand you start by $\forall n\in \mathbb{N}, K_n\not\subset\Omega$ after that you say $\exists n_0 \forall n\geq n_0$ is the same $\exists n_0$ ?????
Comment: @PolineSandra Do you understand the comment on your question? You have to use the $K_n$ are decreasing!
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/78659/discussion-between-poline-sandra-and-henno-brandsma).
Comment: Can we prove it using sequences ?
Comment: @PolineSandra not really. And sequences are not sufficient in general spaces anyway.
Comment: I found a proof on a book by sequences , $(x_n)\subset K_n$ then it has a convergent subsequence and it limits $x\in K$ then $x\in \Omega$ but $x\in X\setminus \Omega$ because $X\setminus\Omega$ is closed contradiction
Comment: @PolineSandra a compact space need not be sequentially compact. So that step already fails.
Comment: ??????????????????????????
Comment: @PolineSandra you're not making sense. Study my proof and see that it works.
Comment: each sequence in a compact set has a convergent subsequence
Comment: @PolineSandra that is only true in some spaces, like sequential ones, not in all compact spaces!

Compact and open sets


Test java code with JMeter

Question: I have the server functionality of a product packed in jar file, and i have to measure the time of execution of a static method of a class packed in this jar file. Is it possible and if yes, how to do this with JMeter? The only tutorial that i found and that is concerning something similar, is about making junit test and packing it in jar file and putting it in the classpath of jmeter?
Comment: @tak3shi he could call his method with a jsr223 sampler, no?
Answer:
Put your jar (with any dependencies if needed) somewhere to JMeter Classpath
Restart JMeter to pick the .jar(s) up
Add JSR223 Sampler and invoke your method using Groovy language

That's it, JSR223 Sampler response time will be the value you're looking for. See Apache Groovy - Why and How You Should Use It article for more information on using Groovy scripting in JMeter tests.
Comment: And don't forget to tick "Cache compiled script if available" it'll reduce overhead significantly

Test java code with JMeter


Excel VBA how to clear items of a combo box

Question: I want to show the value of a combo box in a cell. But before it, I want to clear the items of the combo box and then fill it by items. The below code works but when I add .clear to the code, It doesn't show the selected value of combo box in cell 1,4. I don't know why.
If I don't add clear to the code, the items of the combo box will be increased every time I run the program.
Private Sub ComboBox1_change()

      With Sheet3.ComboBox1

            For Each Cell In Range("A1:A15")
           .AddItem  Cell.Value
            Next
         xx = ComboBox1.Value
         Set car = Cells(1, 4)
         Cells(1, 4).Value = xx

     End With

End Sub

Answer: Don't use .AddItem to poulate Combo/Listboxes it is very slow for > 5 items, you can use the .List property directly. This will both be more efficient and solve your issue:
Private Sub ComboBox1_change()

      Sheet3.ComboBox1.List = Range("A1:A15").Value
      Set car = Cells(1, 4)
      Cells(1, 4).Value = xx

End Sub

Comment: I have tried this, you're right but my question is about clearing the items, please see the question again.


A question on infinitesimal generator

Question: Pages 120, 121 of W. Boothby's An Introduction to Differentiable Manifolds contain an explanation of infinitesimal generator, with the quotient:
$$\frac{1}{\Delta{t}}[f(\theta_{\Delta{t}}(p)) - {f}(p)]$$
Then the author assumes that $\hat{f} (x^{1}, \ldots, x^{n})$ is the local expression for $f \in C^{\infty}(p)$, and then he equals to the above quotient with
$$\frac{1}{\Delta{t}}[\hat{f}(h(\Delta{t}, x)) - \hat{f}(x)].$$
I am confused as to how these quotients may be equal.
I'd appreciate any useful explanation to help me out.
(I argue that $\theta : \mathbb{R} \times M \to M$ and $f : M \to \mathbb{R}$, so that $f \circ \theta : \mathbb{R} \times M \to \mathbb{R}$. On the other hand, $h : \mathbb{R} \times \mathbb{R}^{n} \to \mathbb{R}^{n}$ and $\hat{f} : \mathbb{R}^{n} \to \mathbb{R}$, which gives $ \hat{f} \circ h : \mathbb{R} \times \mathbb{R}^{n} \to \mathbb{R}$.)
Answer: You put a chart $\phi:M\to\Bbb R^n$ in between, $$f∘θ=f∘\phi^{-1}∘\phi∘θ$$ and split in the middle, to get $$\hat f=f∘\phi^{-1},\\ h=\phi∘θ∘(id_{\Bbb R}, \phi^{-1})$$ with the described properties.

A question on infinitesimal generator


Edit JIRA Issues Java Rest

Question: I have tried to google this, but can't seem to get a good clear answer on this.
I'm trying to edit JIRA issues using Java via the JIRA REST API.
Can anyone provide a full example of editing a custom or standard field including library declarations? Completely new to REST and JIRA.
I can't use plugins as I'll be working with multiple JIRA instances and I don't control the JIRA server I'm connecting to.
I found this:
https://answers.atlassian.com/questions/127302/update-issue-with-jira-rest-java-client-2-0-0-m5
But I don't understand it.
Thanks for your help :)
Comment: Please see [this answer](http://stackoverflow.com/a/28676736/357403) in a very similar question.
Answer: Updating labels and summary with JJRC 4.0.0:
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_URL);
client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
Map<String, FieldInput> map = new HashMap<>();
String[] labels = {"label1", "label2"};
map.put("labels", new FieldInput("labels", Arrays.asList(labels)));
map.put("summary", new FieldInput("summary", "issue summary"));
IssueInput newValues = new IssueInput(map);
client.getIssueClient().updateIssue("XX-1000", newValues).claim();

Comment: Hi @ynka, to do the same for dates ? I tried Joda Datetime and doesn't work... Any idea ? The API is not really useful, we have to guess some object types todo the updates...
Answer: Manged to find a way using the Jira REST and the Jersey Library. Currently, Jira's Java API supports reading and creating tickets but not editing.
package jiraAlerting;

import javax.net.ssl.TrustManager;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

public class restLab {

    WebResource webResource;
    static {
        //for localhost testing only
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
        new javax.net.ssl.HostnameVerifier(){

            public boolean verify(String hostname,
                    javax.net.ssl.SSLSession sslSession) {
                if (hostname.equals("your host here")) {
                    return true;
                }
                return false;
            }
        });
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        restLab rl = new restLab();

        //rl.connectToJiraViaRest();

        rl.editJiraTicket();
    }

    public void connectToJiraViaRest(){
        //System.setProperty("javax.net.ssl.trustStore", "C:/SSL/clientkeystore.jks");

        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("username","password"));

        webResource = client.resource("https://host/jira/rest/api/2/issue/issueID");

    }

    public void editJiraTicket(){
        connectToJiraViaRest();

        ClientResponse response = webResource.type("application/json").put(ClientResponse.class,"{\"fields\":{\"customfield_11420\":{\"value\" :\"No\"}}}");
        //"{\"fields\":{\"customfield_11420\":\"Yes\"}}"
        response.close();
    }
}

Answer: You can Edit Jira issue by writing your Json to OutputStream and check for the response code. If it is 401 then your jira issue will be successfully edited.
public String getAuthantication(String username, String password) {
    String auth = new String(Base64.encode(username + ":" + password));
    return auth;
}

public static HttpURLConnection urlConnection(URL url, String encoding) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization", "Basic " + encoding);
    connection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
    connection.setRequestProperty("Content-Type", "application/json");
    return connection;
}

public void updateJiraIssue(JiraCQCredential jiraCq) throws IOException {

    String summary = "Edit Jira Issue";
    String description = "Testing of Jira Edit";
    String assigne = "Any name who has jira account";
    String issueType = "Bug";

    String encodedAuthorizedUser = getAuthantication("pass your username", "pass your password");
    URL url = new URL("http://bmh1060149:8181/rest/api/2/issue/WFM-90");
    HttpURLConnection httpConnection = urlConnection(url, encodedAuthorizedUser);
    httpConnection.setRequestMethod("PUT");

    String jsonData = "{\"fields\" : {\"summary\":" + "\"" + summary + "\"" + ",\"description\": " + "\""
            + description + "\"" + " ," + "\"issuetype\": {\"name\": " + "\"" + issueType + "\""
            + " },\"assignee\": {\"name\":" + "\"" + assigne + "\"" + ",\"emailAddress\": \"email@example.com\"}}}";

    byte[] outputBytes = jsonData.getBytes("UTF-8");

    httpConnection.setDoOutput(true);
    OutputStream out = httpConnection.getOutputStream();
    out.write(outputBytes);
    int responseCode = httpConnection.getResponseCode();
    if(responseCode == 401){
        System.out.println("Issue updated successfully with the mentioned fields");
    }
}

you can't pass your Json directly to httpConnection. So convert it to byte array and then write to OutputStream.

Edit JIRA Issues Java Rest


Connecting to Superclass Properties with Storyboards

Question: I am converitng a project to Swift with Storyboards.  The old version was Objective-C and did not use Storyboards.  The original version has a number of ViewControllers that are subclasses of a CoreDataFetchedResultsViewController.  In the CoreFetchedResultsViewController class, I have a property for a UITableView that is used in a number of methods.  The declaration of the UITableView in the CoreFetchedResultsController superclass is below.
<code>@interface CoreDataFetchedResultsViewController : UIViewController <NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *storyTableView;
</code>
In the ViewControllers that subclassed the CoreFetchedResultsViewController, I created a tableView and set it to the storyTableView property of the CoreFetchedResultsViewController in the viewDidLoadMethod.
<code>@interface FLOViewController : CoreDataFetchedResultsViewController <FLODataHandlerDelegate, UIActionSheetDelegate>
</code>
viewDidLoad() from the FLOViewController class
<code>- (void)viewDidLoad
{
    [super viewDidLoad];

        self.storyTableView = [[UITableView alloc] initWithFrame: CGRectMake(0, 44, 320.0f, 436.0f) style: UITableViewStylePlain];
        self.storyTableView.backgroundColor = [UIColor clearColor];
        self.storyTableView.rowHeight = 81;
        self.storyTableView.separatorColor = [UIColor blackColor];
        [self.view addSubview: self.storyTableView];
        self.storyTableView.delegate = self;
        self.storyTableView.dataSource = self;
}
</code>
With the tableView connected to the CoreDataFetchedResultsViewController property the tableView did not crash the app.
My trouble occurs when I am using Storyboards.  Since I place the tableView on my FLOViewController in the Storyboard, I am not able to connect it to the storyTableView property in the superclass CoreDataFetchedResultsViewController.
What's the best way to connect a Storyboard element to a superclass property?  Do you create an outlet in the subclass and then set that property to the superclass property?
<code>class FLOViewController
{
@IBOutlet var floViewControllerTableView: UITableView!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.storyTableView = self.floViewControllerTableView
     }
}
</code>
This appears to work but is seems wrong to me.  It seems as if copying the object is not the best idea.  Any help would be appreciated.
Take care,
Jon
Answer: Creating an IBOutlet in the superclass is what works best.  This way you can connect the tableView directly to this property.
Take care,
Jon


Approving Pending Userpoints

Question: I'm developing a site that allows users to earn points based on site actions.  I have the site working for users and their points earned are going into a "pending" category.  The next step is that the points need to be administratively approved.
I was trying to find a way to have this action work through a page content or onclick button without having to go through config -> points -> moderation.
If anyone has any ideas or thoughts that have worked for them I'd love the help, I've been stuck on this for a few days now.
Thank you!
Comment: Hey nit3ch, thanks for your answer, I couldn't get that to work but I got some rigged sql calls to work.  Thanks for your help though!
Answer: you can try rules module to achieve this.
Create a event like "when a node is saved" and provide some condition if required and then action like grant/deduct user points. User points is integrated with rule.

Approving Pending Userpoints


problemas na hora de mandar os dados para o banco de dados

Question: Estou entrando agora na parte de programaçao com mysql e php, e estou com dúvida, na parte de chamar o banco de dados.vcs pode me ajudar?
Os códigos que escrevi:

<title> sistema de cadastro</title>

<form method="get="action="cadastrando.php">
nome: <input type="text" name="name"/>
sobre nome: <input type="text" name="sobrenome"/>
pais: <input type="text" name="pais"/>
estado:<input type="text" name="estado"/>
idade: <input type="text" name="cidade"/>
e-mail: <input type="text" name="email"/>
senha: <input type="password" name="senha"/>
<input type="submit" value=""/>
</form>

///////////////////////////////////////////////////////////////////////////

<title> cadastramento

<?php
$host ="localhost";
$user = "root";
$pass = "";
$banco= "cadastramento";
$conexao = mysql_connect($host,$user, $pass) or die(mysql_error());
mysql_select_db($banco) or die(mysql_error());
?>

<?php
$nome=$_post['NOME'];
$sobrenome=$_post['SOBRENOME'];
$pais=$_post['PAIS'];
$estado=$_post['ESTADO'];
$cidade=$_post['CIDADE'];
$email=$_post['EMAIL'];
$senha=$_post['SENHA'];

$sql = mysql_query("INSERT INTO usaname(NOME,SOBRENOME,PAIS,ESTADO,CIDADE,EMAIL,SENHA) values('$NOME','$SOBRENOME','$PAIS','$ESTADO','$CIDADE','$EMAIL','$SENHA')");
?>

Comment: Recomendaria separar a camada de visão com a camada que faz a conexão com o banco de dados para uma melhor organização.
Comment: Amigo, sua pergunta está muito vaga e meio sem sentido. Poste os códigos que já tem e tente explicar melhor o que precisa.
Comment: A melhor dica para um iniciante me php, NÃO use as funções mysql_*, prefira o mysqli ou o pdo.
Answer: O problema é que as variáveis definidas estão em minusculas e as passdas no insert em maiusculas, o php é case sensitive para variaveis, logo $nome é diferente de $NOME.
O nome da super global é $_POST em maiusculas mesmo.
O método de envio é definido no form
<form method="get="action="cadastrando.php">

Use $_GET para get e $_POST para post, sugiro que altera o method para post.
<?php
$nome = $_POST['nome'];
$sobrenome = $_POST['sobrenome'];
$pais = $_POST['pais'];
$estado = $_POST['estado'];
$cidade = $_POST['cidade'];
$email = $_POST['email'];
$senha = $_POST['senha'];

$sql = mysql_query("INSERT INTO usaname(NOME,SOBRENOME,PAIS,ESTADO,CIDADE,EMAIL,SENHA) values('$nome','$sobrenome','$pais','$estado','$cidade','$email','$senha')") or die(mysql_error());

Leitura recomendada:
Por que não devemos usar funções do tipo mysql_*?
MySQLi vs PDO - qual o mais recomendado para usar?


Does a Dirty Piano on the Inside Affect Action and Sound?

Question: I have researched this question with no results. All I find are tutorials on cleaning pianos, but nothing about the effect dirt and dust have on a piano.
I have a Symphonic baby grand piano made in 1912, and the insides look a little dirty. Could dust or dirt affect the sound of the piano, or even the action of the keys? I notice the bass keys are much harder to press than the treble keys (I know this is normal for grands, but the difference on this piano seems abnormal), and I'm not sure if dirt can cause that. Could it also affect the dampers, making them take longer to mute the strings?
Basically, what effect does dirt and dust on the insides have on the piano sound, action, and functionality, if any at all? Any answers to this question are greatly appreciated!
Comment: If it has been out of use for quite a while then it probably needs tuning.  The tuner could probably assess its condition better than we can.
Answer: It's going to affect just about everything. But to what extent, is another question. String windings that are full of dirt and dust will not sound as bright as clean ones. Rusty single strand strings (the higher part) won't vibrate as well as un-rusty ones.
The felt on hammers will be affected by ingrained dirt. The moving parts (hundreds of them) won't respond and recover as efficiently as they would when clean. Flexible parts will be stiffer when dirt is covering them.
After more than 100 years of dirt accumulation, just about anything would need a good clean, wouldn't it?
Comment: The guy who had the piano before me had it for I think 10 years. He had all the keys, hammer and damper felts replaced. The strings don't look like they're in bad situation. The only thing is the inside is dirty, and the action is really heavy at the bass. It's not unbearable, but a little abnormal. Maybe that's how the piano was built? I'm not sure. All I know is it's dirty inside, and I wasn't sure if that would wreck the sound or explain the tough action.
Comment: What make is it? If it's a Yamaha I'm not surprised by the hard action, and others seem to be similar. If it's general dirt, then a vacuum will clear that. A good piano tuner will provide guidance, so it shouldn't be too long till that opportunity comes along, should it?
Comment: Mine is by Symphonic. I haven't heard of them before, only this piano.
Comment: No, nor me.....
Answer: Not much, unless it's so extreme that it's actually impeding mechanical action.   I certainly don't think you can blame dirt for a heavy bass-end action.   Perhaps for ONE sticking note.
Comment: Part of me thought that, but I wasn't entirely sure. Thank you!


Insert a vector (array 1D) into array two-dimensional?

Question: how can I insert a vector (array 1D)  into an array two-dimensional python?
I have a code generate array one dimension each time length =11, and i want to save this vector in array two dimensions (i,11)
i represent the number of rows, and 11 represent the column
please any suggestion
Comment: Can you share a reproducible example of your code, thanks!
Comment: You're probably looking for np.vstack.
Comment: What module are you using to create these vectors and arrays?
Answer: I solve this problem and the solution bellow.
<code>from array import *
import numpy as np
col_num=4
row_num=4
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]
b=np.array([1,2,3,4])

a=np.array([0,0,0,0])

for row in range(row_num):
    for col in range(col_num):
        multi_list[row][col]= b[col]

for col in range(col_num):
    for row in range(row_num):
        a[col]= a[col]+multi_list[row][col]
</code>


OneDrive on RDS Windows stuck listing folders and files

Question: This is a bit awkward because I've already wasted tons of hours with no result, this is my last chance.
Problem
OneDrive sometimes (90%) is stuck on loading folders and files, but just listing them. Sometimes crashes "explorer.exe" when it's stuck.
You can see the "Cloud" icon appear very slowly.

Hardware (Dedicated VPS Hetzner)

CPU: AMD Ryzen 9 5950X 16-Core
RAM: 60 GB DDR4
SSD: 500GB NVME

Virtualized with Hyper-V, but it's the only Virtual Machine on the host.
Internet Speed
1000Mbps download
1000Mbps upload
Hetzner Datacenter Speed
OS
Windows 10 Pro x64
Version 22H2 (19045.2546)
OneDrive configuration
Installed with "OneDriveSetup.exe /allusers".
All users has "Files on demand activate" because in share point size is big.
Every user has his own OneDrive (with no use)
Every user has a Share point Sync (all files are there)
Number of concurrent users
18 approx, with RDP.
Daily Usage
Users connect with RDP to the server, uses Word, Excel and Outlook. No more.
Edit1
We tried to change Windows File Explorer > Settings > View > Launch folder windows in a separate process. Seems to be more "agile" but still super slow.

Edit2
We forced Windows Indexing to be faster. Still no luck, all seems to work at the same speed and the problem still persist.

Edit3
On OneDrive, we checked "Install Insider Version", and it restarts with the new version. Seems to work a bit better, but still having moments of "eternal waiting" listing files and folders
OneDrive Version: Compilation 23.045.0228.0001 (64 bits)
Comment: Please don't add "solved" to your question. Instead, post the solution as an answer and accept it, otherwise the question will stay as unsolved in the system forever. It is perfectly fine to answer your own question if you find the answer.
Comment: Hi, what a/v you use ? I ask as it can hijack the explorer process to scan change. (I would remove it to test, if it make a change then maybe change the scanning method (on create/on change to on modify)
Comment: That's good information and not unexpected. A remote desktop host can have hundreds of sessions. There's no way an application like OneDrive would scale up to that. I believe it used to be not supported at all. This effectively means it isn't a good option at all, unless that is a hard limit per RDSH.
Comment: Hi @yagmoth555, thanks for your reply! We use "Crowdstrike Falcon", console is Cloud. Version of endpoint 6.51.16510.0.

I'll try to ignore users Sharepoint folders.
Answer: After long checking my server with a Microsoft Engineer, the only way to solve this problem is reading the official documentation about OneDrive.
This LINK and the next image shows that we can only configure nine (9) OneDrive for Work or School accounts in one host.
That makes me get crazy, because Microsoft allow us to use RDS for large amount of users with the same server, but that users can't configure all at the same time OneDrive...

Max OneDrive Accounts per host (EN-US)
So, there are thre possible implementations for that solution:

Implement FSLogix
Separate users in multiple RDS Servers
Use Third Party applications that allows you to map SharePoint as Windows Network Drive
Mount "OneDrive as a Service", with Third Party applications, so one account is syncing with SharePoint and all users consumes files over shared Windows Folder (native)


Reasons to run Drupal on PostgreSQL

Question: What would be the strongest reasons for running Drupal on PostgreSQL, in terms of available features and performance? I.e. what postgres features of that are supported by Drupal are not available on mysql? For example, postgres is known for ACID conformance and transactions; does Drupal core take advantage of these or other features in any way?
This question is not about which is a better DB in general, rather whether there are any specific reasons why one might choose postgres over mysql. One obvious trade-off is that many contrib modules will be buggy running on postgres.
I am working with D6, but feel free to direct answers to any major version.
Comment: Given that we have a DB-abstraction layer that attempts to even this out, and any contrib modules should be taking advantage of that, I expect the differences to be somewhere between small to none.
Comment: Keep in mind that Postgres became a first class citizen in Drupal 7.
Using Postgres with Drupal 6 has always been unwise at best, since the DB abstraction layer was thin, and contrib didn't care much.
Comment: I'm afraid this question might encourage fight between Postgresql users and MySQL users. Drupal 7 abstraction layer pretty much remove features not existing in other rdbms, so feature-wise it's levelled on the bottom side. And performance was always a matter of who tested it and what he wanted to prove ;)
Comment: The question was asked almost a year ago. How much fighting are your concerned about? Regardless of abstraction layer, the 2 DBs do have some different features that a module could incorporate, e.g. http://bugs.mysql.com/bug.php?id=18003, and that was the point of the question.
Answer: Personally, I think the only reason for choosing PostgreSQL over MySQL is if you (or your client) is already a PostgreSQL shop and have DBAs that know PostgreSQL well and know the ins-and-outs of babysitting it.  I would also say the same also applies for choosing MySQL over PostgreSQL, assuming you aren't using any contrib modules with MySQL-only functions in them.
Comment: Now - that's ridiculous. There's only one reason to run MySQL: that's when you want a very fast system, and don't give a damn about sacrificing referential integrity and data quality, and SQLite doesn't cut it. Also, possibly when you don't want to see error messages when you do something wrong - but that's not a good thing either.  For all other usage cases => PostgreSQL - because that's actually a working acid-compliant RDBMS.
Answer: Some of our clients insist on using PostgreSQL because that's the only database they can support in house.
After implementing a couple of complex Drupal projects using Postgres I would say Postgres is generally faster and I would consider it if the site needs lots of rather complex views. MySQL has only one join algorithm (nested loop) whereas Postgres provides a few so when Views have lots JOINs Postgres may be more advantageous. This is more true if those views also have lots of exposed filters. However Views (both 2.x and 3.x) may experience issues with Postgres that some views with DISTINCT may not work very well if at all.
At the end of the day, if your client insists on using Postgres, and/or performance is a priority, give it a shot but be very cautious that some popular modules or some features may not function well. Or stick with MySQL if you don't have an appetite for risk.
Answer: Personally, I am using Drupal on Postgres because I need the PostGIS extension, but I reckon this is not a need many applications have.

Reasons to run Drupal on PostgreSQL


Residue Theorem Integral of $\frac{1}{\sinh(x)-1}$

Question: I need help with the integral: $$\int_{-\infty}^\infty\frac{x}{\sinh(x)-1}dx,$$ and I (unfortunately) have to use contour integration techniques. I know how to do the integral $$\int_{-\infty}^\infty\frac{1}{\sinh(x)}dx,$$ so using a similar strategy, I tried integrating $$f(z):=\frac{z}{\sinh(z)-1}$$ around a box of width $2R$ and height $\pi $ centered at the origin. However, $\frac{1}{\sinh(x)-1}$ has poles at $z_n=\ln(2\pm\sqrt{2})+2\pi i n,$ for $n\in\mathbb{N}$, and so we must make $\epsilon$ bumps around $\log(2\pm\sqrt{2})$. However, around these bumps,
$$\int_{C_\epsilon}f(z)dz=\int_0^\pi\frac{2\log(1\pm\sqrt{2})+2\epsilon e^{-i\theta}}{\log(1\pm \sqrt{2})[e^{\epsilon e^{i\theta}}-e^{-\epsilon e^{-\theta}}]-1}\cdot -i\epsilon e^{-i\theta}d\theta$$
Does this simplify? I'm not sure how to tackle this. I also thought about making a substitution $x\mapsto \ln(x)$ at the very beginning, but the integration bounds that I get confuse me (I get from $-\infty +i\pi$ to $\infty$).
Comment: While the integral of interest diverges, its Cauchy Principal Value does exist.  I've posted a solution accordingly.  If you have a moment, then please let me know your thoughts.
Answer: DETERMINING CONVERGENCE
We are asked to evaluate the integral $I$ given by
$$I=\int_{-\infty}^\infty \frac{x}{\sinh(x)-1}\,dx\tag1$$
We denote the denominator of the integrand in $(1)$ by $g(x)=\sinh(x)-1$.  For $x\in \mathbb{R}$, it is easy to show that $g(x)$ has a single root $x_0-=\log(1+\sqrt 2)$.
Then, from the prosthaphaeresis identity
$$\begin{align}
g(x)&=\sinh(x)-1\\\\
&=\sinh(x)-\sinh(x_0)\\\\
&=2\cosh\left(\frac{x+x_0}{2}\right)\sinh\left(\frac{x-x_0}{2}\right)
\end{align}$$
we find that $g(x)=O\left(x-x_0\right)$ as $x\to x_0$.

Hence, we conclude that the integral in $(1)$ fails to exist.

CAUCHY-PRINCIPAL VALUE
However, the Cauchy Principal Value of $(1)$ does exist and is expressed as
$$\begin{align}\text{PV}\left(\int_{-\infty}^\infty \frac{x}{\sinh(x)-1}\,dx\right)&=\lim_{\varepsilon\to 0^+}\left(\int_{-\infty}^{x_0-\varepsilon} \frac{x}{\sinh(x)-1}\,dx\\+\int_{x_0+\varepsilon}^\infty \frac{x}{\sinh(x)-1}\,dx\right)\tag2
\end{align}$$
In the next section, we use contour integration to evaluate $(2)$.

EVALUATION OF THE CAUCHY PRINCIPAL VALUE
Let $f(z)=\frac{z^2}{\sinh(z)-1}$, $z\in \mathbb{C}$.  The poles of $f(z)$ are simple and located at $z_n=x_0+i2n\pi$ and $z'_n=-x_0+i(2n+1)\pi$.
Let $J$ be the integral
$$J=\oint_C f(z)\,dz$$
where $C$ is the contour comprised of the six line segments $(i)$ from $-R$ to $z_0-\varepsilon$, $(ii)$ from $z_0+\varepsilon$ to $R$, $(iii)$ from $R$ to $R+i2\pi$, $(iv)$ from $R+in\pi$ to $z_1+\varepsilon$, $(v)$ from $z_1-\varepsilon$ to $-R+i2\pi$, and $(vi)$ from $-R+i2\pi$ to $-R$ and the two semicircular arcs $(i)$ $z_0+\varepsilon e^{i\phi}$, from $\phi=\pi$ to $\phi=0$ and (ii) $z_1+\varepsilon e^{i\phi}$, from $\phi=2\pi$ to $\phi=\pi$.

APPLYING THE RESIDUE THEOREM
The contour $C$ encloses only the simple pole at $z'_0=-x_0+i\pi$.  Therefore, the reside theorem guarantees that for $R>|z_0'|$
$$\begin{align}
\oint_C f(z)\,dz&=2\pi i \text{Res}\left(f(z), z=z'_0\right)\\\\
&=2\pi i \lim_{z\to z'_0}\left(\frac{z^2(z-z'_0)}{\sinh(z)-1}\right)\\\\
&=2\pi i \lim_{z\to z'_0}\frac{z^2}{\cosh(z)}\\\\
&=2\pi i \frac{(z'_0)^2}{\cosh(z'_0)}\\\\
&=2\pi i \frac{(x_0+i\pi)^2}{-\sqrt 2}\\\\
&=-\frac{i\pi}{\sqrt 2}(2(x_0+i\pi)^2)\tag3
\end{align}$$

EXPRESSING THE INTEGRAL OVER $C$
We also have as $R\to \infty$ and $\varepsilon \to 0^+$
$$\begin{align}
\lim_{R\to\infty\\\varepsilon\to 0^+}\oint_C f(z)\,dz&= \text{PV}\left(\int_{-\infty}^{\infty}\frac{x^2}{\sinh(x)-1}\,dx\right)-\text{PV}\left(\int_{-\infty}^{\infty}\frac{(x+i2\pi)^2}{\sinh(x)-1}\,dx\right)\\\\
&-i\pi \frac{z_0^2}{\cosh(z_0)}-i\pi\frac{z_1^2}{\cosh(z_1)}\\\\
&=-i4\pi \text{PV}\left(\int_{-\infty}^{\infty}\frac{x}{\sinh(x)-1}\,dx\right)\\\\
&+4\pi^2\text{PV}\left(\int_{-\infty}^{\infty}\frac{1}{\sinh(x)-1}\,dx\right)\\\\
&-\frac{i\pi }{\sqrt 2}(z_0^2+(z_0+i2\pi)^2)\tag4
\end{align}$$

CONCLUSION
Equating $(3)$ and $(4)$ we find that
$$\bbox[5px,border:2px solid #C0A000]{\text{PV}\left(\int_{-\infty}^\infty \frac{x}{\sinh(x)-1}\,dx\right)=\frac{\pi^2}{2\sqrt 2}}$$
Comment: Thank you so much for such a clear solution, Mark. This was really illuminating. I hadn't heard of the concept of principal values until now.
Comment: You're welcome!  My pleasure.
Answer: I think rewriting the problem with an appropriate substitution will turn it into a much more standard application of the residue theorem. Rewriting the integral using the definition of $\sinh(x)$, we have that
$$\int_{-\infty}^{\infty} \frac{x}{\sinh(x) - 1}dx = \int_{-\infty}^{\infty} \frac{x}{\frac{1}{2}(e^x - e^{-x}) - 1}dx.$$
Making the substitution $u = e^x$, we then have the relationships $\ln(u) = x$ and $du = e^xdx = u dx$. Our domain's bounds also change under this substitution, so our integral becomes
$$\int_{-\infty}^{\infty} \frac{x}{\frac{1}{2}(e^x - e^{-x}) - 1}dx = \int_0^{\infty} \frac{\ln(u)}{\frac{1}{2}(u-u^{-1})-1}\frac{du}{u} = \int_0^{\infty} \frac{\ln(u)}{\frac{1}{2}(u^2-1)-u}du.$$
From here, you can extend to $\mathbb{C}$ and pick the appropriate branch of the logarithm  to proceed. EDIT: I actually tried to write the integral out but all my attempts and online integral calculators couldn't solve it. Looking at its graph, I'm now mildly convinced it might actually diverges, but I'd love to see if anyone can take this further or prove that rigorously.
Comment: While the integral of interest diverges, its Cauchy Principal Value does exist.  I've posted a solution accordingly.  If you have a moment, then please let me know your thoughts.


Deleting a string from a dynamic array and making that array one smaller

Question: My class assignment is to create a program using OOP that creates a dynamic array that can act like a vector. My remove entry function is crashing when I run it. After messing around with it for a while I can't seem to make it stop crashing no matter what I do. Here are the instructions for this function in particular.
The function should search dynamicArray for the string.If not found, it returns false. If found, it creates a new dynamic array one element smaller than dynamicArray. It should copy all elements except the input string into the new array, delete dynamicArray, decrement size, and return true.
bool dynamicStringArray::deleteEntry(std::string oldString)
{
    for (int i = 0; i < size; i++){
        if (dynamicArray[i].compare(oldString) == 0){
            std::string* shortArray = new std::string[size - 1];

            delete &dynamicArray[i];
            for (int j = 0; j < size - 1; j++)
                shortArray[j] = dynamicArray[j];

            size--;
            for (int j = 0; j < size; j++)
                dynamicArray[j] = shortArray[j];

            return 1;
        }
    }

    return 0;
}

Comment: You should be able to stop it from crashing by commenting out everything in the method body except the return, if this is where the problem is.
Comment: Yes I have done that and the error is in fact in the if statement body
Comment: Are you sure you need to copy the elements from `0` to `size -1`? You just deleted the one at index `i`, and `i < size`, not necessarily `i == size -1`.
Answer: You have a bit of misunderstanding about what
delete &dynamicArray[i];

does.
It does not remove the i-th entry from dynamicArray. It tries to deallocate memory of one objet -- the i-th object. That in itself is cause for undefined behavior.
You may not call delete on a pointer unless it was returned by a call to new.
The second problems is that dynamicArray continues to have that pointer as the i-th element.
Here's an updated if statement that should work.
if (dynamicArray[i].compare(oldString) == 0) {
   std::string* shortArray = new std::string[size - 1];

   // Copy everything form dynamicArray to shortArray except
   // the i-th element.
   for (int j = 0; j < i; j++)
   {
      shortArray[j] = dynamicArray[j];
   }

   for (int j = i+1; j < size; j++)
   {
      shortArray[j-1] = dynamicArray[j];
   }

   // Delete old array
   delete dynamicArray;

   // Make the newly allocated array the array of
   // the object.
   dynamicArray = shortArray;

   // Decrement the size
   --size;

   return 1;
}


Newline in constant and ; Expected

Question: I'm currently working on school assignment which is to create a simple e-commerce website.
Having Problems with the codes for Updating Customer Details:
 public partial class UpdateCust : System.Web.UI.Page
{
public string UFlag = "F"; public string strUserId;
static readonly string scriptSuccessUpdate = "";

Getting 2 Errors on
"alert(\"Update Successful - Please surf to other pages to shop\");\n ";

Newline in constant
; expected

The codes were provided by the tutor to be used in the update button, but I'm not familiar with them. Any help would be appreciated :)
Comment: Look at your closing quote after ``. It's not an ASCII double-quote...
Comment: You using bad quote at the end of last line ... you using `"` instead of `"`
Comment: Common copy past issue, remove/retype your last double quote.
Answer: static readonly string scriptSuccessUpdate = "";

the last quote is diff please correct it
Comment: The last quote is just a different character than `"`.
Comment: I think, that he not missed anything ... he used bad quote only `"` instead of `"`
Answer: This is because use of wrong quotes symbol:
static readonly string scriptSuccessUpdate = "";

You need to use this :
static readonly string scriptSuccessUpdate = "";

check out the correct way to use quotes. When to use double quotes " and when to use single quote '
 That was the only problem with your code.
Answer: You Use " .
Correct Code :
static readonly string scriptSuccessUpdate = "\n" +
            "alert(\"Update Successful - Please surf to other pages to shop\");\n ";
Comment: review your answer, then edit the code format and insert problem description, thanks, this answer is horrible

Newline in constant and ; Expected


difference between sequence and series of functions regarding uniform continuity?

Question: Those two confuses me. Could anyone please explain the main differences?
Thanks in advance
Comment: The main differences between what?
Comment: Sorry i wasnt specific enough. When proving something is uniformly continuous.
Comment: Any sequence can be written as a series and vice versa (assuming the values are in a vector space or some other space which allows adding/substracting the elements), e.g. $a_k = \sum^k_l b_l$ and $c_i = \sum^i_k (c_k-c_{k-1})$. You may simply observe things easier in one or the other representation. Of course this applies to functions, too.
Answer: Series of functions are specific type of a sequential functions! So, we can see a serie of functions as a sequence of functions: Let $\sum\limits_{n=1}^\infinit f_n(x)$ be the serie. Than the sequence $S_n=\sum\limits_{k=1}^n f_k(x)$ representes the same serie. So, while serie and sequence are same, than the uniform continuity states same for both cases.


How to report percentage change in proportions?

Question: I want to compare changes in the proportion of fruit purchases over time for a household. For example, in year 1, 4/40 (10%) fruit were apples, in year 2, 12/80 (15%) fruit were apples.
When reporting this in a paper, it feels inappropriate to report the percentage change in a proportion (i.e. "there was a 50% increase in the proportion of apples), but the alternative ("there was a 5 percentage point increase in the proportion of apples") ignores the underlying magnitude. I was curious if there is a good rule of thumb for how to report relative changes in relative quantities (e.g. percentage change of proportions, or percentages, etc).
Comment: Differences can be as important as ratios, here and indeed elsewhere. A more subtle point is that many effects are better expressed  on a logit scale. Much depends on your readership and analysis.
Answer: As a start,

I'd recommend to make sure that the denominator is spelled out every time you mention percentages, fractions and relations to avoid confusion.
This is always recommended, but doubly important here.
In similar situations I try to be consistent in which fraction is reported as percentage. So in your example, if I decide to report the fraction of apples in the purchases as percentage, then the change of that percentage is reported e.g. as fold change (if you want to emphasize that it's multiples). IMHO it doesn't hurt to make doubly sure and also report the fractions again:

the fraction of apples among the fruit purchases by year 2 had increased to 1 1/2 times that of year 1, i.e. from 10 % to 15 %.

(IMHO e-ink isn't that expensive, and it is far more tedious to try finding out what the reference/denominator is if unexplained percentages or fractions are inconsistently sprinkled throughout a text than to skip over clear but redundant information - the more so as the reader may not find the information as redundant as the author ;-) ).