A question about the statement of Lemma $1.1.3$ in Huybrechts' Complex Geometry

Question: On page $6$, Lemma $1.1.3$ of Huybrechts' Complex Geometry, it says

Let $U \subset \mathbb{C}^n$ and let $V \subset \mathbb{C}$ be an open neighbourhood of the boundary of $B_{\epsilon}(0) \subset \mathbb{C}$ where $\mathbb{C}$ is the complex plane. Assume that $f: V\times U \to \mathbb{C}$ is a holomorphic function. Then $g(z)= \int f(\eta, z_1, \dots, z_n)\,d\eta$ is a holomorphic function on $U$.

What is the meaning of "let $V \subset \mathbb{C}$ be an open neighbourhood of the boundary of $B_{\epsilon}(0) \subset \mathbb{C}$"? Is $B_{\epsilon}(0) \subset \mathbb{C}$ the boundary of $V$ or $V$ is a open neighbourhood of $B_{\epsilon}(0) \subset \mathbb{C}$ or $V$ is an open neighbourhood containing $B_{\epsilon}(0) \subset \mathbb{C}$?
Answer: "Let $V \subset \mathbb{C}$ be an open neighbourhood of the boundary of $B_{\varepsilon}(0) \subset \mathbb{C}$" means $V$ is an open set containing $\partial B_{\varepsilon}(0)$.
The statement in your post is incomplete; you have not indicated what you are integrating over in the definition of $g$. In the book, it defines $$g(z) := g(z_1, \dots, z_n) = \int_{|\xi|=\varepsilon}f(\xi, z_1, \dots, z_n)\, d\xi.$$ Now note that $\{\xi \in \mathbb{C} \mid |\xi| = \varepsilon\} = \partial B_{\varepsilon}(0)$; this is why you need $V$ to be an open neighbourhood of $\partial B_{\varepsilon}(0)$.
Comment: could I ask you a question regarding the proof of this LEmma
Comment: I haven't looked at the proof in a long time. I think it would be better to ask a separate question.


Replace \\ with / Python

Question: This doesn't work:
import re
re.sub('\\', '/', "C:\\Users\\Judge")

Error:
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    re.sub('\\', '/', "C:\\Users")
  File "C:\Python27\lib\re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "C:\Python27\lib\re.py", line 244, in _compile
    raise error, v # invalid expression
error: bogus escape (end of line)

Answer: Try escaping two backslashes instead of one: \\\\
re.sub('\\\\', '/', "C:\\Users\\Judge")
You are just passing the RE engine one backslash, which confuses it. So, not only do you have to escape the backslashes for Python to be happy, you need to escape it again for RE. Since you are escaping two backslashes, you need four total.
If you aren't using any regular expression features, perhaps you'd be better off with string's simpler replace method:
'C:\\Users\\Judge'.replace('\\', '/')
Comment: Why in the world can't it treat it as a raw string? This makes no sense to me!
Answer: You don't need a regular expression for such a simple substitution. And the quoting becomes easier then:
"C:\\Users\\Judge".replace("\\", "/")

Answer: You can also use raw strings:
re.sub(r'\\', '/', 'C:\\Users')

Note the r in front of the search string which interprets backslashes differently from ordinary strings. That is, control sequences like \n will be taken literally, i.e. as backslash followed by n instead of a newline.
Comment: This is the right way. Note, however, that even a raw string cannot end with an odd number of backslashes.
Answer: "C:\\Users\\Judge".replace('\\', '/')

As for regex patterns, use r'\\'
Answer: Assuming you want to normalize your path, and not just generally asking how to turn backslashes into forward ones, you can use the path.normpath() instead. Granted it may not work exactly as you expect, because you are trying to convert away from the windows-form, but consider this sample:
import os2emxpath as path
print path.normpath("C:\\windows\\hello")

prints

C:/windows/hello

EDIT
As Oben points out in the comments the backslash-ed string is the correct form for windows, so it should work for most of your needs. However if you want to mangle that to some other form, you could just import the corresponding path module.
Comment: -1: Accroding to the [docs](http://docs.python.org/library/os.path.html#os.path.normpath) this collapse redundant separators and on Windows slashes are converted to backslashes (but not the other way around).
Comment: @Oben True, but you can pretend that you are not on windows, and import the corresponding module. After all that's what the asker is suggesting, because why would we want to mangle a directory string that would work well on windows?
Comment: Gleno, don't get me wrong, `os.path.normpath` is a good tool to recommend in general. However, the OP does not provide much context what his final goals are -- taking the question as it is, `normpath` isn't the solution. Also, importing `os2emxpath` to force forward-slashing is kind of a dirty hack. I'm willing to undo my downvote once the OP clarifies that he is indeed looking for a `normpath` normalization.
Answer: You need to use \\\\:
re.sub('\\\\', '/', "C:\\Users\\Judge")

Or use the r modifier:
re.sub(r'\\', '/', "C:\\Users\\Judge")

See Python documentation on re.

Replace \\ with / Python


Como faço para excluir parte de uma string em um pandas.DataFrame

Question: Tenho um DataFrame com a coluna Assinatura.Cadastro, porém a data e hora está tudo junto.

Como eu posso deixar somente o campo de horas, excluindo a data ?
Comment: Thiago, editei sua pergunta para facilitar a busca de outros com o mesmo problema, se achar que eu mudei muito o sentido você pode [edit] ou se quiser pode voltar para uma versão anterior acessando [revisões](https://pt.stackoverflow.com/posts/492934/revisions)
Comment: Perfeito, sem problemas.
Answer: Como o dado me parece uma string, voce pode utiliza o metodo slice
df['hora'] = df['coluna'].str.slice(10)
# ou usando índices ↓
# df['hora'] = df['coluna'].str[10]

df['data'] = df['coluna'].str.slice(0,10)
# ou usando índices ↓
# df['data'] = df['coluna'].str[0:10]

Veja o codigo funcionado no ideone
Como você quer substituir você pode simplesmente colocar:
df['Assinatura.Cadastro'] = df['Assinatura.Cadastro'].str.slice(0,10)
# ou usando índices ↓
# df['Assinatura.Cadastro'] = df['Assinatura.Cadastro'].str[0:10]

Comment: agora consegui, muito obrigado pela ajuda.
Comment: Se não for um problema você pode transformar em String, `df['coluna'].astype(str).str.slice(0,10)` o `.astype(str)` transforma em string


If $X/F$ is separable, must $X/F$ isomorphic to $F$?

Question: Suppose $X$ is a Banach space and $F$ is a closed subspace of $X$. Clearly $X/F$ is a Banach space, equipped with quotient norm.
Question: If $X/F$ is separable, must $X/F$ isomorphic to $F$?
The motivation of this question comes from Corollary $3.4$. It seems that I need this fact to conclude that $F$ is linearly complemented in $X$.
Answer: No, in general, this is very false.
A counterexample can already be obtained by taking $X =\Bbb {R}^3$ and $F=\Bbb {R}^2\times \{0\} $.
Then $\dim X/F=1$, but $\dim F=2$, so that they can not be isomorphic.
But since finite dimensional spaces are always separable and complete, your assumptions hold.
Comment: Then may I know how the author obtained conclusion of corollary $3.4$?
Comment: @GEdgar: No, I did not. Every finite dimensional space is complete and hence a Banach space. The question does not say that the spaces under consideration  should be infinite dimensional.
Comment: My error.  For some reason I thought it said $F = \mathbb R^2 \setminus \{0\}$ instead.
Answer: Every separable Banach space is isomorphic to a quotient of $\ell_1$. Certainly most of separable Banach spaces are not isomorphic to a subspace of $\ell_1$.
Answer: In direct sum $X = l^1 \oplus l^2$, take
subspace $F = 0 \oplus l^2$, which is reflexive, to get quotient
$X / F$ isomorphic to $l^1$, which is separable and not reflexive, and therefore not isomorphic to $F$.


Flatpickr stop text input and remove Iphone default calender

Question: Using flatpickr for our calendars, are we running into issue with the Iphone/Ipad. On calender open, the curser is 'in' the text box, which triggers the default Iphone calender as shown beneath.
This works 100% on android and chrome mobile simulation.
does any know how to disable

let config = {
            ...this.minDate ? { minDate: this.minDate.toDate() } : {},
            ...this.maxDate ? { maxDate: this.maxDate.toDate() } : {},
            locale,
            defaultDate: this.date.toDate(),
            dateFormat: DATE_FORMAT,
            disableMobile: true
            }
<input type="text" data-input="" class="form-control wdio-arrival qa-arrival-date-input book-box-datepicker flatpickr-input active" aria-label="Arrival date" readonly="readonly">
Answer: The answer is to put onfocus=this.blue() and readonly in the html

<input type="text" onfocus="this.blur();" class="form-control" @input="onInput" v-on:click="manualClose" readonly/>


Linear algebra, finding polynomial of degree of 2 or less that gives minimal result for certain condition

Question: yesterday I had an exam in linear algebra, and I had the following problem:
find a real polynomial of deg $\leq$ $2$
$$p(x)= A+Bx+Cx^2$$ that satisfies $p(0)=0$ and the value of $$|p(1)-1|^2+|p(-1)-1|^2+|p(2)|^2$$ is minimal. $$$$after the test I realized almost no one solved this question on the exam(good thing there was a choice :) ), I would be more than thankful if someone could clarify how to solve it or give a good solution.
I'll add and say it's probably related somehow to IP spaces and minimization problems (using the orthogonal projection, triangle equality, or Cauchy-Schwarz inequality in some shape or form)
Answer: Since $p(0)=0$, $A=0$.
Now $p(1)=B+C$, $p(-1)=-B+C$ and $p(2)=2B+4C$. So, the objective function is
$$\Phi=(B+C-1)^2+(-B+C-1)^2+(2 B+4 C)^2=6 B^2+16 B C+18 C^2-4 C+2$$ Compute the partial derivatives $\Phi'_B$ and $\Phi'_C$; set them equal to zero and you have two linear equations in $(B,C)$. When solved, plug the values in $\Phi$.
Comment: You can also proceed by noticing that the problem is equivalent to minimizing $3B^2 + 8BC + 9C^2 -2C +1= 3(B+\frac{4}{3})^2 + \frac{11}{3}(C-\frac{6}{11})^2 - \frac{1}{11}$
Comment: @Jorge. Yes, for sure ! Again, complete the square ! Cheers :-)
Comment: Sorry, I miss a $C$. Probabily your method is faster and you get the same equations, i guess.
Answer: Indeed there is a nice geometry way:
we have to mimimize the square of the distance between the points $(x,y,z)$ and $(1,1,0)$ where $x=p(1)=B+C,y=p(-1)=C-B,z=p(2)=2B+4C$ clearly $x,y,z$ lie in the plane $\phi=3x+y-z=0$.
So the minimum distance between the point  $(x,y,z)$ and $(1,1,0)$ is the distance between the plane $\phi$ and $(1,1,0)$ $$=\frac{3(1)+1-0}{\sqrt{3^2+1^2+1^2}}$$ and the answer will be the square of this distance which is $\frac{16}{11}$


Is this formula related to the energy function / boltzmann distribution?

Question: I am reading research done in this thesis. On page 20-21 (section 2.1) of the thesis, it describes the following stochastic model:

... let us focus for the rest of this chapter on
  time-varying signals ... In this context,
  an observed object is simply a signal in a time window of a certain length. A latent
  source object may be thought of as a signal corresponding to a prototypical type of
  event. If the same type of event were to happen many times, we suppose that the
  resulting observed signals are noisy versions of the latent source signal corresponding
  to that type of event.
We say an observation $s$ from an infinite stream $s_{\infty}$, is generated by a latent source
  $q$ if $s$ is a noisy version of $q$. Accordingly, we propose the following stochastic model
  relating a latent source $q$ and an observation $s$:
  $$P(s \text{ generated by } q) \propto \text{exp}(-\gamma d(s,q))$$
where $d(s, q)$ is the distance between $s$ and $q$ and $-\gamma$ is a scaling parameter.

I had never seen this formula before, and after looking around, I think it may be related to a potential function, whose representation is the Boltzmann distribution. There is a picture on page 23 of the thesis depicting what seems like different potential values.
Am I correct? Any other insights/references are welcome.
Answer: The Boltzmann distribution is not only a different expression (it shares the exponential term, but so do many other distributions), but also a much different mechanism that generates the distribution (The Boltzmann distribution is more like related to a combinatorics problem relating probability of an event, observing some energy or energy distribution, to the size/density of the set of points in the sample space with that energy distribution).
The distribution that you have, when using the squared distance $d (s,q) = \sum_{i=1}^{N_{obs}} (s_i-q_i)^2 $ looks more like a multivariate Gaussian distribution.
When you substitute that term then the equation becomes:
$$P(s \text{ generated by } q) \propto \prod_{i=1}^{N_{obs}} \text{exp}(-\gamma (s_i-q_i)^2)$$
I haven't read much more from that thesis but it looks like some sort of generalization of k-means clustering or mixture model.
Comment: this looks like some kind of a kernel method
Comment: @MartijnWeterings I did some further looking into and I've come to the conclusion that this is a spin on the radial basis function. Since this is related to SVM kernels, k-means clustering, and other critical topics, it is confusing that the authors never mentioned this.
Comment: I am not sure how you connect the euclidean distance formula with the multivariate Gaussian distribution. Also, I looked into some online k-means clustering and I didn't see any references that seemed similar, can you provide one that does?
Comment: @guy A multivariate distribution can be related to the Euclidean distance by considering a geometrical interpretation https://en.m.wikipedia.org/wiki/Multivariate_normal_distribution#Geometric_interpretation


Is a pairwise Cox regression approach valid for small samples?

Question: Firstly, some background on the dataset:
I am performing survival analysis on a 28-event dataset. We found a genetic marker that predicts survival on a drug. Examining the data, the proportional hazards assumption appears to be met. I want to perform Cox regression with the goal of identifying potential confounders.
The issue is that with a 28-event dataset, I can't really fit more than 2 independent variables at a time to the data without risking overfitting. My approach has been to fit each potential confounder in turn together with my variable of interest (the genetic marker) and observe the impact on the regression.
My question is whether this is a valid approach for determining whether these other independent variables are confounders or not. Is there anything fundamentally wrong with this "pairwise" approach - aside from not being able to catch confounders which may have an impact on the regression together but not apart?
Answer: As Frank Harrell puts it on page 2 of Regression Modeling Strategies, "Testing too many hypotheses is related to fitting too many predictors in a regression model"; and "If the sample size is insufficient for modeling it is often insufficient for tests or estimation."
If you were to do regressions with multiple selections of a second variable to combine with your marker, you would at least have to consider the dangers inherent in multiple testing. Note that this approach could lead to both Type I and Type II errors in terms of evaluating the prognostic importance of your marker.
There is a suggestion from simulation studies that the rule-of-thumb of 10 events per predictor can be somewhat relaxed when adjusting for confounders, perhaps down to as low as 5 events per predictor, but one should proceed cautiously and use procedures like bootstrapping to try to evaluate potential over-fitting and bias.
With only 28 events, you are evidently still in the exploratory stage of this study. From that perspective, playing with your data in the way you suggest may help point the way to better design of later studies to evaluate the marker rigorously. But keep in mind the dangers inherent in trying to glean too much information from too few data points.
One further note: as you proceed with your study, think closely about what you mean by "confounder." If you are simply adjusting for other variables that might affect outcome, then a simple multi-variable model makes sense. If, however, "confounders" are thought to affect the relation of your marker to outcome, then you need to incorporate interaction terms in your model, and you will need even more events.
Answer: My advice is to include the most important known prognosis factors as confounding variables, in the model. This could be a problem with a small sample size, but is the way to make sure that you consider all the relationships between the genetic variable and the prognosis factors.


Transcribing a PDF to Guitar Pro

Question: I am very new to Guitar Pro and music theory/notation in general. I have a pdf with some music that I want to input into Guitar Pro, but it seems like the time signature doesn't match with the notes in bars. Is the file wrong or am I not understanding something?
I attached the first line of what I have.
Comment: Does this answer your question? [Can I put different note lengths on guitar pro (in one bar )](https://music.stackexchange.com/questions/80876/can-i-put-different-note-lengths-on-guitar-pro-in-one-bar)
Comment: @Aaron I see that the bars are split between two voices but I can't figure out how exactly
Comment: The proposed duplicate addresses how to do the Guitar Pro entry. See [Too many notes in this measure](https://music.stackexchange.com/questions/53041/too-many-notes-in-this-measure) for an explanation of the seeming mismatch between notation and time signature.
Answer:
The reason the notes and time signature seem not to match up is that there are two separate "voices" happening simultaneously. This idea is discussed in Too many notes in this measure and linked Q&A.

To identify the two voices, just know that the dotted quarter notes are one voice, and the eighth rests/notes are the other.

GuitarPro allows for multiple voices (up to four) using the Edit -> Voices menu. Can I put different note lengths on guitar pro (in one bar) discusses this and includes a link to the GuitarPro help center.

Transcribing a PDF to Guitar Pro


How to use Linear Indicator dynamic stock values

Question: I want linear indicator for dynamic values how to use condition in stock details and color values
Answer: You can try this.
<code>double stockValue = 0.5; // update stock value
LinearProgressIndicator(
   backgroundColor: const Color(0xFFB4B4B4),
   valueColor: AlwaysStoppedAnimation<Color>(stockValue == 1?Colors.red:Colors.green),
   value: stockValue,
),
</code>


Why does user column name has UNIQUE Constraint?

Question: I got aware that the column name in TABLE users has a UNIQUE Constraint, when I tried to register a 2nd user with the same username : it returned a `integrity constraint violation 1062 duplicate entry '' for key 'name'.
Lets' say 2 of my customers called "John Doe" want to create an account : Ths 2nd one could not then ?!
So I made a quick SQL fix
ALTER TABLE `users` DROP INDEX `name`

I'd like to be sure it's not a very bad idea for some reasons ?
Config : this is a Drupal Commons distro
Comment: The name field is the username of your user and should be unique, just like the mail field.
Comment: @ScottJoudry, thanks for your reply. I realise, maybe tired, I made a stupid confusion btw real name & login. I may vote for deleting that question and try to solve that bug then
Answer: It's a bad idea, your are modifying a core feature of Drupal that others module (and the core itself) may relay on. That's the reason why that column has 'UNIQUE' option, because Drupal requires unique username. Think on user login: how you can login with different users if the have the same username?
Check this answer where you may find more info:
Is it possible to allow duplicate usernames ?
Comment: All have moments of confusion :). I think you can leave the question because can be an advice for others that may want to make thatn change or wonder why username is unique, but it's up to you.
Comment: Thanks for your reply. Well people actually log in with email, cause I already use Email registration (don't remember but I think it came with Commons). I realise, maybe tired, I made a stupid confusion btw real name & login. I may vote for deleting my question :)
Comment: Check the answer I link, some answers talk about login with email.
Comment: Yes, realname is absolutely different from username, in fact you can make username not visible for users and be only used by Drupal internals.
Comment: of course, tks, I had a moment of confusion :(


"symmetry" in the sense of Abel-Jacobi map of hyperelliptic curves

Question: I met such a very interesting problem in algebraic curves (from Griffiths' Introduction to algebraic curves):
Denote by $u: Div(C)\rightarrow Jac(C)$ the Abel-Jacobi map of the compact Riemann surface $C$. Identify $C$ with the subset $\{1\cdot p ~|~p\in C\}$ of $Div(C)$. Then $u(C)=-u(C)$ iff $C$ is hyperelliptic.
I'm a beginner and I only know the basic definition of a hyperelliptic surface, namely admitting a 2-fold holomorphic mapping onto $\mathbb{P}^1$. Is there any further properties of hyperelliptic surfaces that I can use to tackle this problem? Thanks in advance for any suggestions!
Comment: Maybe you can take base point $p_0$ to be fixed by hyperelliptic involution $\tau$, then show that $\int_{p_0}^p=-\int_{p_0}^{\tau(p)}$.
Comment: @AGlearner thanks! but I have a further question: does the result $u(C)=-u(C)$ depend on the choice of the base point $p_0$?
Comment: @AGlearner I am a little puzzled. I think the geometric interpretation would tell me $\int _{p_{0}} ^p=\int _{p_{0}} ^{\tau(p)}$, without the sign; because locally that isn't a ramification point. (This is also the reason why I can't complete the proof at beginning. )  Could you please explain the geometric intuition of the sign? thanks!
Comment: Here is my intuition: The derivative of Abel-Jacobi map is the canonical map, but the canonical map is 2:1 so I regard it as an even function, say $x\mapsto x^2$ on $\mathbb R$. Now its antiderivative $x\mapsto \int_0^x(x^2)=\frac13x^3$ is an odd function, so that's why $u(C)$ is symmetric. Note that I choose base point to be ramification point, and shifting graph of an odd function will not be odd, so the base point really matters.
Comment: @AGlearner  Thank you. So to be precise, the argument should be modified as "there exists a base point of $C$ s.t. the Abel-Jacobi map has the property $u(C)=-u(C)$". But I still don't know how to write the proof in a rigorous way...and how about the necessity?
Answer: As I mentioned in the comment, the statement is based on some elementary observations in Calculus:
$$\textit{The antiderivative of an even function is an odd function},$$
when picking the critical point as the base point, and the other direction is more or less:
$$\textit{If an antiderivative of a function}~f~\textit{is odd, then}~f~ \textit{is even}.$$
We should apply the "odd function" to the Abel-Jacobi map $u:X\to JX$, and the "even function" to the canonical mapping $u:X\to \mathbb P^{g-1}$ (or maybe its dual space) by noting that the canonical mapping derived from the derivative of the Abel-Jacobi map $$du:TX\to \mathbb PT(JX)\cong JX\times \mathbb P^{g-1}\to \mathbb P^{g-1},$$
by sending $x$ to $[\omega_1(x):\omega_2(x):\cdots:\omega_g(x)]$ which vanish at the tangent line at $x$.
Here is the proof. For sufficiency: Suppose $X$ is a hyperelliptic curve, then it is a two-sheeted cover of $\mathbb P^1$ along $2g+2$ points $p_1,...p_{2g+2}$. We draw slits between $p_i$ and $p_{i+1}$ for $i$ odd, then $X$ can be thought as two copy of $\mathbb C$ glued along the $g+1$ segments (and with an $\infty$ point added). Let's say $p_1=0$ and $p_2=1$. We choose $0$ to be our base point.
Then a point on the "lower sheet" can be joined to $0$ by a path $l$ which does not cross any of the slit, while a point on the "upper sheet" can be joined to $0$ by a path $l'$ which cross the slit $[0,1]$.
In particular, if the point on the lower sheet $x$ and the point on upper sheet $x'$ have the same "shadow" (same image under the canonical map), $$l+l'+\gamma=0,$$ where $\gamma$ is a loop homologous to a small circle encompassing $[0,1]$ and represents a nonzero homology class in $H_1(X,\mathbb Z)$. In other words, the Abel-Jacobi image of $x$ and $x'$ differ by a sign:
$$u(x)=-u(x').$$
For necessity, since $u(X)=-u(X)$, for any $x\in X$, the inverse map on the ambient torus defines a holomorphic map $\tau:X\to X$. Since it is an involution,
$$x+\tau(x)=0,$$
and the equation is complex differentiable with respect to the parameter $x$. Taking the differential gives
$$dx+d\tau(x)=0.$$
This says that as the holomorphic differential, $dx=-d\tau(x)$, so in the projective space $(\mathbb P^{g-1})^*$, $[dx]=[d\tau(x)]$. Therefore, the canonical mapping of $X$ is not injective, thus $X$ has to be Hyperelliptic.
Comment: Oh, I understand! Thank you very much for the precise proof!


Feeds vs. Aggregator for rss

Question: Is it fair to say that aggregator is retained in d7 core for legacy support, and that Feeds is the likely successor?   Feeds covers more scenarios than aggregator, and appears to be better situated for adaptions, although the generalization makes it more difficult to understand how to go about implementing.    Are there projects that you can recommend that build on themes to implement particular use cases?
--- Looking through the Feeds documentation, we find the statement

"Feed: aggregation importer. Aggregates RSS/Atom feeds to nodes.
  Provides a node type Feed and a node type Feed item. Create one or
  more "Feed" nodes to add RSS/Atom feeds to your site. On cron, these
  feeds will continuously produce "Feed item" nodes. Requires the
  Aggregator core module to be enabled.

So project/feeds depends on core aggregator, although it seems to overlap and extend functionality as well.
Answer: Even though the module's name is 'Feeds' , it can import CSV, XML and other types of data too. Also, you can attach them to a stand alone form or a node type form.
The basic difference between aggregator and Feeds module is, how it stores data.
Aggregator module stores categories, feed URLs and imported data in its own tables. You will have Views support but it cannot be extended like nodes or such entity.
Also, you will not be able to map data. It's almost a fixed structure, like title to title, body to body, etc.
But in case of Feeds, you can decide what you need.
You can build a standard feed importer that maps feed item's title to node title and contents to a body field. But you can also be radical by mapping to other fields.
You also can use different entities as the target.
It also has 'pubsubhubbub' support which Aggregator doesn't support.
Both modules uses cron to fetch data.
Use aggregator if you want to show contents from few RSS/atom feeds in a simple block.
For all other cases, I'd recommend Feeds module.
Answer: I would suggest "Feed import" module. I have a great experience at creating node with images and files attached to their fields. Hope it helps.
Comment: For the record, project/feeds contains a module called feeds_import, which is a features example illustrating Feeds' import capabilities;  on the other hand, project/feed_import installs a single module, feed_import, which looks to be a proposed alternative to feeds.
Comment: Feed Import only has a few hundred installs and no documentation on the project page.  The Feeds module has over 30k installs and a fair amount of documentation; in addition, it is used by some of the largest organizations using Drupal and thus extremely likely to receive updates and fixes for years to come.  While there are probably cases where the Feed Import module is useful, I highly doubt that it allows for "more complex actions" than what one can do with the Feeds module.
Comment: I know there are big distance between docs, instals, and evens bugs. But Feed import let's you create nodes from, for example, any urls and let you download files and store them in any directory you specify. I'm not an expert, but i think Feeds it's just for the most common use cases, while Feed import it's more specific when importing complex data.
Comment: The Feeds module can handle extremely complex use cases, as the first page of the documentation suggests (http://drupal.org/node/622696).  Feeds is definitely **not** just for the most common use cases; it gives developers the power to set up extremely specific workflows for site(s) as necessary.  If anything, it offers too much control.
Answer: For Drupal 8, Aggregator is stable as of April 2016 (part of core) and works with views out of the box.
Aggregator is bare-bones next to the Feeds module but useful nonetheless. Especially since the Feeds modules appears to be ways off from a D8 port.

Feeds vs. Aggregator for rss


Iptables on Centos 7 doesn't work after reboot

Question: I am on Centos 7, removed the new firewall and installed a classic iptables service. I have a guest machine in it with Debian 8.1 and static external ip.
I do:
echo 1 > /proc/sys/net/ipv4/ip_forward
sysctl -w net.ipv4.ip_forward=1
iptables -P FORWARD ACCEPT

and:
iptables -t nat -I PREROUTING -d *external_ip* -i enp2s0 -j DNAT --to-destination 192.168.122.72
iptables -t nat -I POSTROUTING -s 192.168.122.72 -o enp2s0 -j SNAT --to-source *external_ip*
iptables -P FORWARD ACCEPT

And my guest system begins to work and become able on the Internet.
Then I do service iptables save, restart host machine and my guest machine becomes unavailable on the network. But when I check iptables rules (iptables -t nat -L --line-numbers) I see that all my rules are there. When I flush all iptables rules and enter them again - it begins to work again until new reboot.
My friend suggested a solution to write an sh script with these rules and add it to rclocal, but maybe there is a better solution?
Answer: If you're writing your own NAT rules for your virtual machines, rather than allowing libvirt to manage them, then the virtual network to which the VMs are connected should be set up as a routed network, not a NAT network.
You can fix this with virsh net-edit <network> and change:
  <forward mode='nat'/>

to:
  <forward mode='route'/>

(And this is perfectly doable with firewalld; I have one such machine in production already.)
Comment: That worked! Thanks! Dear Mr. Hampton, maybe you can help with my other question? http://serverfault.com/questions/707718/no-internet-access-after-importing-virtual-machine-image-to-a-new-host-machine
Answer: If you want to use old iptables services intend of firewalld, you can do as follow
iptables-save > /etc/sysconfig/iptables

In this way, the rules you inserted by hand, are saved and applied at boot time, you need to be sure the old iptables services is enabled at boot time.
Comment: He said he already did that!
Comment: for me it works, maybe he is missing net.ipv4.ip_forward=1 in /etc/sysctl.conf


Parsing datestring in format "dd/mm/yyyy" in moment.js

Question: I can't parse the simplest date string for some reason. the following is giving me 'invalid date'.
 moment.locale('en-gb');
 var tempDate = moment("23/07/2018").format("DD/MM/YYYY");

this doesn't work either:
 moment.locale('en-gb');
 var tempDate = moment("23/07/2018");

Answer: You can use String+Format version of the moment function:
moment("23/07/2018", "DD/MM/YYYY")

Comment: @BMills if you set "en-gb" locale, you can use "L" format `moment("23/07/2018", "L")`
Answer:

var mydate= moment("23/07/2018","DD/MM/YYYY").format("DD/MM/YYYY");
console.log(mydate);

Comment: they were likely typing at the same time
Comment: I fail to see how this answer is any different than the one already posted 5 minutes ago....


Como criar uma nova tag img com jQuery?

Question: Gostaria de alterar o c:\imagem.jpg de acordo com o que foi selecionado no <option id="selecao" value="01">c:\imagem.jpg</option>.
Segue o código:

<DOCTYPE html>

    <select name="select-native-fc" >
        <option id="selecao" value="01">c:\imagem.jpg</option>
    </select>
    <button id="btnTeste">Testar</button>

Este é o código da Views:

@model ProjetoDelphiMobile.Models.cliente

@{
    ViewBag.Title = "";
}

<form>
    <fieldset data-role="controlgroup">
  @*

*@

               Foto:

                    @Html.DropDownList("idFoto", String.Empty)

              <button id="btnTeste">Testar</button>

Retornar para consulta

    </fieldset>
</form>

Este é o código do Controller:
    public ActionResult AtualizaCliente(int id)
    {
        ViewBag.idFoto = new SelectList(dao.fotos, "idFoto", "Foto");
        ViewBag.idInformacao = new SelectList(dao.informacoes, "idInformacao", "titulo");
        return View(dao.cliente.Find(id));
    }

Answer: Se queres criar uma imagem nova usando a informação do select  podes fazer assim, usando o método .text() que te dá o texto do selec:
$("#btnTeste").click(function(){
      var src = $('[name="select-native-fc"] option:selected').text();
      alert(src);
      var img = $('', { id: 'Myid', src: src , alt:'MyAlt'}) .appendTo($('#divPrincipal'));
});

Sugiro que em vez de dar ID's a cada option que dês o ID ao próprio select, uma vez que IDs têm de ser únicas.

Como criar uma nova tag img com jQuery?


adding deeper menus in vertical drop down list

Question: I am trying to change an existing html drop down menu to add more drop menus within other drop down menus. My issue is I can't seem to make the dropdown menu appear as a hover drop down 2 levels deep. What CSS syntax did I forget to add in this code?

nav {
 /* Repeating background image */
 background: #d3d3d3;
 width:300px;
 margin:20px;
}

nav ul {
 /* Removes bullet points */
 list-style:none;
 margin:0;
 padding:0;

}
nav ul li {
 /* Any child positioned absolutely will be positioned relative to this */
 position:relative;
}
nav a {
 color:#000000;
 padding:12px 0px;
 /* Fill all available horizontal space */
 display:block;
 /* Remove underline */
 text-decoration:none;
 /*
 New CSS3 animations:
 apply transition to background property, taking 1s to change it
 */
 transition:background 1s;
 -moz-transition:background 1s;
 -webkit-transition:background 1s;
 -o-transition:background 1s;
 font-family:tahoma;
 font-size:13px;
 text-transform:uppercase;
 padding-left:20px;
}
nav a:hover {
 /*
 RGBA background for transparancy:
 last number(0.05) is the transparency
 */
 background: RGBA(255,255,255,0.05);
 color:#fff;

}
nav a:hover span {
 background: #7d2c41;
 transform:rotate(90deg);
 -moz-transform:rotate(90deg);
 -webkit-transform:rotate(90deg);
}
nav ul li:hover ul {
 display:block;
}
nav ul ul {
 position:absolute;
 left:300px;
 top:0;
 border-top:1px solid #e9e9e9;
 display:none;
}
nav ul ul li {
 width:200px;
 background:#0000FF;
 border:1px solid #e9e9e9;
 border-top:0;
}
nav ul ul li a {
 color: #0000FF;
 font-size:12px;
 text-transform:none;
}
nav ul ul li a:hover {
 color:#0000FF;
}

nav ul ul ul li {
 width:200px;
 background:#0000FF;
 border:1px solid #e9e9e9;
 border-top:0;
}
nav ul ul ul li a {
 color: #0000FF;
 font-size:12px;
 text-transform:none;
}
nav ul ul ul li a:hover {
 color:#0000FF;
}

nav ul ul ul ul li {
 width:200px;
 background:#0000FF;
 border:1px solid #e9e9e9;
 border-top:0;
}
nav ul ul ul ul li a {
 color: #0000FF;
 font-size:12px;
 text-transform:none;
}
nav ul ul ul ul li a:hover {
 color:#0000FF;
}
nav span {
 width:12px;
 height:12px;
 background:#fff;
 display:inline-block;
 float:left;
 margin-top:3px;
 margin-right:20px;
 position:relative;
 transition:all 0.5s;
 -moz-transition:all 0.5s;
 -o-transition:all 0.5s;
 -webkit-transition:all 0.5s;
}
nav span:before {
 content:"";
 width:12px;
 height:2px;
 background:#d3d3d3;
 position:absolute;
 left:0px;
 top:5px;
}
nav span:after {
 content:"";
 width:2px;
 height:12px;
 background:#d3d3d3;
 position:absolute;
 left:5px;
 position:top;
}

 S

 R

 H

 A

 D

 Operations Support Compliance

 HC

 a

 D

 H

 A

 D

 P

 O

Answer: Use the child selector >.
Right now nav ul li:hover ul targets ANY ul that is a descendant of a hovered li that is a descendant of ANY ul that is the descendant of ANY nav.
Another way to phrase it: if you hover an li inside of a ul inside of a nav it will set EVERY ul inside of that hovered li to display: block;.
Using the child selector > will help you gain control of which dropdowns get shown and which don't. Preventing the "far reaching" capabilities of your original selector.
Change
nav ul li:hover ul {
 display:block;
}

To
nav ul > li:hover > ul {
 display:block;
}

Demo JSFiddle.
Comment: thank you I will now try to see if I can add a few more drop downs within drop downs
Comment: sorry another question how can I position the last drop down menu so that it's beside the selected menu?


How do I prove this limit (multivariable limit)?

Question: I evaluated this on the computer to be 0.5, but I need to prove it.
\begin{align*}
\lim_{n\to\infty}\left(\lim_{N\to\infty}\left(\frac{n+1}{n+N+2}\right)\right)
\end{align*}
I really want to just combine $N$ and $n$, so the limit is obviously 0.5, but am I allowed to do that? $N$ and $n$ are both going to infinity, but since infinity is more a concept than a value, is that mathematically sound?
If not, is there a way to solve this without combining the two terms?
My other thought process was to apply L'hopital's rule (sort of) and take the derivative of both $N$ and $n$ so I'd get $\frac{1+1}{1+1+2} = \frac{1}{2}$, but I don't think that really works either.
Comment: I believe the limit is zero. $$\frac{n+1}{n+N+2}=\frac{\frac{n}{N}+\frac{1}{N}}{\frac{n}{N}+1+\frac{2}{N}}$$ so taking the limit with respect to $N$ first, using algebra of limits, gives $\frac{0}{1}=0$
Comment: Are for both variables $n\to \infty$, $N\to \infty$ or $n\to +\infty$, $N\to +\infty$?
Comment: Probably what you actually want is to make $(n,N)$ go to $\infty$ along the diagonal (or a neighborhood of it) or something like that.
Answer: As it is written we have
$$\lim_{n\to\infty}\left(\lim_{N\to\infty}\left(\frac{n+1}{n+N+2}\right)\right)=\lim_{n\to\infty}\left(0\right)=0$$
Comment: @SchrodingersDog In this case we have $$\lim_{N\to\infty}\left(\lim_{n\to\infty}\left(\frac{n+1}{n+N+2}\right)\right)=\lim_{N\to\infty}\left(1\right)=1$$
Comment: Would there be a difference if $N$ were the outside limit and $n$ were the inside limit?
Comment: I probably didn't give enough context then because it's part of a larger limit. Basically I'm evaluating a limit of a product operator (the evaluation of which gives this post's limit), which comes from a ratio test of a summation. The summation itself has the $N$ limit, and the $n$ limit comes from applying the ratio test. I don't know if that changes anything, but I know the above limit in the context that I'm evaluating it to is 0.5 so this is quite confusing, but thank you so much for the help.
Comment: @SchrodingersDog You could post the original problem here in your question or making a new question on that. Of course the value for the limit depends upon $n$ and $N$ tend to infinity. Abd indeed for $n=N=t \to \infty$ the limit is $1/2$.
Comment: $\lim_{n\to\infty}(\lim_{N\to\infty}(\prod_{v=1}^{N+2}\frac{n+v}{n+v+1}))$

Upon evaluation, I arrived at this post's limit.
Comment: @SchrodingersDog This product telescopes to $\frac{n+1}{n+N+3}$ and taking th elimit we obtain zero. What about $n$?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/128747/discussion-between-schrodingersdog-and-user).
Answer: Let, for every $n \geq 0$,
$$u_n = \lim_{N\to+\infty}\left(\frac{n+1}{n+N+2}\right)$$
One clearly has $u_n = 0$ for every $n$, so
$$\lim_{n\to+\infty}\left(\lim_{N\to+\infty}\left(\frac{n+1}{n+N+2}\right)\right) = \lim_{n\to+\infty} u_n = \lim_{n\to+\infty} 0 = 0$$


How can I calculate the stability of my dataset?

Question: Forgive my ignorance, I am not a mathematician or statistician. I'll try to explain as clearly as I can.
I have a dataset (image below). The data represents delays of some signal over time. The large "spikes" are caused by incorrect predictions - when an incorrect prediction is made, the delay increases sharply. However, noise and whatnot causes some smaller spikes to occur between the larger ones.
I want to define a metric which will describe how "stable" or "jumpy" my data is, if that makes any sense.
Variance tells us how far values are from the mean, but in my case the large spikes will give too much weight and not give me any information about the smaller spikes. I thought about if I normalise my values and then calculate the variance... but I'm not sure... I've also read about the "index of dispersion", but I cannot tell if this is what I'm after. It's all very confusing to me!
Consider this graph:

And compare it to:

Graph 1 is far more stable: both encounter incorrect predictions (large spikes), but when predictions are correct (between the large spikes), there is a clear difference between the two graphs.
I thought that perhaps this is what I can do:

normalise all data points (I want a score between 0 and 1)
Sum the normalised values
divide the sum by the number of data points.

Like in this Python 3 program:
<code>import random

vector = [int(100*random.random()) for i in range(10)]
print(vector)

min_value = min(vector)
max_value = max(vector)
normalised = [(value-min_value)/(max_value-min_value) for value in vector]
print(normalised)

answer = sum(normalised) / len(normalised)
print(answer)
</code>
My question is: Have I done this correctly, or is there another/better way to do this?
Comment: Your question is unclear. Are you asking about a single number that measures the jumpiness of your whole time series? (if so, the mean may be *fine*: because it is sensitive to extreme values if it deviates from the median by more than a set amount that may work swell). OTOH, if you are interested to know if a particular data point *during* your time series is in a jump: the extremity of the jumps would seem to make a threshold above a certain value correspond to "in a jump." Finally, another way to describe jumpiness would be the proportion of data points that are "in a jump".
Comment: @Alexis My question is about a single number. I can't use the mean because in my updated question, I'd say graphs 1 is better than graph 2 and if I used the mean, it would not tell me how "choppy" or "jumpy" the values are. Sorry, I don'y know if I'm making sense.
Comment: So would a proportion of the time spent in those transient spike work for your purposes? (e.g, proportion of values above that first horizontal line?)
Comment: A very quick and dirty approach would be this: use the median as a low pass filter.
A "moving" median with a large enough window will zero all those very large spikes in both graphs, but it should still show up as a higher number in graph 2 than 1 (which is I think where you are going with graph 1 being more stable).
Comment: Some closely related threads offer solutions that might work for you, including https://stats.stackexchange.com/questions/587385/ and https://stats.stackexchange.com/questions/1142.
Comment: "Variance tells us how far values are from the mean, but in my case the large spikes will give too much weight and not give me any information about the smaller spikes." Don't give up on the variance. Just model your *changing* mean function of time. The error variance or its estimate MSE will be what you want I suspect
Answer: You might look at control charts maths, to identify the areas of your dataset which are stable.
An example of the python code you would use is provided here:
https://medium.com/swlh/process-stability-analysis-with-python-798c4ebdd08a
Hope that helps.
Comment: Any decent (or even poor) control charting method will *detect* all these spikes, including the small ones -- but how would that help?


Changing the colors of QTableView

Question: I want to change the colors of the Table Widget in PyQt5 in those two places, but couldn't find how:

Here's my style sheet so far:
QTableView QHeaderView::section
    {
    background-color:rgb(48, 48, 72);
    color:white;
    }

QTableView QHeaderView::section:checked
    {
    background-color: rgb(48, 48, 72);
    color:white;
    }

QTableView QTableCornerButton::section {
    Background-color:rgb(48, 48, 72);
}

QTableView,QListView::section {
    Background-color:rgb(48, 48, 72);
}

Answer: QTableView QHeaderView {}

sets the properties of the HeaderView without sections
QTableView QHeaderView::section {}

the one of the HeaderViews sections, even of the checked ones, if no different properties for them are set. So you only need to replace the first line of your code by
QTableView QHeaderView, QTableView QHeaderView::section

the section
QTableView QHeaderView::section:checked {}

is only needed, if checked sections shall have different properties
so you can ease your code to
QTableView, QTableView QHeaderView,
QTableView QHeaderView::section, QTableView QTableCornerButton:section
    {
    background-color:rgb(48, 48, 72);
    color:white;
    }

and only if needed
QTableView QVerticalHeaderView::section:checked
    {
    background-color:rgb(255, 0, 0);
    color:white;
    }

Changing the colors of QTableView


Running command with paramiko PTY gives error: write() argument must be str, not bytes

Question: I'm using paramiko to connect to the remote machine via SSH where a bash command is ran and the stdout output needs to be read line by line as they are sent.
This is what I have so far. get_pty=True needs to be set.
import paramiko
import sys

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect('my.host.com', 22, 'root', key_filename="/home/me/.ssh/id_ed25519")

stdin, stdout, stderr = ssh.exec_command("ls", get_pty=True)
while True:
    v = stdout.channel.recv(1024)
    if not v:
        break
    sys.stdout.write(v)
    sys.stdout.flush()

Running this gives the error
  File "/home/me/test.py", line 13, in <module>
    sys.stdout.write(v)
TypeError: write() argument must be str, not bytes

What is the correct way to read the multi-line output from running the command?
Answer: The channel stdout gave you bytes, but the sys.stdout is a TextIO. Use sys.stdout.buffer.write(...) instead.


How do I compute the length of the following curve?

Question: I have the following problem.
I need to compute the length of the curve given by

$z^2=2x,3y=xz$ between $(0,0,0)$ and $(\frac{1}{2},\frac{1}{6},1)$

I first want to find my curve, so geometrically I could draw it with geogebra but I can't see how to find my curve. Could maybe someone give me a hint?
Thanks a lot
Answer: Hint: Use the fact that $x=\frac{z^2}2$ and that $y=\frac{xz}3=\frac{z^3}6$.
Comment: oh nooo, I made the same computations but I somehow doesn't see that one can define $\phi:[0,1]\rightarrow \mathbb{R}$ where $\phi(z)=(\frac{z^2}{2},\frac{z^3}{6},z)$ right?
Comment: Yes, that is correct.
Answer: Parametrize your curve $\vec{r}(t) = (x(t), y(t), z(t))$, and then compute the arc-length integral of the curve:
$$
\int_{t_{1}}^{t_{2}} |\vec{r}'(t)| dt
$$
Hint: Define $y$, $z$ in terms of $x \in [0, 1/2]$
Comment: Now that I see Jose's Hint, maybe you should try his substitution first. It may require less work.


Titled separator in java swing

Question: I want to show titled separator in java swing application. Something like

-------Text-------

I found some third party libraries providing this functionality:

http://www.jidesoft.com/javadoc/com/jidesoft/swing/TitledSeparator.html
http://www.jaxfront.org/member/java-core-api/com/jgoodies/forms/builder/PanelBuilder.html

But I'm interested in a way without using any third party api. Can we do this by extending JSeparator? How else can we do that?
Comment: See my answer here: http://stackoverflow.com/a/9533238/995822 . It uses a `TitledBorder`.
Answer: I think you might be able to use a combination of a MatteBorder and a TitledBorder
MatteBorder mb = new MatteBorder(1, 0, 0, 0, Color.BLACK);
TitledBorder tb = new TitledBorder(mb, "Some Long Text", TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION);

Comment: Great. :) And it should be `TitledBorder` and not `TitleBorder`.
Comment: Typing on iPad, always fun :P
Answer: Use a TitledBorder. Like this for example:
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;

public class TestBorder {

    protected void initUI() {
        JFrame frame = new JFrame(TestBorder.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        TitledBorder titledBorder = BorderFactory.createTitledBorder("Some title");
        titledBorder.setTitleJustification(TitledBorder.CENTER);
        panel.setBorder(titledBorder);
        frame.add(panel);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestBorder().initUI();
            }
        });
    }

}

Comment: It shows text to left, I want the text to be in the center of line separator.
Comment: @mark updated my code. Simply set the justification of the border.
Comment: titledBorder (aka: GroupBoxes) introduce visual noise, so don't use them - nowadays, even win ux guide cautions against using them ... @mark it's rather straightforward to implement a TitledSeperator for yourself, or extract the code from open source projects like SwingX or any other you already found
Comment: @mark exactly :-) Have a look at Karsten's (JGoodies) articles/talks
Answer: That is simple and lower case.
import javax.swing.border.*;

then
BevelBorder bedge=new BevelBorder(BevelBorder.RAISED);
lbl.setBorder(bedge);

-----------------next border type
import javax.swing.border.*;

then
TitledBorder tedge=new TitledBorder(TitledBorder.CENTER);
lbl.setBorder(tedge);

Titled separator in java swing


Do these two rearranged matrices have the same singular values (or the same rank)?

Question: This is the origin of my problem: I have a set of data which expresses which user ($U$ set) applies what tag ($T$ set) to which item ($I$ set). So it is actually a $U×I×T$ tensor $A$ (or 3-dimensional matrix). Now I unfold this tensor A to be two 2-dimensional matrices. Matrix $A_{(u)}$ is $U×IT$, and matrix $A_{(i)}$ is $I×UT$. So these two matrices actually come from the same initial tensor, with differently arranged elements.
The two matrices are the unfolding matrices of the same tensor by different mode.
I am wondering if these two matrices have the same singular values, or the same rank? Or any other relations?
E.g.
$A_{(u)}$=
u_1,i_1,t_1 u_1,i_2,t_1 u_1,i_1,t_2 u_1,i_2,t_2
u_2,i_1,t_1 u_2,i_2,t_1 u_2,i_1,t_2 u_2,i_2,t_2

and
$A_{(i)}$=
u_1,i_1,t_1 u_2,i_1,t_1 u_1,i_1,t_2 u_2,i_1,t_2
u_1,i_2,t_1 u_2,i_2,t_1 u_1,i_2,t_2 u_2,i_2,t_2

(Note e.g.,(u_1,i_2,t_1) or $(u_1,i_2,t_1)$ is a numeral element with 1 as index of $u$ in $U$, 2 as index of $i$ in $I$ and 1 as index of $t$ in $T$)
Comment: E.g., if $b_2=0$, $A_{(u)}$ can be (by a suitable choice of the other parameters) made to have rank 2, while $A_{(i)}$ would have rank 1.
Answer: If you have a single user, $|U|=1$, then $A_{(u)}$ is rank 1, while $A_{(i)}$ is an arbitrary matrix, perhaps of full rank.
So neither the rank nor the singular values need to match.
In this case $A_{(u)}$ is essentially the vector you get by unfolding $A_{(i)}$.
If $\;|U|=u$, then $A_{(u)}$ is essentially the $u$ rows you get from "unfolding" $A_{(i)}^\top$ so that each block of $u$ rows moves as a block.  The unfolding process acts on blocks, where each block corresponds to a value in $T$.
We can see that
$A_{(u)}$ has the blocks in a row, while $A_{(i)}^\top$ has the blocks in a column.
Suppose $A_{(u)}$ has rank $r$.
Then each block has rank at most $r$.
Since $A_{(i)}^\top$ is composed of $|T|=t$ of these blocks, the rank of $A_{(i)}^\top$ (and thus of $A_{(i)}$) can be at most $t \cdot r$.
If $r<u$ then this gives a nontrivial restriction on the rank of $A_{(i)}$.
So you are right that the ranks (and therefore the singular values) of the two matrices are not completely independent, specifically, the ranks must be within a factor of $t$ of each other.


How to install apache2 while not removing apache on debian etch?

Question: I'm looking to do an upgrade from apache1.3 to apache2.2.
My plan was to install apache2 with aptitude, but that tells me apache and related packages will be removed, which obviously I don't want as it's up and running.
I'd like to run apache2 on port 81 until I configured everything correctly before putting it on port 80 and shutting down the old apache.
Any ideas? I'm not really a linux expect...
Comment: Seems like an ugly process - do you have any other options for migration?
Answer: This doesn't address your specific question but it does address the larger underlying problem.
Debian Etch has been at End-of-Life status since February 2010. That means no security updates. If this is a publically facing web server, you will be quite lucky if it hasn't already been successfully hacked. You should upgrade to the current version of Debian Stable (version 6.0). If you do not have the skills to do this yourself nor the time to acquire them, you should hire someone who can. Nothing personal, this is just how it is.
My recommendation is to perform your "upgrade" from Apache to Apache2 by building a new server using Debian 6.0, installing Apache2 and then migrating your website from your old server to the new one. What you suggest will be painful and ultimately unproductive.
Comment: Right, thanks for the help. I'll discuss that with my hosting company to get a decent setup alltogether instead of upgrading just one part.
Comment: I know it's not what you really wanted to hear, but you'll be happy you did it in the end. If you're paying for shared hosting and the platform they are providing is an EOL, you should A) ask for a refund and B) find a new hosting provider.


Making font color same as that of background image

Question: I am designing a webpage with a background-image. There is a white box in the center (using div) and inside the white box is some text. What I want to do is make the text color the same as that of the background of the body. If I set the color attribute of the text to transparent , it disappears since there is a white div. How do I do this?
This is the link to JSFiddle: http://jsfiddle.net/FpJpV/
The html is

Title

The CSS is
body {
    background-color: red;
    font-family: sans-serif;
}

div {
    width: 200px;
    background-color: white;
    margin: auto;
    text-align: center;
    padding: 1em;
}

Note: In the JSFiddle, i used a red background for simplicity but in the real webpage, the background of the body is an image.
Comment: That's not possible with CSS. You cannot see through a containing div if it has a background color but see below.
Comment: what about "color:red;"
Comment: As in a punch-out mask so the underlying image is fully visible?
Comment: My bad, OP, guess I skipped the part about using an image as background.
Comment: possible duplicate of [How to apply Inverse text mask with css](http://stackoverflow.com/questions/15507401/how-to-apply-inverse-text-mask-with-css)
Answer: There are three ways to what you're looking for in HTML/CSS/JavaScript, some a little more hacky than others.

Use <canvas> to draw your shape and type, and set ctx.globalCompositeOperation="xor";where ctx is your canvas context.

var c=document.getElementById('myCanvas');
var ctx=c.getContext('2d');
ctx.font = "bold 36px Proxima Nova";
ctx.fillStyle='blue';
ctx.fillText("MORE",100,87);
ctx.globalCompositeOperation='xor';
ctx.beginPath();
ctx.fillStyle='white';
ctx.arc(150,75,75,0,2*Math.PI);
ctx.fill();
body{
  background: -webkit-radial-gradient(top left,rgb(23, 39, 34) 4%,rgb(56, 99, 99) 37%,rgb(22, 27, 15) 73%,rgb(22, 27, 14) 93%,#232323 100%);
  width:100%;
  height:100%;
}

html{
  height:100%
}
<canvas id='myCanvas'></canvas>

Use mix-blend-mode: screen and set the colour of the text to black.

.blend-mode {
  background:white;
  border-radius:100%;
  width:150px;
  height:150px;
  line-height:155px;
  float:left;
  margin:20px;
  font-family: "Proxima Nova", Hevetica, sans-serif;
  font-weight:bold;
  color:black;
  text-align:center;
  vertical-align:middle;
  font-size:36px;
  mix-blend-mode: screen;
}

body{
  background: -webkit-radial-gradient(top left,rgb(23, 39, 34) 4%,rgb(56, 99, 99) 37%,rgb(22, 27, 15) 73%,rgb(22, 27, 14) 93%,#232323 100%);
  width:100%;
  height:100%;
}

html{
  height:100%;
}

MORE

Use -webkit-text-fill-color:transparent and -webkit-background-clip:text to reveal a copy of the background behind it. This one requires some alignment of the background copy to match the 'original' background.

.wrap{
  margin:20px;
  float:left;
  position:relative;
}

.background {
  width: 150px;
  height: 150px;
  border-radius: 100%;
  background: white;
  position:absolute;
  top:0;
  left:0;
  z-index:4;

}

.text {
  position:absolute;
  top: 25px;
  left: 25px;
  z-index:5;
  background: -webkit-radial-gradient(top left, rgb(23, 39, 34) 4%, rgb(56, 99, 99) 37%, rgb(22, 27, 15) 73%, rgb(22, 27, 14) 93%, #232323 100%);
  font-family: Proxima Nova, Helvetica, sans-serif;
  font-weight:bold;
  line-height:100px;
  font-size: 36px;
  color: #666;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

body{
  background: -webkit-radial-gradient(top left,rgb(23, 39, 34) 4%,rgb(56, 99, 99) 37%,rgb(22, 27, 15) 73%,rgb(22, 27, 14) 93%,#232323 100%);
  width:100%;
  height:100%;
}

html{
  height:100%;
}

MORE

None of these are likely to work that well cross browser, and I haven't tested them!
Answer: Can't do that with CSS; What I suggest:
Try using an image instead.
Use software such as Photoshop/GIMP to cut the text out from a white image so it's transparent where the text was. Save it as a PNG and set the image as the div's background.
Just make sure you remove the white background from the div as well.
EXAMPLE
Like so:


Passing id through url to modal and update table

Question: I have a problem, i was working on this for a few days and i am stuck. What i want to do? I want to pass $id through url to modal, witch opens on click and opens table with data that i can edit/update from mysql, using php!
When i press edit i get data and person id in url but modal is not opening. I think my script/jquery is wrong, can someone look and help me.!!
When i press edit button i get this in url but nothing opens?!?!
http://localhost/zadatak_senso/index.php?poslovni_korisnici#update_poslovni=34

modal --> m_update_ok.php
<?php
// ---- Pocetak modal-a za update poslovnih korisnika ---- //
echo'

        <button type="button" class="close" data-dismiss="modal">×Uredi</button>

Unos poslovnih korisnika

';

      if (isset($_POST['submit_upk'])) {

            $partnername    = $_POST['partner_name'];
            $partnerstreet  = $_POST['partner_street'];
            $partnerzip     = $_POST['partner_zip'];
            $partnercity    = $_POST['partner_city'];
            $partnercountry = $_POST['partner_country'];

            $sql = "UPDATE poslovni_partneri
                     SET
                     Partner_name     = '$partnername',
                     Partner_street   = '$partnerstreet',
                     Partner_zip      = '$partnerzip',
                     Partner_city     = '$partnercity',
                     Partner_country  = '$partnercountry'
                     WHERE Partner_id = '$id'";

        // Prepare statement
        $stmt = $dbh->prepare($sql);

        // execute the query
        $stmt->execute();

        }

        echo'
        <form method="POST" target="_parent" >

              Partner name
              Partner street
              Partner zip
              Partner city
              Partner country

';

        $id = $_GET['Partner_id'];

        $sql = "SELECT * FROM poslovni_partneri WHERE Partner_id LIKE '$id'";
        $stmt = $dbh->query($sql);
        $row =$stmt->fetchObject();

        $partner_name    = $row['partner_name'];
        $partner_street  = $row['partner_street'];
        $partner_zip     = $row['partner_zip'];
        $partner_city    = $row['partner_city'];
        $partner_country = $row['partner_country'];

        echo'

            <input type="text" name="partner_name" value="'.$partner_name.'">'.$partnername.'
            <input type="text" name="partner_street" value="'.$partner_street.'">'.$partnerstreet.'
            <input type="text" name="partner_zip" value="'.$partner_zip.'">'.$partnerzip.'
            <input type="text" name="partner_city" value="'.$partner_city.'">'.$partnercity.'
            <input type="text" name="partner_country" value="'.$partner_country.'">'.$partnercountry.'

        <input type="submit" name="submit_upk" value="Uredi" />

      </form>

</script>';
// ---- Kraj modal-a za update poslovnih korisnika ---- //
?>

index.php
echo'

              Partner name
              Partner street
              Partner zip
              Partner city
              Partner country

              <button type="button" class="btn btn-default btn-sm">Delete</button>

';

        $sql = "SELECT * FROM poslovni_partneri";

        foreach ($dbh->query($sql) as $row)
        {

            echo'

                '.$row['Partner_name'].'
                '.$row['Partner_street'].'
                '.$row['Partner_zip'].'
                '.$row['Partner_city'].'
                '.$row['Partner_country'].'
                Edit
                <input type="checkbox" id="blankCheckbox" value="option1" aria-label="...">

';
        }

        echo'

';

Comment: Don't you mean to use index.php?poslovni_korisnici&update_poslovni=34 ?
Comment: i guess so, im lost in code :P
Answer: Get the hash from the URL: How can you check for a #hash in a URL using JavaScript?
Once you have the hash, simple get the element with the id selector of the hash and then:
$(hash).modal('show')

Comment: does not work, I have not managed to do that. can you make me a code for it


Valores de fórmulas não correspondem

Question: Estou tentando fazer a fórmula do Excel VF(valor futuro) em PHP, porém os valores não estão correspondendo, ou seja, no Excel está um valor para a coluna e no calculo do PHP saem outros valores mas valores quase idênticos, distantes de R$ 1,50 a R$ 3,00.
index.php
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">

            Mes
            Se for investir
            Juros no finan.
            Amortização
            VT
            Valor futuro

          <?php require_once('calcs.php'); ?>
          <?php for($i = 0; $i <= $mes; $i++): ?>

              <?php echo $i; ?>

              <?php echo number_format($sac['G'][$i], 2, ',', '.'); ?>

              <?php echo number_format($sac['H'][$i], 2, ',', '.'); ?>

              <?php echo number_format($sac['I'][$i], 2, ',', '.'); ?>

              <?php echo number_format($sac['J'][$i], 2, ',', '.'); ?>

              <?php echo $sac['K']['vf'][$i]; ?>

          <?php endfor; ?>

calcs.php
<?php
// F = P. (1+i)° + M.[(1+i)° - 1]/i
function vf($taxa,$n,$pgto,$vlr_presente=0, $iterador)
{
    if($iterador > 0):
        // $first  = bcmul($GLOBALS['ul_vf'],   $taxa);
        // $second = bcadd($GLOBALS['ul_pgto'], $first);
        // $vf     = bcadd($GLOBALS['ul_vf'],   $second);
        // $vf = ($GLOBALS['ul_vf']) + ($GLOBALS['ul_vf'] * $taxa + $GLOBALS['ul_pgto']);
        $first  = bcadd(1, $taxa);
        $second = bcpow($first, $n);
        $third  = bcmul($GLOBALS['ul_vf'], $second);

        $fourth = bcsub($second, 1);
        $fifth  = bcdiv($fourth, $taxa);
        $sixth  = bcmul($fifth, $GLOBALS['ul_pgto']);

        $seventh = bcadd($third, $sixth);
        $vf = $seventh;

        $GLOBALS['ul_vf']   = $vf;
        $GLOBALS['ul_pgto'] = $pgto;
    else:
        $vf = $vlr_presente;
        $GLOBALS['ul_vf']   = $vf;
        $GLOBALS['ul_pgto'] = $pgto;
    endif;
    return $vf;
}

$vlr_imovel   = 144000; //var_dump($vlr_imovel);
$vlr_aluguel  = 400.00; //var_dump($vlr_imovel);
$vlr_entrada  = 43200.00; //var_dump($vlr_imovel);
$vlr_encargos = 500.00; //var_dump($vlr_imovel);
$mes = 360;

$taxa = (0.54/100);
$se_for_investir  = $vlr_encargos + $vlr_entrada;

for($i = 0; $i <= $mes; $i++):

    $juros_no_finan    = (($vlr_imovel - $vlr_entrada) - ((($vlr_imovel - $vlr_entrada)/$mes)*$i))*0.007;

    $amortizacao      = ($vlr_imovel - $vlr_entrada)/$mes;

    $vlr_total        = $amortizacao + $juros_no_finan;

    //VALOR FUTURO -------------------------
    // Como: FV = PV x ( 1 + i ) ^ n
    $n            = 1;
    $pgto         = $vlr_total - $vlr_aluguel;
    $vlr_presente = $vlr_entrada + $vlr_encargos;
    $tipo         = 0;
    $one = 0.96;
    $two = 0.42;
    $taxa2        = 0.54/100;

    $vf           = vf($taxa2, $n, $pgto, $vlr_presente, $i);
    //VALOR FUTURO -------------------------

    $sac['G'][] = $se_for_investir;
    $sac['H'][] = $juros_no_finan;
    $sac['I'][] = $amortizacao;
    $sac['J'][] = $vlr_total;

    $sac['K']['pgto'][] = $pgto;
    $sac['K']['vf'][]   = $vf;

endfor;

Explicação do código.
1 - Eu faço um loop nos meses, 360 meses ao todo.
2 - No primeiro loop(0) a função FV é chamada, FV recebe os parametros:
($taxa, $parcelas, $pagamento, $vlr_presente, $iterador_atual) Esses parâmetos
são do loop atual.
3 - Na FV(função) temos condicionais que verificam se o $iterador(que foi passado pelo parâmetro) é > 1, exemplo:
if(iterador > 1):
    //aqui eu faço a formula com as variaveis globais no else abaixo
    //e insiro variaveis globais para ser aproveitadas no proximo loop
else:
    //aqui é o primeiro loop, ou seja a primeira linha do excel(o mês 0)
    //variavel global desse valor passado(será aproveitada no proximo loop)
    //variavel global do pagamento passado(será aproveitada no proximo loop)
endif;
return $valorFuturo;

4 - Agora, no Calcs.php temos o valor futuro que será passado para a view;

O Erro aqui é que os valores não são idênticos, quase, mas não idênticos. Pensei que poderiam ser os floats, que estavam atrapalhando mas não é.
Coloquei o arquivo excel no google drive.
Comment: Reformulei a pergunta
Comment: De novo, coloca um exemplo númerico da sua função. Pegue uma linha que dê diferente e coloque os valores aqui e como é feito a chamada da função para estes valores. Fica muito confuso entender tanta informação assim. Por exemplo, na segunda linha da tabela fica diferente, então qual é a chamada no PHP que gera este valor?
Comment: Por favor, me ajudem, to 2 dias com essa fórmula bendita ai. ^^_
Comment: https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas
Comment: @DanielOmine não coloquei os códigos aqui porque "só eu entendo", eu até queria colocar, mas ele está meio bagunçado, coloquei no Google Drive também para não deixar minha pergunta muito extensa, para que quem quiser resolver possa executar no seu computador, entende? Mas obrigado, nunca tinha lido essas dicas. E o que achou da minha pergunta?
Comment: A pergunta está ok. O problema é que depende de um link terceiro o arquivo excel. Se esse link deixar de existir a pergunta perde o sentido. Por isso torna-se fora de escopo ou não clara o suficiente. E pior ainda se  possui algo que só você entende, conforme comentou. Talvez melhor perguntar num forum pois aqui o formato deve ser mais objetivo.
Comment: @DanielOmine entendi, de qualquer forma consegui chegar numa solução através do link que o MarceloBoni passou abaixo, ai eu coloquei uma resposta como solução, mas obrigado!
Answer: Dada a seguinte formula para se calcular juros compostos dado um valor inicial e um valor de investimento mensal:

Fonte: https://money.stackexchange.com/a/26187
Seria algo mais ou menos assim:
function valorFuturo($valorInicial, $taxaJuros, $periodo, $investimentoMensal)
{
    $jurosComposto = (1 + $taxaJuros) ** $periodo;
    $v1 = $valorInicial * $jurosComposto;
    $v2 = $investimentoMensal * ( ( $jurosComposto - 1 ) / $taxaJuros ) * ( 1 + $taxaJuros );
    return number_format($v1 + $v2, 2, ",", ".");
}

echo "R$ ".valorFuturo(2500, .00333333, 60, 100)."
";

Por falta de exemplo, eu testei usando os mesmos valores:
valorInicial: 2500
taxaJuros: 0.04 anual que mensal vira 0.003333333
periodo: 5 anos ou 6 meses
investimentoMensal: 100

O valor bateu com o esperado: R$ 9704,49
Veja funcionando no ideone
Detalhe !importante!
Para cálculos de valores muito grandes de cunho financeiro, opte sempre por usar o máximo possivel de casas apos a virgula, veja no seu exemplo usa: 0.54/100 que é igual a 0.0054000000000
Se você estender as casas apos a virgula no excel vera que o valor real utilizado de taxa para o calculo é:

Pense em valores grandes, assim como fez
100.000 * 0.0054 = 540
100.000 * 0.00543169 = 543.169

Uma diferença de +3 unidades, e quanto maior forem os valores, maior sera a divergência no valor final.
Comment: No seu deu certinho MarceloBoni?
Comment: To tentando criar um exemplo funcional, seria legal dar um exemplo de valores iniciais (input), e resultado esperado (output)
Comment: Cara a segunda resposta desse link que você me passou funcionou pra mim, vou editar a pergunta pra vocês verem. http://money.stackexchange.com/a/16517
Comment: Fico feliz que funcionou, pode criar uma nova resposta do jeito que fez, pelo jeito ficou diferente dessa resposta :)
Comment: Cara só mais uma coisa, como eu poderia fazer com que a minha taxa ficasse mais precisa, porque a taxa não vai ser fixa, será alterada com o `input` do usuário.
Answer: Solução
https://money.stackexchange.com/a/16517
É feito o valor futuro do pagamento, e depois o valor futuro passado(linha anterior, ou iterador anterior).
Valor futuro do pagamento

$pmt: Pagamento

$i: Juros

$n: Número de períodos

Valor futuro da última linha(valor futuro passado, linha anterior).

$vl: Valor futuro

$i: Juros

$n: Número de períodos

Agora é feita a soma dessas duas fórmulas. Vocês podem ver no código o funcionamento.
function valorFuturo($vl, $i, $n, $pmt, $iterator)
{
  if($iterator > 0):
  $first  = $GLOBALS['ul_vf'] * (1+$i)**$n;
  $second = $GLOBALS['ul_pgto'] * ((1+$i)**$n-1)/$i;
  $vf     = $first + $second;

  $GLOBALS['ul_vf']   = $vf;
  $GLOBALS['ul_pgto'] = $pmt;
 else:
  $vf                 = $vl;
  $GLOBALS['ul_vf']   = $vf;
  $GLOBALS['ul_pgto'] = $pmt;
 endif;
 return $vf;
}

$vlr_imovel   = 144000;
$vlr_aluguel  = 400.00;
$vlr_entrada  = 43200.00;
$vlr_encargos = 500.00;
$mes = 360;

$taxa = (0.54/100);
$se_for_investir  = $vlr_encargos + $vlr_entrada;

for($i = 0; $i <= $mes; $i++):

  $juros_no_finan    = (($vlr_imovel - $vlr_entrada) - ((($vlr_imovel - $vlr_entrada)/$mes)*$i))*0.007;

  $amortizacao      = ($vlr_imovel - $vlr_entrada)/$mes;

  $vlr_total        = $amortizacao + $juros_no_finan;

  //VALOR FUTURO -------------------------
  // Como: FV = PV x ( 1 + i ) ^ n
  $n            = 1;
  $pgto         = $vlr_total - $vlr_aluguel;
  $vlr_presente = $vlr_entrada + $vlr_encargos;
  $tipo         = 0;
  $taxa2        = 0.54316901573592300/100;

  $vf           = valorFuturo($vlr_presente, $taxa2, $n, $pgto, $i);
  //VALOR FUTURO -------------------------

  $sac['G'][] = $se_for_investir;
  $sac['H'][] = $juros_no_finan;
  $sac['I'][] = $amortizacao;
  $sac['J'][] = $vlr_total;

  $sac['K']['pgto'][] = $pgto;
  $sac['K']['vf'][]   = $vf;

endfor;

Valores de fórmulas não correspondem


Connecting to external database in android

Question: I am trying to connect to my database on my localhost through my android application. I have created a php file and stored it in my wamp/www/myfolder, when I run it it works fine, so it must be a problem with my android class.
   public void getData(){
    String result ="";
    InputStream isr = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new        HttpPost("http://localhost/testdata/getAllCustomers.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    }catch(Exception e){
        Log.e("log_tag", "Error in http connection");
        resultView.setText("Couldnt connect to database");

I have gone over my code many times but I can't find the problem.
I have created two morw try catches in this method that convert the result and the other one parses the data but when I run it the first log appears so it doesn't connect to the database.
P.s I am using eclipse, to I need a plugin for json, I know eclipse IDE supports it.
Comment: I get a warning from System.err on HttpResponse response = httpclient.execute(httppost); but I don't understand why and also i get the log I created.
Comment: android.os.NetworkOnMainThreadException that my error but don't really know what it is
Comment: Thanks Keyser, I know it may be a duplicate but I am new to this site and I don't know how everything really works. Sorry for that.
Comment: No problem :p You gotta start somewhere.
Comment: I have found the solution, Because I am using an android version over 9 I had to use StrictMode in my onCreare method.

    if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
  }

Answer found from
http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception
Comment: Read the comments on that answer, then read my answer :p It's a dangerous workaround.
Answer: The loopback address in case of android when you are trying to connect from emulator is 10.0.2.2
i.e instead of localhost use 10.0.2.2
Comment: Thanks Santhosh for your answer but it didn't change anything.
Answer: NetworkOnMainThreadException means that you are attempting to perform a network operation on the main thread, which is forbidden. Simply do it from another thread. This is mainly done by creating an AsyncTask. Here's an example. And here's another one.
It's worth noting that NetworkOnMainThreadException is only thrown for applications targeting the Honeycomb SDK or higher, but the behaviour is always heavily discouraged.


probability of a positive random variable larger than a sequence tending to 0

Question: Let $X$ be a random variable on a probability space $(\Omega, \mathcal{F}, P)$ such that $X > 0$. The distribution of $X$ is not known. Let $\{ a_k \}_{k = 1}^\infty$ be a sequence such that $a_k \downarrow 0 $.
Intuitively $P[ X > a_k ] \rightarrow 1$ as $k \rightarrow \infty$. I am wondering if the following proof is correct, and/or if there is an easier/better way to do this?
Proof: Let $f_k(\omega) = I(X(\omega) > a_k)$, where $I(A)$ is the indicator function of set $A$.
Then clearly $0 \le f_k(\omega) \le f_{k + 1}(\omega)$. The limit of $f_k$ is $I(X(\omega) > 0)$. Then Lebesgue's monotone convergence theorem would give the desired result.
Answer: Yes, your reasoning is correct.
However, I would say that applying the monotone convergence theorem is kind of overkill. What you are really using is that the probability measure $\mathbb{P}$ is continuous from above (i.e. that $A_k \downarrow A$ implies $\mathbb{P}(A_k) \to \mathbb{P}(A)$.) Simply note that
$$A_k := \{X>a_k\} \downarrow \{X>0\}$$
and therefore, by the continuity of the measure,
$$1 = \mathbb{P}(X>0) = \lim_{k \to \infty} \mathbb{P}(X>a_k).$$
Comment: Thank you. I knew I was overthinking on the matter but was not able to find a better way.
Comment: @cly31107 You are welcome.


Showing that a limit is false, did I prove it?

Question: I want to show that $\lim_{x \to 2} x = 5$ is false.
Let $\epsilon > 0$. If this limit equivalence were true, we would need a $\delta$ such that $|x - 5| < \epsilon$ whenever $0 < |x-2| < \delta$.
$|x - 5| < \epsilon$ can be rewritten to $3-\epsilon < x - 2 < 3 + \epsilon$ or $|x-2| < \min(3 + \epsilon, \epsilon - 3) = \epsilon - 3$
However, we cannot set $\delta = \epsilon - 3$, since for $\epsilon \leq 3$, we have $\delta \leq 0$, which does not satisfy our original requirement that $0 < |x-2| < \delta$.
Comment: Yes, you proved it.
Comment: @ir7 I don't think it is
Comment: "We can not set $\delta =\epsilon -3$".  We need to show we can't set delta to *anything*.  Thing is, if $\epsilon <3$ we $|x-2|<\epsilon \implies $|x-5|>\epsilon $.  For any $\delta $ the $|x-2|< \min (\epsilon, \delta) $ won't give <$|x-5|<\epsilon $.
Comment: Nah. Epsilon-3 is delta's best chance to exist. Anything less than that is certainly negative, given that epsilon is already positive.
Comment: So, basically, take epsilon equal to 1, and delta is nowhere to find.
Comment: @fleablood I am assuming that the negation of $\forall \epsilon, \exists \delta, (0 < |x-2| < \delta) \implies (|x-5|<\epsilon)$ is $\exists \epsilon, \forall \delta, (0 < |x-2| < \delta) \land \lnot(|x-5|<\epsilon)$ but I don't know if this is even right, and if it is, how to show it
Comment: I think that is correct.  You can show it the way I did.  You are on the right track and have done all the work.  I just don't think you have explained the conclusion as clearly as it could be.
Comment: @fleablood I don't know how to show that for all delta we fail to satisfy the epsilon condition. The righthand inequality of $0 < |x-2| < \delta$ can be rearranged to $|x-5| < \min(\delta - 3, \delta + 3) = \delta-3$ but I don't know if this is on the right track.
Comment: Example.  If |x-2|<1 then |x-5|>2.  For any $d>0$ then then for |x-2|2.  So for any e<2 we can't do it.  Because all |x-2|2? Based on my inequality math above if |x-2|<1 then |x-5| < -2
Answer: By contradiction suppose that
$$\lim_{x \to 2} x = 5$$
then by definition of limit we have that $\forall \epsilon>0$ $\exists\delta>0$ such that $\forall x$
$$0<|x-2|<\delta \implies |x-5|<\epsilon$$
but for $ \epsilon=1$
$$|x-5|<1\iff 4<x<6$$
and for $\delta<1$
$$|x-2|<1\iff 1<x<3$$
then
$$\lim_{x \to 2} x \neq 5$$
Note that from the logical point of view since the definition is
$$\left(\lim_{x\rightarrow a} f(x) = L\right) \iff \Big(\forall \varepsilon >0\, \exists \delta > 0: \big(0<\vert x-a\vert <\delta \implies \vert f(x)-L\vert <\varepsilon\big)\Big)$$
the negation is
$$\left(\lim_{x\rightarrow a} f(x) \neq L\right) \iff \Big(\exists \varepsilon >0\, \forall \delta > 0: \big(0<\vert x-a\vert <\delta \not\Rightarrow \vert f(x)-L\vert <\varepsilon\big)\Big).$$
Comment: Can you please show how you are actually getting to these results? When numbers are pulled out of nowhere I don't understand how they satisfy everything. I believe the negation of $\forall \epsilon, \exists \delta, (0 < |x-2| < \delta) \implies (|x-5|<\epsilon)$ is $\exists \epsilon, \forall \delta, (0 < |x-2| < \delta) \land \lnot(|x-5|<\epsilon)$
Comment: How do I show that when $0 < |x-2| < \delta$ is true for all $\delta$, we can find an $\epsilon$ to make  $|x-5| < \epsilon$ false?
Comment: The first step is clear? for $\epsilon<3$ we have $|x-2|<3-\epsilon$. Now if we set $\epsilon=1$  we have $|x-2|<2$ that is $00$ but the condition for the limit is in the whole interval $0<|x-a|<\delta$.
Comment: "If this limit does not equal L, then for all delta > 0 there exists an epsilon > 0 such that 0 < |x-a| < delta for all x in that range does not imply |f(x)-L| < epsilon" is it not?
Comment: @user536260: if the limit equation is true then for every $\epsilon>0$ there is a $\delta>0$ which works nicely and if the limit equation is false then *obviously* it means that there is some $\epsilon>0$ for which no $\delta >0$ works nicely. The obvious part in last sentence is not a result of study of logical quantifiers but plain common sense. Convince yourself that it is obvious.
Comment: @ParamanandSingh Right, but I can't seem to find the correct conditions for epsilon for that to be the case. 0 < |x-2| < delta can be rearranged to x!=2 and |x-5| < delta - 3. If |x-5| < delta - 3 implied |x-5| < epsilon then delta - 3 <= epsilon would be true. But since we're looking for the negation, this is no longer implied when epsilon < delta - 3... but then this doesn't make any sense if delta is <= 3
Comment: @user536260: also algebraic manipulation of inequalities does not help too much here. One has to see how he inequalities related to $\delta$ and $\epsilon$ come in conflict with each other as we choose some small $\epsilon $. Try to analyze $2-\delta<x<2+\delta $ and $5-\epsilon <x<5+\epsilon $. Cont'd..
Comment: @user536260: these inequalities come in conflict if $2+\delta<5-\epsilon$ ie $\epsilon <3-\delta$. Just choose $\epsilon<3$ like $\epsilon=2.99999$ and you will have a conflict as soon as $\delta <3-\epsilon=0.00001$.
Comment: @user536260 : in general we choose simpler value like $\epsilon=1$ or $2$ rather than $2.99999$ but the logic to choose the $\epsilon$ is the one in my previous comment.
Comment: I think I have it down to epsilon < 3 + delta proving the limit false, but I am not 100% yet
Comment: @user536260 : you should get $\epsilon <3-\delta$ rather than $3+\delta$.
Comment: I'll post my work in another answer
Answer: $0 < |x-2| < \delta$ can be rearranged to $x \neq 2$ and $-3-\delta < x-5 < \delta - 3$.
$|x-5| < \epsilon$ can be rearranged to $-\epsilon < x-5 < \epsilon$
If the former condition implied the latter, we'd have $-\epsilon \leq -3-\delta$ and $\delta - 3 \leq \epsilon$.
This simplifies to $\epsilon \geq 3 + \delta$.
Since we are after the negation of this, we have:
$\epsilon < 3 + \delta$
Since $\delta > 0$, this suggests any $\epsilon \leq 3$ should prove the limit false regardless of $\delta$, i.e. you won't be able to find a $\delta$ that works. Unless I made a mistake with this somewhere.
Comment: That seems correct, indeed just when $\epsilon = 3$ we can find a $\delta>0$ such that $x=2-\delta$ doesn't fulfil the condition. The idea is to fix $\epsilon$ sufficiently small in order to have the preimage of the interval around the limit not containing the limit point (x=2 in this case).
Comment: Well your inequalities $\delta+3\leq \epsilon, \delta-3\leq \epsilon $ can be combined into just $\delta+3\leq \epsilon$.
Comment: This implies that as long $\epsilon> 3$ you will be able to get a suitable $\delta$, but once you have $\epsilon \leq 3$ you will start having problems choosing $\delta $. This works out fine.
Comment: @ParamanandSingh You're right; simplified those two inequalities into one piece.
Answer: Let $\epsilon_0:=1$. Given any $\delta>0$ put
$x:=2-{\delta\over2}$. Then $|x-2|<\delta$, but  $|x-5|\geq1$. It follows that no $\delta>0$ whatsoever suffices for the given $\epsilon_0$.


Why $\lim_{x\to\infty}\int_2^x \frac{\sin^2{t}}{t}\, dt\geq \lim_{x\to\infty}\int_{2\pi}^x \frac{\sin^2{t}}{t}\, dt$

Question: Why can I say that $\lim_{x\to\infty}\int_2^x \frac{\sin^2{t}}{t}\, dt\geq \lim_{x\to\infty}\int_{2\pi}^x \frac{\sin^2{t}}{t}\, dt$?
I have thought that it is due by the fact that passing from $2$ to $2\pi$ I am restricting the interval of integration but I am not sure.
Or it is due simply by the fact that $\int_2^{2\pi}\frac{\sin^2{t}}{t}\, dt\geq 0$ and it is the missing term in the right hand side? Can you help me?
Answer: Notice that $\sin^2(t)\ge 0$ due to it being a squared function. $\frac1t>0$ is also due to our domain. This means that our integrand over our domain is always greater than or equal to zero. Now we can just split our integral up:
$$\int_2^xf(t)dt=\underbrace{\int_2^{2\pi}f(t)dt}_{\ge 0}+\int_{2\pi}^xf(t)dt$$
Now as we can see this will then create our inequality since LHS and RHS are just your integrals in question
Answer: Since $\sin^2t/t \ge 0$ for all $t > 0$, you have $$\int_2^x \frac{\sin^2t}{t}dt \ge \int_{2\pi}^x \frac{\sin^2t}{t}dt$$
The inequality does not change while limiting both sides.
The above inequality is easy to observe since
$$\int_2^x \text{positive} ~dt = \underbrace{\int_2^{2\pi} \text{positive} ~dt}_{\ge 0} + \int_{2\pi}^x \text{positive} ~dt \ge \int_{2\pi}^x \text{positive} ~dt$$
Comment: Ok thank you very much!!
Comment: I can accept you answer by $5$ min as a message tells me! I will do it!
Comment: @cely No hurry, that's fine. Glad that it helps.


What do I label the legend in this regression plot

Question: What do I label the predicted values, or fitted model in this chart? (In the legend)
Fitted model? Fit model? Predicted? Regression? What are my options?
The black line and points are the actual results and the gold is the fitted values of the non linear regression.
Thanks,
Answer: It makes more sense if you label it by the name of the method which produces the result. For example, "Linear Regression".


Mostrar emoticons com botão independente do teclado

Question: Estou desenvolvendo uma aplicação no qual criei um botão que gostaria que fizesse a mesma função de mostrar os emoticons do teclado. Essa imagem:

<code> btnMostrarEmoticons.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //mostra emoticons
        }
    });
</code>
Existe algum método que mostra os emoticons com botão independente do teclado?
Answer: Me parece que não.
Mas você pode tentar uma biblioteca de emojis que se assemelha muito com a entrada de emoji do teclado para atingir esse objetivo.


Xcode7 Beta IOS9 Cannot Create Notifications

Question: I semi-recently updated to Xcode 7 and IOS9 but I am encountering an issue. When I try to follow tutorials, I am told to add this line of code:
let notificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound

However, this causes an error that says "Binary operator cannot be applied to two UIUserNotificationType operands." If anyone knows a work-around to this I would very much appreciate some help.
Answer: With Swift 2, Apple has added OptionSetType's.  Use an array of options values instead of boolean operations like OR.
let notificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]

EDIT:
I think a better way to express this would be the following.
let notificationType: UIUserNotificationType = [.Alert, .Badge, .Sound]

Comment: Now I am getting an another issue. "Cannot call value of non function type '[UILocalNotification]'" for :UIApplication.sharedApplication().scheduledLocalNotifications(UINotification)


Can this code be improved to avoid repetition?

Question: Code below is a switch statement written in php. The line $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); repeats in every case. This violates the DRY (don't repeat yourself) principle. Is there some way to improve the code to adhere to DRY?
 switch ($term)
            {
                case "1":
                    $term = 'XXX_1_year';
                    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);
                    break;
                case "2":
                    $term = 'XXX_2_year';
                    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);
                    break;
                case "5":
                    $term = 'XXX_5_year';
                    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);
                    break;
                default:
                    print ("Invalid  parameter.");
            }

Answer: obvious improvement:
switch ($term) {
    case "1":
    case "2":
    case "5":
        $term = 'XXX_'.$term'_year';
        $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);
        break;
    default:
        print ("Invalid parameter.");
}

or
if ( ($term == '1') || ($term == '2') || ($term == '5') ) {
    $term = 'XXX_'.$term'_year';
    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);
} else {
    print ("Invalid parameter.");
}

or
if (in_array($term, array('1', '2', '5'))) {
    $term = 'XXX_'.$term'_year';
    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);
} else {
    print ("Invalid parameter.");
}

Comment: Thanks for the numerous answers which all work. I prefer the obvious one most. It is easiest to understand.
Answer: You can do something like this :
 switch ($term)
            {
                case "1":
                case "2":
                case "5":
                    $term = 'XXX_'.$term.'_year';
                    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);
                    break;
                default:
                    print ("Invalid  parameter.");
            }


Downvotes in cryptocurrency posts

Question: I've noticed that a few posts related to cryptocurrencies have constantly all the answers downvoted:
This one from this week had a downvote for both answers, without comments (i upvoted the other user)
This one from May had a new user receiving a down vote without any comment
This one from August received 1 down vote and 1 upvote.
Is it just a coincidence, or is the community intentionally ignoring cryptocurrencies?
I admit I am directly involved in many of these posts, and what frustrates me on this is the lack of feedback, not the downvote itself. Attitudes like this are likely to prevent growth in the community - the user in one of the posts above hasn't posted ever since.
Answer: Questions about economic aspects of cryptocurrencies should be welcome in principle.  As EnergyNumbers says it's a topic that can attract bad questions and bad answers, but there's no reason why it shouldn't attract good ones too.
Although the site doesn't require downvotes to be explained, comments with reasons for downvotes can sometimes be helpful, especially where posts have both good and bad features, eg to encourage editing to improve posts, and to draw readers' attention to errors.
Comment: Thanks a lot for the straight-to-the-point answers. I think at the end the three answers we received here represent different perspectives in the community, and I understand all points of view - which explains the reception of cryptocurrency questions clearly.
Answer: Cryptocurrencies routinely attract bad questions and bad answers. Unsurprisingly, such ponzi schemes routinely attract people who are economically illiterate.
You've given some good examples. These should be downvoted - that's just as it should be.
Furthermore, downvotes are not required to be accompanied by comments. The tooltip over the down arrow gives the reasons for downvotes.
And finally, asking for comments from downvoters, in comments, is noise and clutter. Please stop doing it.
Answer: Personally I find that two out of these three questions are unclear, so I am definitely ignoring them. I don't think there is any trend.
I was the downvote on your answer on the third question. I have just read the edit made after my vote and I removed my vote.

Downvotes in cryptocurrency posts


What are the different ways of writing an IIFE? What are their use cases?

Question: I have started reading this book. Chapter 2 says that there are different ways to write an IIFE:
!function (){}()
~function (){}()
+function (){}()
-function (){}()
new function (){}
1,function (){}()
1&&function (){}()
var i=function (){}()

The author says:

Each manifestation has its own unique qualities and advantages—some
  with fewer bytes, some safer for concatenation, each valid and each
  executable.

I'm a newbie to JS. I know what an IIFE is, but what do these IIFE forms do exactly?
Comment: And `void function() {}()`
Comment: @batman `void `: "evaluate __ and return `undefined`" - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
Comment: They missed my favourite, `(function() {})()`
Comment: virtually the same thing @JamesThorpe and it's twin without the dogs bollock, `(function() {}())`
Comment: These functions do absolutely nothing:-), see this blog for more information: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Comment: @joews: Oh, wow, I've never seen it used, but you're 100% right of course.
Comment: @joews: `void` in js?
Answer: Why do this?
Before we get to the list, let's start with "Why do this at all?"
The answer is: To keep any variables and function declarations within the function private. Commonly this is to avoid globals (avoiding globals is a Good IdeaTM). E.g.:
+function() {
    function foo() {
        /* ... */
    }

    foo();

    var answer = 42;
}();

Thanks to the IIFE (called a scoping function in this context), foo and answer are not globals. They're private to the code within the function, unless they get exported somehow.
You might do this even if not at global scope, just to avoid polluting whatever scope you're in.
IIFEs in general have other uses, but the style you've quoted is typically used for scoping.
The examples
The author is dramatically overstating the case that "each has its own unique qualities and advantages".
Unless you're using the return value, these are all exactly the same:
!function (){}()
~function (){}()
+function (){}()
-function (){}()
1,function (){}()
1&&function (){}()

The code within them is run, scoped within the function.
We can add these to that list as well:
(function(){}())
(function(){})()
0||function (){}()
1^function(){}() // any binary math operator in place of ^ also works

Of course, the 1 in all of the above is not special. Could be any number (or just about anything else) for most of them, but the one using && wouldn't work with 0, "", null, undefined, NaN, or false (the function wouldn't get run). Similarly, the one with 0||... works as long as the value starting it is falsey.
In this one:
var i=function (){}()

...the only difference is that it declares a variable, i, which stores the return value. That can, of course, be a big difference. Consider this more obvious version of it:
var MyPseudoNamespace = function() {
    // ...

    return { /* nifty "namespace" stuff here */ };
})();

Finally:
new function (){}

That creates a new object and then calls the function with this set to the new object. If you don't use this within the function, it's utterly pointless. If you do, well, whether it's useful depends on what you do with this.

Note: If there's any possibility of code you don't control coming immediately before your scoping function (when you're combining and minifying files, for instance), it's best to start all of these off with a ;, e.g.:
;!function (){}()
;~function (){}()
;+function (){}()
;-function (){}()
;1,function (){}()
;1&&function (){}()
;(function(){}())
;(function(){})()
;0||function (){}()
;1^function(){}() // any binary math operator in place of ^ also works

Several of them don't technically need one, but most of them do. The side-effects of not having them can be subtle, or catastrophic. Consider:
Code before your code:
obj.prop = function() {
    // Do something big and awful
}

Then your code:
(function(){}())

Automatic Semicolon Insertion will not kick in! The result? the obj.prop function gets called, with our IIFE passed into it as an argument. This will make it more obvious:
obj.prop = function() {
    // Do something big and awful
}(function(){}())

See how those () are now invoking the function?
Similarly:
obj.criticalValue = 42

then
+function(){}()

Suddenly, criticalValue is messed up. Why? Because:
obj.criticalValue = 42+function(){}()

Doh!
Having multiple ; in a row is harmless, so if you start off with one, you're less likely to run into trouble.
Comment: @joews: Thanks to your excellent note, I've added an entire thing about that to the end.
Comment: The `(function() {})` form can lead to unexpected invocation if preceded by a non-II function expression with no semicolon: `var f = function(x) { console.log ("called with x: " + x) } /* new line, no semi-colon */
(function() { console.log("second") }())`
Comment: Sounds like a bizarre edge case but I've seen it happen in the wild. Moral: always use semicolons if you favour parethesis-style IIFEs (or just "always use semicolons").
Comment: @joews: Many of these can lead to unexpected outcomes with improperly terminated code in front of them, not just the `(function...)` ones. A leading semicolon is a good defense, that's what I always do with minifying, for example.
Comment: Ah, of course! I hadn't given the operator prefixes much thought before now.
Answer: It is an optimization to concatenate multiple files into one. The idea there is, if the last line of the previous file does not end with a newline, then the first line in this file starts in the middle of a line.
Adding things like ; before the function permits it to still work correctly.