How to prove independence in the following case?

Question: Let $f$ be a (possibly randomized) function with finite domain $D$ and finite range $R$, such that for any two $x$ and $x'$ in the domain, $f(x)$ and $f(x')$ are identically distributed; i.e.:
$$\forall x,x'\in D, \forall y\in R \quad \Pr[f(x)=y] = \Pr[f(x')=y] \enspace. \qquad (\dagger)$$
I want to prove that the output of $f$ is independent of any input distribution. That is, for any discrete input distribution $X$ with support $D$, we have:
$$\forall x\in D, \forall y\in R \quad \Pr[f(x)=y \mid X=x]=\Pr[f(x)=y] \enspace. \qquad (\ddagger)$$

Here's two examples that satisfy $(\dagger)$, and therefore satisfy $(\ddagger)$:
Example 1. $f(x)$ is a constant function.
Example 2. Domain $D$ is the set of $n$-bit strings, and $f(x)=x \oplus r$. That is, $f$ picks a random $n$-bit string (internally), and XORs it to its input.
Comment: Isn't this result immediate, given that the output of $f$ is a weighted average (i.e., a *mixture*) of identical distributions?
Comment: @whuber: I think it must be quite intuitive, but I was unable to prove it. Could you please expand your comment into an answer? Specifically, the term *mixture* was new to me. I looked it up in Wikipedia and understood the concept, but it's not immediate for me how $f$ is a mixture of identical distributions, and how this proves the theorem.
Answer: Definitions and clarification
Let $f$ be a randomized function from $D$ to $R$.  In the context of the question this implies that for each $x\in D$, $f$ assigns a probability $f(x,y)$ to each $y\in R$. (Actually, it does not matter that $f(x,y)$ is a probability: it merely has to be any element of a real vector space, such as a real number or tuple of real numbers.  Probabilities are real numbers.)
Suppose $p$ is a probability distribution over $D$ (entailing, in particular, that $\sum_{x\in D}p(x)=1$; it turns out this is all we need to know about $p$).  Then--this is how I interpret the question--$p$ acts on $f$ by mixing it to create a probability distribution $f^{(p)}$ on $R$ where, for any $y\in R$,
$$f^{(p)}(y) = \sum_{x\in D} p(x) f(x,y).$$
(When all the $f(x,*)$ are probability distributions and $p$ is itself a probability distribution, then in fact $f^{(p)}$ is itself a probability distribution: this is straightforward to show.  But that doesn't matter for this demonstration.)
Solution
Suppose $f(x,y)$ is independent of $x$ (which is the assumption of the question); that is, we may write $f(x,y) = g(y)$ for some function $g$.  Then
$$f^{(p)}(y)  = \sum_{x\in D} p(x) f(x,y) = \sum_{x\in D} p(x) g(y) =  g(y)\sum_{x\in D}p(x) = g(y)1 = g(y),$$
QED.
Comment: Nice! Just one point: consider my example 2, which with your notation is defined as $f(x,y)=x\oplus y$. We cannot find any function $g$ such that $f(x,y)=g(y)$.
Comment: Sure you can, but first you have to be consistent about how you think of $f$. $f(x,y)$ is a *number*, not a string: it gives the probability $\Pr(x\oplus r=y)$. This is a constant value of $f(x,y) = 2^{-n} = g(y)$ for each $y\in R$. For a concrete example, let $D=R=\{00,01,10,11\}$ (the case $n=2$). Consider $x=10$: with equal probability $r=00, 01, 10,$ and $11,$ whence with equal probability $x\oplus r$ is equal to $10, 11, 00,$ and $01$, respectively. *Ergo,* $f(10,10)=f(10,11)=f(10,00)=f(10,01)=1/4$. The same result holds for all other $x$.
Answer: I will compact notation a bit. We have a discrete support, $D=\{x_1,...,x_n\}$. We define the events $f_i:\{f(x_i)=y\}, \; f_k:\{f(x_k)=y\},\; i,k =1,...,n$
Then, for any given $y$, your premise can be written as  $$\Pr(f_i) = \Pr(f_k)\; \forall i,k$$
and you want to show that
$$\Pr(f_i|x_i) = \Pr(f_i)\; \forall i$$
By Bayes theorem
$$\Pr(f_i) = \sum_i^n\Pr(f_i|x_i)\Pr(x_i) $$ $$= \Pr(f_i|x_1)\Pr(x_1)+...+\Pr(f_i|x_i)\Pr(x_i)+...+\Pr(f_i|x_n)\Pr(x_n)$$
But $\Pr(f_i|x_k) = 0 \;\;\forall\, k\neq i$. If the realized value of $X$ is $x_k\;, k\neq i$, the event ${f(x_i)=y}$ is impossible, because $f(x_i)$ is impossible - only $f(x_k)$ is possible  . So we are left with
$$\Pr(f_i) =  \Pr(f_i|x_i)\Pr(x_i)$$.
So what we wanted to prove is not correct. But it seemed fairly intuitive... There is another relation here that I believe represents this intuition. Use a prime to denote that all previous analysis is conducted for the probability that $f$ takes the value $y'$. Then we will arrive at
$$\Pr(f'_i) =  \Pr(f'_i|x_i)\Pr(x_i)$$
Combining the two results we obtain
$$\frac {\Pr(f_i)}{\Pr(f_i|x_i)} = \frac {\Pr(f'_i)}{\Pr(f'_i|x_i)} $$
$$\Rightarrow \frac {\Pr(f_i)}{\Pr(f'_i)} = \frac {\Pr(f_i|x_i)}{\Pr(f'_i|x_i)} $$
Moreover, since $\Pr(f_i)=\Pr(f_k)$ and $\Pr(f'_i)=\Pr(f'_k)$ we obtain
$$ \frac {\Pr(f_i)}{\Pr(f'_i)} = \frac {\Pr(f_i|x_i)}{\Pr(f'_i|x_i)} =\frac {\Pr(f_k|x_k)}{\Pr(f'_k|x_k)}=\frac {\Pr(f_k)}{\Pr(f'_k)}$$
The key here is that the realization of some $x_i$ may affect the distribution of $f(x)$ -but it will do it in a way that leaves relative probabilities unchanged.
Comment: Thanks a lot for the detailed answer. But I think the statement $\Pr(f_i|x_k) = 0 \;\;\forall\, k\neq i$ is not correct. For instance, if $f$ is the zero function, then $\Pr(f(x_i)=0|x_k)=1$.
Comment: I didn't treat the "f is a constant" case" -it is not interesting. The interest arises when the value of $f$ actually depends on $x$
Comment: Fair enough, but for me, $f(x)=x \oplus r$ is an "interesting" case (see Example 2 in question). Then, for any $y \in R$, we have $\Pr(f(x_i)=y|x_k)=\frac{1}{|R|} \ne 0$. So, I think it's rather hard (or even impossible) to find even trivial examples with $\Pr(f(x_i)=0|x_k)=1$.
Comment: My conceptual problem here, is that the realization of some $x_i$ makes the concurrent realization of any other $x_k$ impossible -and so it makes also impossible any event depending on these other $x_k$'s.
Comment: I understand $\Pr(f(x_i)=y|x_k)$ as $\Pr(f(x_i)=y|X=x_k)$, which means the probability that the outcome of (the possibly randomized function) $f(x_i)$ is $y$, given that the outcome of $X$ is $x_k$. It does not mean that the outcome of $X$ is simultaneously both $x_i$ and $x_k$.
Comment: Me too. But since $X=x_k$ and we condition on that, it means that $f$ takes as input the specific $x_k$, not any other $x$. in that case, isn't it true that $ \Pr(f(x_i\neq x_k) = y |X=x_k)$ is zero?


$C^\infty$ functions with all derivatives in $L^p$

Question: Let $1\le p<\infty$ and $f\in C^{\infty}(\mathbb{R})$ be such that its all derivatives $f^{(n)} \in L^p(\mathbb{R})$ for every $n\in \mathbb{N} \cup \{0\}$.
Is it true that $f\in L^\infty(\mathbb{R})$?
If it is true, do we have a generalization in $\mathbb{R}^n$?
My partial answer for $p=1$:
For $p=1$ and  $t\in \mathbb{R}$, we have
$$
|g(t)|=
|\int_{0}^{t} g'(x) \ dx+g(0)|
\le
\int_{0}^{t}
|g'(x)| \ dx
+|g(0)|
\le
\|g'\|_{L^1}
+|g(0)|.
$$
Thus, $g\in L^\infty(\mathbb{R})$ with
$\|g\|_{L^\infty} \le \|g'\|_{L^1}+|g(0)|$.
Thanks for help and hint.
Answer: That $f'\in L^1(\mathbb R)$ implies already that $f \in L^\infty$. To see this, first we observe that
$$\lim_{x\to\infty} f(x) = 0.$$
Indeed like you did,
$$f(x) - f(y) = \int_x^y f'(s) ds\Rightarrow |f(x) - f(y)| \le \int_x^y |f'(s)|ds \to 0$$
as $x, y\to \infty$ (this is where we use $f' \in L^1$). Thus $\lim_{x\to \infty} f(x)$ exists and must be zero since $f\in L^1$. Then
$$f(x) = \int_\infty^x f'(s)ds\Rightarrow |f(x)| \le \|f'\|_{L^1}.$$
When $p>1$, we consider $g = f^p$. Then $g' = pf^{p-1} f'$ and so by Holder's inequality
$$\begin{split} \int |g'| &= p \int |f^{p-1} f'|  \\
& \le p \left(\int |f^{p-1}|^{\frac{p}{p-1}}\right)^{1-1/p} \left(\int |f'|^p\right)^{1/p}\\
&= p \| f\|_{L^p}^{p-1} \| f'\|_{L^p}
\end{split}$$
Thus $g$ satisfies $g,g' \in L^1$ and so $g\in L^\infty$ by the first argument. Hence $f\in L^\infty$.
The generalization in $\mathbb R^n$ is the general Sobolev embedding, which shows that your $f$ has pointwise bounds on all derivatives
$$ \sup_{x\in \mathbb R^n} |D_I f(x)| \le C(I,f) <\infty.$$
Comment: Shouldn't there be a minus sign in front of that last integral?
Comment: @JohnMa: Maybe power ``1/p" is missing. I am sorry if it is too elementary, How do we conclude $f\in L^\infty$ from $f$ is Holder continuous?
Comment: The last bit seems a little fuzzy to me. In fact $|f|$ is differentiable everywhere except for a countable set. With your approach I would think absolute continuity would play a role. I took a slightly different route in my answer.
Comment: There are two versions of sobolev embedding, one for $kpn$. If you use the latter case, since $f^{(k)} \in L^p$ for all $k$, choose $kp >n$ and so it embeds into Holder spaces @testes
Comment: @tomasz : Thanks, edited.
Comment: @testes Thanks for pointing that out. The argument was not quite correct. Please see the edit.
Comment: @JohnMa: I see the reason now. Is it alright if we assume that $f\ge 0$? Because you define $g=f^p$.
Comment: Good point again (since you tag "sobolev space" I should have include that in the answer). The point is that $|f|$ is also almost everywhere differentiable and $|f|' = \pm f'$ almost everywhere. Thus we can consider $|f|$ instead of $f$ @testes
Comment: @JohnMa: After reading Sobolev embedding, I think that the function will be in L^{p*} where $p<p*<\infty$. But I can not find the argument $f\in L^\infty$.
Answer: If $f\in C^1$ and $f' \in L^1,$ then
$$|f(x)-f(0)| = |\int_0^x f'| \le \|f'\|_1,$$
giving $\|f\|_\infty \le |f(0)| + \|f'\|_1.$
Suppose $p>1.$ If $f\in C^1,$ then $|f|^p$ is the composition of $|x|^p \in C^1$ with $f;$ hence $|f|^p\in C^1.$ Check that the formula $(|f|^p)'(x) = p|f|^{p-1}f'(x)\text { sgn }(f(x))$ holds. If we assume now that $f, f'\in L^p,$ then we know $|f|^{p-1}f' \in L^1$ as in John Ma's answer. By the first paragraph, we have $|f|^p,$ and hence $f,$ in $L^\infty.$
Comment: Thank you for adding your answer. Do you know whether we have a generalization in $R^n$? After reading about Sobolev embedding, the case $p>n$ and bounded domain is true. Do we still have $f\in L^\infty(\mathbb{R}^n)$?


ubuntu 10.04 automated LAMP configuration script with virtual hosts

Question: I am looking for a set of bash scripts which can help me to automate the procedure of getting LAMP server up and running.
Typically what I am looking for is boot a VPS (say linode) with Ubuntu 10.04, upload the script with ssh and run it. The end product should be a properly configured LAMP server with virtual hosts.
Can somebody point me to a trusted source to obtain such a script?
Regards,
Pritam.
Comment: what exactly do you want this script to do?
Answer: You could try Ansible, which is a far simpler implementation of configuration management than Chef or Puppet, it doesn't require anything except SSH access to the server.

Ansible is a radically simple model-driven configuration management, deployment, and command execution framework. Other tools in this space have been too complicated for too long, require too much bootstrapping, and have too much learning curve. Ansible is dead simple and painless to extend.

I have created a playbook for setting up a LAMP server on Ubuntu 12.04 that you can use as a base for your own. Take a look, it's all YAML and Python syntax, very straightforward.
Answer: Have a look at puppet.  Its probably the most widely used solution for what you are trying to do.  Its probably going to be much more complex to get started than what you are looking for, but unfortunately, since so many hosting deployments are unique, I think you are going to have trouble finding a magic bullet to your solution.
If you don't like the looks of puppet, there are other similar solutions, such as cfengine or chef.
Comment: Thanks for replying. Checked them out. All of them seem to full blown server management solutions. All I need is handy bash/perl script which I can modify on my own. I searched the net a lot, but Google has let me down on this one.


fast staccato on same note for piano

Question: A few years back I found this dual piano arrangement for Imperial March.

!
I noticed that in the original composition there are a lot of staccato triplets on the same note.
This arrange replicates that flawlessly. When I was practicing at home, I noticed that it was impossible to do because the key simply won't bounce back up quick enough(cuz same note).
Is there a technique to this kind of thing?
Comment: Is your piano an upright piano or a grand piano?
Comment: I have an upright
Comment: If you listen carefully, the triplets are far from "flawless" - but they are good enough to be convincing.
Comment: Related question: [Proper repeated note fingering on piano?](https://music.stackexchange.com/questions/103941/proper-repeated-note-fingering-on-piano)
Answer: The key recovery time on grand pianos is much less than on uprights, due to a different mechanism, so it's more difficult to execute this on most uprights.Thumb,index and middle are the usual way, with the hand suspended over the key.
Answer: The "classical" technique for repeated notes, in twos or threes, is to "change fingers", e.g. fingering a fast triplet 1,2,3.    This may be what Tim meant.
Answer: There is a link at the bottom on this page http://www.piano.christophersmit.com/repetitionMech.html which has an animation of how the repetition mechanism works in a grand piano action. I would expect a piano tech did a careful job of regulating those pianos before that performance!
The grand piano repetition action works well, and is consistent between the different notes on the keyboard, because it is basically "powered" by gravity acting on the weight of the moving parts. That isn't possible with an upright action, where almost everything in the action, except the keys, is rotated through 90 degrees.
The best you can do on an upright is to experiment to find out exactly where the repetition action "kicks in" when depressing the keys part way down, and then work on playing with enough force to operate the repetition action without pressing the keys right down to the key bed (except for the last note of the triplet, of course). There will probably be a tradeoff between "fast" and "loud" repetition (i.e. louder means slower repetition).
In an old upright piano, thoroughly cleaning the action and/or replacing some of the felt and leather parts, and carefully readjusting the repetition action, may help, but that is a long job and there is no way to know exactly how much improvement you would get before actually doing it. A botched attempt at regulating the repetition may make things worse, not better, if you aim for something that is too "good" to be realistically achievable.

fast staccato on same note for piano


bash command piping (and php): How to check from command line each php file in all subdirs?

Question: I'm trying to loop recursively through my project dirs and subdirs and check syntax from php command line.
I'm able to list all php files using
find ./ -name '*.php'

and I'm able to che check a single php php as
php -l ./full/path/to/file/filename.php

But I'm not ble to make them working together
 find ./ -name '*.php' | php -l

This really doesn't do any check. I tried forcing a syntax error in a file but this tell me every time:
No syntax errors detected in -

How to correctly pipe each file name for php syntax checking?
Feel free to adjust the title and/or the question, my english is not so good.
EDIT 1: I googled on stackoverflow and tried these, but without success
$ find ./ -name '*.php' | xargs -0 "php -l"
xargs: argument line too long

EDIT 2: another try
$ find ./ -name '*.php' -exec php -l
find: missing argument to `-exec'

Comment: It's the difference between `echo filename | php -l` and `php -l filename`.  Because `php -l` does not use standard input to read the names of the files you want to process, the former doesn't work.
Answer: You can run php command with each file name with,
find ./ -name '*.php' -exec php -l {} \;

Comment: It's all in the man page.  Have you tried reading `man find`?  Briefly, `-exec` is the option for running a command on the files that `find` returns, and is needed before your `php` command.  `{}` is the placeholder for the found file name, and the escaped semicolon `\;` terminates the command.  Your command pipes the file names into the **standard input** of php, which is different from them being specified on the command line.
Comment: @rojomoke Thanks for the additions. Regarding `\;`, it terminates the command but it also runs what comes after `-exec` with each finding of `find`. When you replace it with `\+` it will make a list of the findings and pass it to the command, like `php -l file1.php file2.php ...`.
Comment: @realtebo Your command was probably not working because `php` expects a file name after `-l` parameter, not input from `STDIN`. Regarding `xargs`, since `php -l` expects one file name at a time you should do `find ./ -name '*.php' | xargs -n 1 php -l`.
Comment: This works, great! Can you expand the answer explaining why my command was not working? And, what does it mean the syntax `{} |;`  ?
Answer: You could do it in a shell loop:
for file in $(find ./ -name '*.php')
do
  php -l "${file}"
done

Comment: This works, great! Can you expand the answer explaining why my command was not working?
Comment: It should be semicolon separated like `for file in $(find ./ -name '*.php'); do   php -l "${file}"; done`. See http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html.


Selenium Issues With Waiting Until Multiple Dropdowns Populate

Question: I am having a great amount of trouble working with python selenium on a multi-dropdown url retrieval algorithm. In short, I'd like my program to go the the link (https://www.xpel.com/clearbra-installers/) and iterate through each of the three location dropdowns to retrieve every possible final link (i.e. https://www.xpel.com/clearbra-installers/united-states/california/bakersfield).
I have tried several different methods of doing this, including clicking on the table options, iterating through the dropdowns, and even collecting dataframes of each dropdown option, then creating urls and going to those links. However I try to approach the problem, there I always hit a snag related to wait times and "stale element not found" errors.
Here is the html I'm trying to scrape:
<select class="dealer-locator-select" id="dealer-locator-country-select" name="dealer-locator-country-select" data-action="country-select" data-filter="">
<option value=""> Region, Country or Area </option>
<option value="albania"> Albania </option>
<option value="algeria"> Algeria </option>
<option value="argentina"> Argentina </option>
<option value="armenia"> Armenia </option>
<option value="australia"> Australia </option>
<option value="austria"> Austria </option>
<option value="bahrain"> Bahrain </option>
<option value="belgium"> Belgium </option>
<option value="bosnia-and-herzegovina"> Bosnia and Herzegovina </option>
...
<option value="vietnam"> Vietnam </option>
</select>

Here is some code I've tried for retrieving countries:
# set wait
delay = 10 # seconds
wait = WebDriverWait(driver, delay)

# iterate through country options
for i in range(2,96):
    wait.until(EC.presence_of_element_located((By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]")))
    country_name = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]").text.lower().replace(' ', '-')
    country = Select(driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']")).select_by_value(country_name)

print("done")

The code seems to work find until the selection; for instance, if I just retrieve the country name then print it, everything works perfectly. I've also tried using try/except/finally, which I haven't had luck with either:
# set wait
delay = 10 # seconds
wait = WebDriverWait(driver, delay)

# iterate through each country option
for i in range(2,96):
    wait.until(EC.presence_of_element_located((By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]")))
    country_name = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]").text.lower().replace(' ', '-')
    try:
        country = Select(driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']"))
    except:
        sleep(5)
        country = Select(driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']"))
    finally:
        country.select_by_value(country_name)

print("done")

Answer: The idea in the link you shared is that a new page is being rendered based on every dropdown choice. For example, selecting Algeria from the first dropdown forces the browser to open https://www.xpel.com/clearbra-installers/algeria. If the user then selects blida state then a new page is rendered https://www.xpel.com/clearbra-installers/algeria/blida and so on.
So you have to reselect all dropdowns again with any action you are doing.
The solution in my point of view to add a delay (5 seconds as an example) after each country.select_by_value statement then reselect the dropdowns again because the page content has been changed.
Also it might be a good idea to add a delay at the end of your loop just to make sure the dynamic content is loaded.
Example:
# set wait
delay = 10 # seconds
wait = WebDriverWait(driver, delay)

# iterate through country options
for i in range(2,96):
    wait.until(EC.presence_of_element_located((By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]")))
    country_name = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]").text.lower().replace(' ', '-')
    country_element = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']")
    country = Select(country_element)
    country.select_by_value(country_name)
    wait.until(EC.staleness_of(country_element))

print("done")

Answer: You are getting StaleElementReferenceException as far as dropdown is re-rendered after new options selection.
As far as you don't wait for re-rendering, your script on next iteration gets old reference that doesn't exist anymore and can't be reached.
To handle this case, should wait for old dropdown element to be stale after selection.
for i in range(2,96):
    wait.until(EC.presence_of_element_located((By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]")))
    country_name = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]").text.lower().replace(' ', '-')
    country_element = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']")
    country = Select(country_element)
    country.select_by_value(country_name)
    wait.until(EC.staleness_of(country_element))

Comment: Thank you so so much! This solution saved my life. Also I'm just curious, what does 'staleness' of an element entail? Does this just mean that the new page has loaded so 'country_element' is not accessible any more?
Comment: Some elements have custom render logic, so after some actions like input / selection it's content can be re-rendered. It's usually made to not to increase DOM elements amount on each action. For example, triggering first dropdown needs 2nd and 3rd dropdown content to be consistent. So, I guess, devs decided to re-render that components block after select action.


How to center cell contents of a LaTeX table whose columns have fixed widths?

Question: Consider the following piece of LaTeX code:
\begin{tabular}{p{1in}p{1in}}
A & B\\
C & D\\
\end{tabular}

How can I make the contents of each cell aligned in the center of the cell rather than the left?
Note that I want to make sure that the widths of my columns are fixed, so I cannot use the "c" position attribute instead of "p{.1in}" to center my cell contents.
Comment: Similar question: [how to fix the width of the columns in the latex table? - TeX - LaTeX Stack Exchange](https://tex.stackexchange.com/questions/51009/how-to-fix-the-width-of-the-columns-in-the-latex-table)
Answer: \usepackage{array} in the preamble
then this:
\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"
Comment: use raggedleft instead of centering
Comment: Why such statement not make text in second column aligned to top `\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}p{1in} |}`? The same is for `b`. All cells are vertically aligned like first statement (here `m{1in}`) sets.
Comment: any reason why this would not be working for me in Overleaf? wondering if there's been any updates since this was answered back in '09 that would make it out of date.
Answer: You can use \centering with your parbox to do this.
More info here and here.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
Answer: I think that this answer is the best source. You can declare the newcolumntype in the header and then use it when necessary:
\documentclass{article}
\usepackage{array}

\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}

\begin{document}
\begin{tabular}{|C{1in}|C{1in}|}
A & B\\
C & D\\
\end{tabular}
\end{document}

I only added the vertical lines | to make the column width (1in) and the centering more evident in the output:


Como Recuperar valor de variável em uma janela modal Bootstrap

Question: Meu problema é o seguinte:
Tenho esse código que exibe vários carros em uma tabela:
<?php
$veiculos = "SELECT * from veiculo ";
$veiculos .= "WHERE id_secretaria = '1' ORDER BY placa DESC LIMIT 2"; //mudar conforme o id da secretaria
$query_veiculos = mysqli_query($conexao,$veiculos);
if(!$query_veiculos) {
die("Falha na consulta ao banco");
}
while ( $exibir = mysqli_fetch_array($query_veiculos)) {
$placa = $exibir["placa"];
?>

<?php  echo "Modelo: ".$exibir["modelo"]." | Placa: ".$placa." ";?>

<?php } ?>

Ao clicar no link abre um modal com o seguinte código:
<?php
include('../conecta-db.php');

$placa = $_POST["placa"];

$veiculos = "SELECT * from veiculo ";
$veiculos .= "WHERE placa = '{$placa}'";
$query_veiculos = mysqli_query($conexao,$veiculos);
if(!$query_veiculos) {
die("Falha na consulta ao banco");
}

?>

Veiculo selecionado

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
    </button>

        #
        Placa
        Modelo
        Ano
        Km Rodados

      <?php $i = 1;?>

      <?php
        while ( $exibir = mysqli_fetch_array($query_veiculos)) {
      ?>

        <?php echo $i; ?>
        <?php echo $exibir["placa"]; ?>
        <?php echo $exibir["modelo"]; ?>
        <?php echo $exibir["ano"]; ?>
        <?php echo $exibir["km_rodados"]; ?>

    <?php $i++;} ?>

    <button type="button" class="btn btn-secondary" data-dismiss="modal" id="botao-fechar" style="width: 90%;
display: table;
margin-left: auto;
margin-right: auto;
position: static;">Fechar</button>

Quero saber como posso recuperar o valor da variável placa no modal para chamar apenas a linha que tem a mesma placa no banco de dados.
seguem imagens do sistema:
Aqui os links dos carros:

Aqui o modal onde deve exibir todas as informações do carro:
Comment: É um ajax?.....
Comment: E essa tabela `Carros desta secretária (ou seria secretaria?)` qual é a dela? Surgiu sem mais nem menos no meio da pergunta
Answer: Tu pode fazer como eu, é meio que uma gambiarra, mas me serviu. É só tu colocar esse código dentro de uma função e chama-la por um onClick().
$('#idDaModal').modal();
$("#idDoInput").val(variavalAqui);

Aí tu só cria uma input com type = hidden que irá receber esse valor. Não sei se entendi direito, mas espero ter ajudado.
Comment: Infelizmente não funcionou =(
Comment: Marlon, dê uma olhada nesse código aqui: http://jsfiddle.net/o5fa6k7L/ ele faz o que eu te disse lá em cima, caso atenda à suas necessidades implemente-o ao seu código
Comment: Poxa ajudou muito, obrigado!
Comment: De nada, Marlon


A question about convex functions of minimum and maximum

Question: A question about convex functions of minimum and maximum
Let $f_1, f_2$ are two convex functions $\mathbb{R^n}\to \mathbb{R}$
then I prove that their $\max\{f_1(x),f_2(x),\forall x\in \mathbb{R}^n$ is convex
Is their minimum is also convex?
Answer: $f(x)=x$ and $g(x)=-x$ gives a counterexample.
Comment: Sir..Do you mean $$\min\{f,g\}=\frac{f+g-\vert f-g \vert }{2}=\frac{- \vert 2x \vert}{2}$$ is not convex?
Comment: @ChinnapparajR If you draw the lines $y=x$ and $y=-x$ you can see immediately that $\min \{f,g\}$ is not convex.
Comment: Ok sir. Thanks!
Answer: take $f_1(x)=x^2$ and $f_2(x)=x^2+7$
then $ f(x)=\min \{f_1(x),f_2(x)\}$ is not convex function


Why does ESLint throw parsing error while defining async function as method to existing object and how to prevent it?

Question: Let's assume we have plain object
const foo = {}

and by using Promise constructor syntax we would add async method to it this way:
foo.myAsyncMethod = function () {
  return new Promise((resolve, reject) => {
    ...
  })
}

but we can't do this (according to ESlint):
foo.myAsyncMethod = async function() {
  ...
}

what is convenient approach to add new async functions to objects as method properties after object is already declared?
Comment: You can not access the original object being created?
Comment: @dewwwald Nope, it's just ESLint parsing error, please see answer below for more info.
Comment: I know that. That is why I am asking. I was bussy writing an answer. So if you have access to the object creation that would make it obvious. See potential solution below.
Answer: It appears syntax from question is actually legit:
const obj = {}

obj.foo = function () {
  return new Promise((resolve, reject) => {
    resolve(1)
  })
}

obj.bar = async function () {
  return await Promise.resolve(2)
}

obj.foo().then(context => console.log(context))

obj.bar().then(context => console.log(context))

Produces:
1
2

I got cofused by it because of ESLint giving me error:

In addition, to fix parsing errors from ESLint, add this to your babelrc file:
"parserOptions": {
  "ecmaVersion": 2017
}

Comment: worked on my end too !


The length of an open set.

Question: Our textbook states:

The length l(I) of an interval I is defined to be the difference of the endpoints of I if I is bounded, and infinity if I is unbounded. Lenght is an example of a set function, that is, a function that assosiates an extended real number to each set in a collection of sets. In the case of length, the domain is the collection of all intervals. In this chapter we extend the set function length to a large collection of sets fo real numbers. For instance, the "length" of an open set will be the sum of the lengths of the countable number of open intervals of which it is composed."

I don't understand this last sentence.
1) How can there be a "countable number of open intervals" in an open interval? For example, if we have $(0,2)$, I can choose any two numbers x,y such that $0 < x,y <2$ and create an open interval from them, right? So I don't understand what they mean by a "countable number of open intervals".
2) The text is telling us the the "'length' of an open set will be the sum of the lengths of the countable number of open intervals of which it is composed". But how can we know the length of those "countable number of open intervals of which it is composed.
I was wondering if anybody could give me an example in order to clarify what this means...
Thanks in advance
Comment: The last sentence that you quoted is about the length of an open *set*, not necessarily an interval. If you already know the lengths of intervals, then, given any open set $U$, it is the union of countably many disjoint open intervals (this should be proved in the textbook), and you define the length of $U$ to be the sum of the lengths of those intervals.
Comment: The author must be thinking of the open set as a countable *disjoint* union of open intervals.
Answer: 1)
The phrase "of which it is composed" seems to be intended to mean that you write the open set $U$ as
$$\tag1 U=\bigcup_{i\in S}(a_i,b_i)$$
Where $(a_i,b_i)\cap (a_j,b_j)=\emptyset$ for $i\ne j$.
2)
In (1) above, the length of $(a_i,b_i)$ is $b_i-a_i$. Then the author wants to define
$$l(U)=\sum_{i\in S} (b_i-a_i).$$
Of course, one needs to show that this s well defined
Comment: @Artus You seem to be assuming that these are all single intervals. Some are not: $(1,2)\cup(3,4)$ is an open set. It makes more sense to give it length $2$ rather than $3$, since it doesn't contain the middle section. A single open interval on its own would be given a length in the way you describe.
Comment: But if U is a set (v,w), then why don't we just say that its length is w-v instead of saying $l(U)=\sum_{i\in S} (b_i-a_i)$? In other words, why do we need to break U up into pieces to take the sum of their lengths, instead of just taking the length of U itself? Is that because v and w are not included in the set (since its open)? But, can't we also say that $l(U)=\sum_{i\in S} (b_i-a_i)$ also does not represent the true length of U, since there is not miminum or maximum point to start from or end at (since U is open)?
Answer: The author means to say that an open set in the reals is a countable set of disjoint open intervals. For example, the open set $(2n,2n+1): n \in \mathbb{N}$ is open, and is made up of a countable number of open intervals.
The author says that the 'total length' is the sum of these 'smaller lengths,' which I think is the most intuitive way of thinking about it.

The length of an open set.


Fidning multivariable limit

Question: I'm having trouble in finding multi-variable limit and hope that an example like this could get me started on my work
$$\lim \limits_{(x, y) \to (2,0)} \frac{1-cosy}{xy^2}$$
Answer: It is a limit in two variable but the indeterminate form that comes out is due to a one of them. Then we calculate:
$$\lim \limits_{(x, y) \to (2,0)} \frac{1-\cos y}{xy^2}=\frac{1}{2}\lim_{y\to 0}\frac{1-\cos y}{y^2}$$
But it is a well-known limit:
$$\lim_{t\to 0} \frac{1-\cos(t)}{t^2} = \frac{1}{2} $$
Then
$$\lim \limits_{(x, y) \to (2,0)} \frac{1-\cos y}{xy^2}=\frac{1}{2}\lim_{y\to 0}\frac{1-\cos y}{y^2}=\frac{1}{2}\cdot \frac{1}{2}=\frac{1}{4}$$
Comment: Would I do something similar like plugging in x or y and pulling it out of the limit to most other limits?
Comment: No, there is not a general rule. It depends on the limit.
Answer: $1-\cos(y)=2 \sin^2 \left(\frac{y}{2}\right)$
Then use the equivalency of $\sin^2\left(\frac{y}{2}\right)\sim \frac{y^2}{4}$ when $y$ is close to $0$.
The answer is $\frac{1}{4}$
Comment: It would be beneficial to use TeX code going forward.  You will find a tutorial [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).

Fidning multivariable limit


Is this a valid use case for generics?

Question: Right now in my code I have a bunch of repeated work that looks something like this.
type FP = func(arg1 string, arg2 int, arg3 []string) bool
func Decorator(fp FP, arg1 string, arg2 int, arg3 []string) {
    // Do some stuff prior to running fP
    res := fp(arg1, arg2, arg3)
    // Do some other stuff depending on res
}

My problem is that I have to redefine this method every time I want to add a new FP type with differing number/type of arguments, so I end up having decorator redefined across my code 4-5 times and will probably need to do it more. I want to replace decorator with
type FP = func(a ...interface{}) bool
func Decorator(fp FP, argDetails interface{}) {
    // do stuff
    res := fp(a)
    // do other stuff
}

And having FP assert the type. But I'm unsure if this will cause issues down the line/is a bad use case as Ive seen a lot of stuff about not using interface/will cause performance issues.
Answer: Generics won't help for a few reasons, in particular that generics only help with types, not with the number of arguments. Personally I'd solve this a little differently:
func Decorator(fp func()) {
    // do stuff
   fp()
    // do other stuff
}

Calling it using a closure:
var res someType

Decorator(func() {
    res = originalFunc(arg1, arg2, arg3)
})

It's a little more verbose at the callsite but it works with absolutely any function signature - any number or type of arguments and any number or type of return values. It even works with method calls. It sounds like maybe you're doing some logic based on the result so you could also:
func Decorator(fp func() bool) {
    // do stuff
   res := fp()
    // do other stuff
}

var res someType

Decorator(func() bool {
    res = originalFunc(arg1, arg2, arg3)
    return res
})

Which will still work even if the decorated func has more return values than just that bool, or if you want to use other logic (like, say, if it returns an error you want to convert to a bool with != nil).
Answer: There are some patterns that can help with generic middleware or decorators.
The thing that you suggest with interface actually exists out there. Especially before generics. As example, you can look here https://gokit.io/examples/stringsvc.html
Now, since generics have been released, there are some tricks you can do with generics to achieve middleware without type assertion.
You can find a real world example using generics here: https://github.com/bufbuild/connect-go, if you look hard enough. Although I think they still use interfaces and type assertion, somewhere down the line.
One of the key aspects is that request and response are always exactly one value. To get around the limitation posed by our question, you can stick all the params in a struct (and also do the same for response, if required). Since everything is a struct, you can now pass that as a single value.
Below is a simple implementation using those ideas revolving around generics.
https://go.dev/play/p/fhP1mDwBSXD
func main() {
    handleUpper := decorateLogging("upper", upper)
    fmt.Println(handleUpper(context.TODO(), upperParams{msg: "hello, gopher."}))

    handleAdd := decorateLogging("add", add)
    fmt.Println(handleAdd(context.TODO(), addParams{a: 11, b: 31}))
}

type Handler[REQ any, RES any] func(ctx context.Context, req REQ) (res RES, err error)

func decorateLogging[REQ any, RES any](label string, next Handler[REQ, RES]) Handler[REQ, RES] {
    return func(ctx context.Context, req REQ) (res RES, err error) {
        defer func(ts time.Time) {
            log.Printf("label=%s success=%v took=%s", label, err == nil, time.Now().Sub(ts))
        }(time.Now())
        res, err = next(ctx, req)
        return res, err
    }
}

type upperParams struct {
    msg string
}

func upper(_ context.Context, params upperParams) (string, error) {
    s := strings.ToTitle(params.msg)
    return s, nil
}

type addParams struct {
    a int
    b int
}

func add(_ context.Context, params addParams) (int, error) {
    r := params.a + params.b
    return r, nil
}

This is just one way of doing it. Other answers here look also good. If you can get away with a simpler method, I would go for that. Sometimes this pattern here can come in handy though.

Is this a valid use case for generics?


get check box value dynamically using dynamic check box name

Question: javascript.js
function getbyname(url, emId, obj){
   alert(emId)
    var checked = $('input[name="rsvp_role"+emId+"[]"]:checked').val();//error in this line not getting the value of name
    alert(checked)
   """"""""""""""""""
   other code comes here
   """""""""""""""""""

I want to get the value of checked check box using name.I alerted the emId variable in alert i am getting the correct id ,but if i concatenate and pass that emId in rsvpApproval function i am not getting the  value of that name.I alert i am getting undefined as value.
Is it possible to get the value of checkbox from dynamic name of check box.
Please help.
Answer: Your string concatenation is not proper, the string is delimited using ' but you are trying to use + with the delimiter "
var checked = $('input[name="rsvp_role'+emId+'[]"]:checked').val();

Comment: @user2681579 there is a problem again `input["name=rsvp_role113[]"]:checked"` should be `input[name="rsvp_role113[]"]:checked"` - did you use the same code as I gave
Comment: Sorry i corrected afterwards and it is working fine.
Answer: You need to concatenate your emId properly here using ':
var checked = $('input[name="rsvp_role' + emId + '[]"]:checked').val();

instead of
var checked = $('input[name="rsvp_role"+emId+"[]"]:checked').val();


How to get the according generated javascript file for a KotlinJS project dependencies?

Question: Previously I use the IDEA built-in system to build my kotlinJs project. Today when I migrate it to use the official gradle kotlin2js plugin.
I met a problem.
Previously, I can get the generated libs file like kotlin.js and kotlinx-html-js.js.
But now it seems that I can't get them even when use the buildDependents gradle task.
How to get them?
Or even better, how to bundle them together like the Webpack?
Answer: The simplest solution I know is to use JS DCE plugin with "development mode" enabled: https://kotlinlang.org/docs/reference/javascript-dce.html#development-mode
Alternatively you could create a Copy task, which looks at the dependencies, and extracts .js files from those (look for task assembleWeb in the tutorial: https://kotlinlang.org/docs/tutorials/javascript/getting-started-gradle/getting-started-with-gradle.html)


XmlDocument cannot find the specfied file

Question: I just upgraded my Windows Phone 8.0 Silverlight app to a Windows Phone 8.1 Runtime app.
Unfortunately, I have to downgrade this app to a 8.1 SL project, because Windows Runtime lacks Google Admob support.
That aside, in my 8.1 RT project I use the following code to fetch a XML feed:
private async void GetData()
{
    XmlDocument regenthetinXML = await XmlDocument.LoadFromUriAsync(new Uri("http://regenthet.in/data/regenthetin.xml", UriKind.Absolute));
}

The XmlDocument class is supported at both platforms, but when I use exactly the same code in my Windows Phone 8.1 SL project I get exceptions like this one:

An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

Any suggestions? What I'm doing wrong?
Comment: Take a look here at this previous `SO` posting looks to be similar in nature.. http://stackoverflow.com/questions/9650232/read-xml-using-xmldocument-loadfromuriasyncurlstring
Answer: Use a WebClient to retrieve the string first.
string xmlStr;
string m_strFilePath = "http://regenthet.in/data/regenthetin.xml";
using(var wc = new WebClient())
{
    xmlStr = wc.DownloadString(m_strFilePath);
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStr);

On mobile, if you don't have DownloadString, use DownloadStringAsync with an additional event handler to DownloadStringCompleted.
Comment: Thanks for your response. I know you can use the WebClient class to retrieve datafiles etc, but why isn't it possible to fetch external datafiles on the Silverlight platform on the way as described above. It is the same XmlDocument class, how can I notice the difference of functionality between the two platforms?
Comment: Does the code work for you? Yes, regarding the difference in functionality between two platforms, there are some methods in desktop which are not there on phone (like cryptography). Maybe, by forcing `Async` on us, we are driven to responsive UI models


Gimel function and cofinality.

Question: I am supposed to show that under the conditions given below, the next property is true:
Let $\lambda \in Card$, where $Card$ is the class of all infinite cardinals. Then,
If $\kappa>\lambda$ and $\forall\eta<\kappa$ $\eta^{\lambda}<\kappa$ and if cof$(\kappa)\leq\lambda$, then $\kappa^{\lambda}=\kappa^{cof(\kappa)}$
Here $cof(\kappa)$ is the standard notation for cofinality in context of the minimal cardinality of all cofinal subsets of $\kappa$.
One inequality is obvious, i.e. $\kappa^{cof(\kappa)}\leq\kappa^{\lambda}$ because of one of the assumptions above, but I am struggling with the other one.
Comment: You should really take the hint and stop tagging these with [tag:large-cardinals].
Answer: Hint: If $S\subseteq\kappa$ is unbounded, then $\kappa^\lambda\leq\prod_{\alpha\in S}|\alpha+1|^\lambda$.
If you can't figure out why this inequality is true, more details are hidden below.

 A function $f:\lambda\to\kappa$ is determined by its restriction to partial functions $\lambda\to \alpha$ for each $\alpha$ and such a partial function can be thought of as a total function $\lambda\to\alpha+1$ (send the undefined values to $\alpha$).

Gimel function and cofinality.


How to select specific column in LINQ?

Question: I have to select specific column from my DataTable using linq
I am using this code
ds.Table[0].AsEnumerable().Where<DataRow>(r=>r.Field<int>("productID")==23).CopyToDataTable();

~
But it is giving me all columns and I need only PRODUCTNAME , DESCRIPTION  , PRICE
How I can write this query?
Answer: To expand a bit on @lazyberezovsky, you can use an anonymous type projection to get all of the fields you want:
ds.Table[0].AsEnumerable()
    .Where<DataRow>(r => r.Field<int>("productID") == 23)
    .Select(r => new { ProductName = r.Field<string>("productName"),
                       Description = r.Field<string>("description"),
                       Price = r.Field<decimal>("price") });

I don't know what name and type your product name, description, and price fields are, so you will have to substitute those.
Comment: Thanks it works.You got my question claerly and your answer is the answer of my question. I know already how to show one field but don't know how to show 3
Answer: Use Select method:
ds.Table[0].AsEnumerable()
           .Where<DataRow>(r=>r.Field<int>("productID")==23)
           .Select(r => r.Field<int>("productID"));

UPDATE: In case you need to select several columns, you can return anonymous type:
var query = from row in dt.ds.Table[0].AsEnumerable()
            where row.Field<int>("productID")==23
            select new  {
                           ProductID = x.Field<string>("productID"),
                           Foo = x.Field<string>("foo")
                        };

If you need to copy that data to new table, you'll face problem (CopyToDataTable requires collection of DataRow objects). See How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow to solve this problem.
Comment: By this I can pick only one column but I have to pick 3

How to select specific column in LINQ?


Build Variant Android studio

Question: Por que razão o meu build variants (primeira imagem) não apresenta as opções que pretendo para a compilação? Neste caso pretendia o "mockdebug" como apresento na segunda imagem.

O que preciso fazer para obter todas estas opções de escolha no build variants?
build.gradle
    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.2"
        defaultConfig {
            applicationId "com.example.projeto"
            minSdkVersion 15
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
        sourceSets {
            main {
                java.srcDirs = ['src/main/java']
            }
            test {
                java.srcDirs = ['src/test/java', 'src/main/java']
                resources.srcDirs = ['src/test/res', 'src/main/res']
            }
            androidTest {
                java.srcDirs = ['src/androidTest/java', 'src/main/java']
                resources.srcDirs = ['src/androidTest/res', 'src/main/res']
            }
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])

        // Optional -- Mockito framework
        compile 'com.android.support:appcompat-v7:25.3.0'
        compile 'com.android.support.constraint:constraint-layout:1.0.1'
        compile 'com.prolificinteractive:material-calendarview:1.4.3'
        compile 'com.android.support:support-v4:25.3.0'
        compile 'com.android.support:recyclerview-v7:25.3.0'
        compile 'com.android.support:design:25.3.0'
        compile 'org.apache.httpcomponents:httpclient-android:22.214.171.124'
        testCompile 'junit:junit:4.12'
        testCompile 'org.mockito:mockito-core:1.10.19'
        testCompile 'org.robolectric:robolectric:3.0'
        androidTestCompile 'junit:junit:4.12'
        androidTestCompile 'com.android.support:support-annotations:25.3.0'

        //Android testing support librarys runner and rules
        androidTestCompile('com.android.support.test:runner:0.5') {
            // Necessary if your app targets Marshmallow (since the test runner
            // hasn't moved to Marshmallow yet)
            exclude group: 'com.android.support', module: 'support-annotations'
        }
        androidTestCompile("com.android.support.test:rules:0.5") {
            exclude group: 'com.android.support', module: 'support-annotations'
        }

        //Expresso UI Testing dependencies
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
            exclude group: 'com.android.support', module: 'support-annotations'
        }
        androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'

        // add this for intent mocking support
        androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'

        // add this for webview testing support
        androidTestCompile 'com.android.support.test.espresso:espresso-web:2.2.2'
    }

Comment: Compartilhe também seu build.gradle
Comment: já adicionei o build.gradle @Leonardo Lima
Comment: http://www.techotopia.com/index.php/An_Android_Studio_Gradle_Build_Variants_Example
Answer: Para adicionar flavors como na imagem, você deve adicionar um bloco de  productFlavors no seu build.gradle. Dentro dele você poderá criar diversos flavors e personalizá-los.
...
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
productFlavors {
    prod {
        // Configurações de prod
    }
    mock {
        // Configurações de mock
    }
}
...

Comment: Muito obrigada @Leonardo Lima

Build Variant Android studio


drupal views : display previous nodes

Question: I am having difficulties to filter data with views. I have made several video lessons on a subject and managed to display on the side of each video all other related videos in a block.
However i wish to see displayed in this block all related AND Previous videos.
I created a field called "order" (integer) in my content type, and i wonder how i can add a filter to make sure that the related videos have an "order" value lower than the "order" value of the video being displayed.
I 'd be greateful if anybody could help me with that.
Answer: It would be best to create a page/block (basically just a different views display) to achieve that.
The constraints that you have i.e. Previous and Related can only find a practical application if your videos belong to the same category.
If I am getting the question right what you are better off doing is creating another block which displays all videos irrespective of the categories.

drupal views : display previous nodes


Debug info from Symfony sfMailer regarding sending a mail

Question: I need to log result of sending an e-mail message by sfMailer in Symfony 1.4
The message is to be sent when user submits a form which includes his contact e-mail address.
In case of failure (sending the mail) I should log his e-mail address using logger. That is pretty clear to me.
What I still don't get is how to get an "update" from sfMailer about whether the sending was success?
Something that returns true or false if possible.
Web debug toolbar is nice but it does not help here.
Answer: According to the doc:

When using send() the message will be sent just like it would be sent if you used your mail client. An integer is returned which includes the number of successful recipients. If none of the recipients could be sent to then zero will be returned, which equates to a boolean false. If you set two To: recipients and three Bcc: recipients in the message and all of the recipients are delivered to successfully then the value 5 will be returned.

Which result in:
<code>// Send the message
$result = $mailer->send($message);

// or in a symfony action
$result = $this->getMailer()->send($message);
</code>


Is there anything I can do about someone who has pointed their domain at my ip?

Question: This is kind of a weird request. For some reason whoever owns safeandbuy.com has pointed their domain at my IP address. The reason it's a problem is that I'm having all kinds of crawlers that are trying to crawl my site with that domain name.
Is there anything I can do about this?
Comment: Some SEO scammers will point their domain at your site, and use your content to get their domain into the search engines. After a while, they will point their domain back at their own scam site, and will  reap the visit traffic they get via the search queries.
Comment: I am having the same issue.  In fact when I look up the domain of the other guy, dnsdo2.com it seems he has his A record set to my IP.

http://www.dnswatch.info/dns/dnslookup?la=en&host=dnsdo2.com+&type=A&submit=Resolve

I already wrote to the registrar but they are out of China and I am not sure they will do anything about it.

I also do not want all of the crawlers trying to crawl with that domain.

Some additional info:
Initially, my server admin set me up with 4 name servers ns1, ns2, ns1.name.domain, ns2.name.domain which was assigned to two sets of IP's (one of which was to the
Answer: You could set up a virtualhost on your webserver for safeandbuy.com to grab all that traffic, and just have an index page that says "I am not safeandbuy.com".  That would at least pull the hits out of your actual domain.
The whois information for safeandbuy.com has a contact phone number, address and email.  You could try to contact them and let them know they are pointing to the wrong IP.
Comment: and, if they fail to correct the situation, you can always setup a redirect to your favorite porn site =)
Comment: +1 This would be the most ideal method
Comment: Throw in a robots.txt to (hopefully) prevent the crawlers from trying to access anything else, and that's perfect.
Comment: Or even better: make sure your default name based virtualhost does not provide useful content that can help them gain search engine reputation.
Comment: To optimize the solution, you'd wan't to send as little data as possible in the response.  I'd say to setup @Alex virtual host, but have the only response be a HTTP 403.  Not a custom "forbidden" file, just a plain HTTP /403 and let the web browser do the rest.  Then any query to *.safeandbuy.com will return an instant 403.  Minimal server impact, no SEO help given, and real admins who goofed tend to figure this out FAST. (in apache this would be a RewriteRule of [F] )
Answer: Ok here is something that can be very good to do:
Add this under your "header" section at the top of your index page:
<base href="http://www.mydomain.com" target="_top"/>
(Complements of BillThor whos is a very senior member on this site)
By doing this, the person who has his domain pointed to yours .. once someone gets there and clicks on a link, it will redirect them to use your links so they only can steal the home page link and nothing else).
Unfortunately there is no way to stop these kind of people. but all you can do is do a redirect back to your links from his domain.
Another permanent fix to this pesky problem.
It depends on what server program you are using, but for, apache2
has its virtual host settings in the '/etc/apache2/site-enabled'
directory. Basically, it has a default virtual hosts ('000-default')
and this is set for the mydomain.com site for now. Thus,
here is my approach.

Copy the current 000-default to 010-somename. (Please be
careful, 000-default is usually symbolic link file so you have to copy
it from ../site-available/default.)
Set the virtual host setting in 010-somename. Add these two
lines below the first line
'<VirtualHost *:80>':
ServerName www.mydomain.com
ServerAlias mydomain.com

Make 000-default points to other directory (elsewhere). In
'000-default' file, change 'DocumentRoot /var/www' to point other
location like 'DocumentRoot /var/www-test'. The directory
/var/www-test don't need to exists, If it is not exists, the
connections using other domain name will get error.
Restart apache2 : "sudo /etc/init.d/apache2 restart"

I hope this is helpful.
Comment: 000-default is an ubuntuism and does not hold true for all distros. Other than that it's good advice.
Comment: Correct.  This is for Ubuntu.  For Cent/OS and other software the 000-default may be something else. However, if you are using Apache2, the approach will be the same using a different convention.  This solved my problem permanently.
Answer: Adding a default virtual host that redirects to a 403 or 404 as others have stated is a solid option. If you want something you can quickly add to your .htaccess file you can do the following to block unofficial domains (requires Apache 2.4 and having mod_rewrite enabled):
# Send requests that don't match domain name to a 404 page
<If "req('Host') !~ /your-domain-name.com/i && req('Host') != 'your.ip.address'">
  RewriteRule ^ - [R=404,L]
</If>

Note: If you have multiple spellings of your domain name pointed to the same IP address you would need to modify the expression to include all valid domain names for the IP address.
Answer: Try using Php to identify the URL of the webpage
if(strpos( $_SERVER['HTTP_HOST'], 'yoururl.com') !== false){
    echo "This is Genuine Yoururl.com";
} else {
    header('Location: http://www.yoururl.com.com/'); exit; // Someone has opened your site as iframe or is using A record to point toward your website
}


Ao printar um campo com o php do banco de dados ele não identifica as váriaveis

Question: Estou tentando criar um gerador de textos automáticos mas alguns textos vão ter variáveis neles ( exemplo nas imagens ). existe a possibilidade de ele identificar? estou usando o campo longtext no banco para os campos que devem ser printados

Edit: os campos em questão estão sendo identificados e printados em outro lugar pois já fiz o teste o problema ocorre apenas quando as variáveis vem do banco de dados
                 $SelectCabecalhotxt = $PDO->prepare($SelectCabecalhotxt);
                 $SelectCabecalhotxt->execute();
                 if ($SelectCabecalhotxt->rowCount()>0){
                     while($row2 = $SelectCabecalhotxt->fetch()){
                         echo"

                         <input type='radio' id='operacaotxt".$row2["id_copi_texto"]."' name='operacaotxt' value='".$row2["copi_texto"]."'>
                         ".$row2["copi_texto"]."

";
                     }
                 };```

Comment: Como não consegui que ele identificasse elas quando vinham do banco usei a grafia *quartos* , assim loco após o select eu passo uma lista substituindo todas as palavras com ** por suas respectivas variáveis *quartos* por $quartos, *vagas* por $vagas e assim por diante. Provavelmente não é o ideal mas deu certo
Answer: Tente definir suas variáveis fora do html é mais confortável para se programar.
Já com as variáveis definidas o seu código precisa ser php nas variaveis então ficaria
                 $SelectCabecalhotxt = $PDO->prepare($SelectCabecalhotxt);
                 $SelectCabecalhotxt->execute();
                 if ($SelectCabecalhotxt->rowCount()>0){
                     while($row2 = $SelectCabecalhotxt->fetch()){
                         echo"

                         <input type='radio' id='operacaotxt<?php echo $row2["id_copi_texto"]?>' name='operacaotxt' value='<?php echo $row2["copi_texto"]?>'>
                         <label for='operacaotxt<?php echo $row2["id_copi_texto"]?>'><?php echo $row2["copi_texto"]?>

";
                     }
                 };

de qualquer forma sempre tente definir suas variáveis fora da area do front. (serio ajuda muito) :)


Convert HTACCESS mod_rewrite directives to nginx format?

Question: I'm brand new to nginx and I am trying to convert the app I wrote over from Apache as I need the ability to serve a lot of clients at once without a lot of overhead! I'm getting the hang of setting up nginx and FastCGI PHP but I can't wrap my head around nginx's rewrite format just yet. I know you have to write some simple script that goes in the server {} block in the nginx config but I'm not yet familiar with the syntax. Could anyone with experience with both Apache and nginx help me convert this to nginx format? Thanks!
# ------------------------------------------------------ #
# Rewrite from canonical domain (remove www.)            #
# ------------------------------------------------------ #

    RewriteCond %{HTTP_HOST} ^www.domain.com
    RewriteRule (.*) http://domain.com/$1 [R=301,L]

# ------------------------------------------------------ #
# This redirects index.php to /                          #
# ------------------------------------------------------ #

    RewriteCond %{THE_REQUEST} ^[A-Z]+\ /(index|index\.php)\ HTTP/
    RewriteRule ^(index|index\.php)$ http://domain.com/ [R=301,L]

# ------------------------------------------------------ #
# This rewrites 'directories' to their PHP files,        #
# fixes trailing-slash issues, and redirects .php        #
# to 'directory' to avoid duplicate content.             #
# ------------------------------------------------------ #

    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^(.*)$ $1.php [L]

    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^(.*)/$ http://domain.com/$1 [R=301,L]

    RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^.]+\.php\ HTTP/
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^([^.]+)\.php$ http://domain.com/$1 [R=301,L]

# ------------------------------------------------------ #
# If it wasn't redirected previously and is not          #
# a file on the server, rewrite to image generation      #
# ------------------------------------------------------ #

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([a-z0-9_\-@#\ "'\+]+)/?([a-z0-9_\-]+)?(\.png|/)?$ generation/image.php?user=${escapemap:$1}&template=${escapemap:$2} [NC,L]

Answer: I convert part-by-part to follow more easily.
Apache:
RewriteCond %{HTTP_HOST} ^www.domain.com
RewriteRule (.*) http://domain.com/$1 [R=301,L]

Nginx:
server {
    listen 80;
    server_name www.domain.com;
    root /var/www/localhost/htdocs;

    rewrite ^ http://domain.com$request_uri permanent;
}

Apache:
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /(index|index\.php)\ HTTP/
RewriteRule ^(index|index\.php)$ http://domain.com/ [R=301,L]

Nginx:
location = /index {
    try_files $uri @homepage;
}
location @homepage {
    rewrite ^ http://domain.com break;
}
location ~ \.php$ {
    if ($request_uri ~* /index\.php$) {
        rewrite ^ http://domain.com break;
    }
    fastcgi_pass 127.0.0.1:9000;
    include fastcgi.conf;

    fastcgi_intercept_errors        on;
    error_page 404 /error/404.php;
}

Apache:
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)$ $1.php [L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)/$ http://domain.com/$1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^.]+\.php\ HTTP/
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+)\.php$ http://domain.com/$1 [R=301,L]

Nginx:
rewrite ^/(.*)/$ /$1 permanent;

if (-f $document_root/$request_uri.php) {
    rewrite ^(.*)$ $1.php last;
}

location ~ \.php$ {
    if (-f $document_root/$request_uri) {
        rewrite ^([^.]+)\.php$ http://domain.com$1 permanent;
    }
    ...
}


Covariance and independence?

Question: I read from my textbook that $\text{cov}(X,Y)=0$ does not guarantee X and Y are independent. But if they are independent, their covariance must be 0. I could not think of any proper example yet; could someone provide one?
Comment: You might also enjoy a quick review of [Anscombe's Quartet](http://en.wikipedia.org/wiki/Anscombe%27s_quartet), which illustrates some of the many different ways in which a particular nonzero covariance can be realized by a bivariate dataset.
Comment: The thing to note is that the measure of covariance is a measure of linearity.. Calculating the covariance is answering the question 'Do the data form a straight line pattern?'  If the data do follow a linear pattern, they are therefore dependent.  BUT, this is only one way in which the data can be dependent.

Its like asking 'Am I driving recklessly?'  One question might be 'Are you travelling 25 mph over the speed limit?'  But that isn't the only way to drive recklessly.  Another question could be 'Are you drunk?' etc..  There is more than one way to drive recklessly.
Comment: The so- called measure of linearity gives a structure to the relationship. What is important that the relationship can be non-linear which is not uncommon. Generally, covariance is not zero, It is hypothetical.The covariance indicates the magnitude and not a ratio,
Answer: Easy example:  Let $X$ be a random variable that is $-1$ or $+1$ with probability 0.5.  Then let $Y$ be a random variable such that $Y=0$ if $X=-1$, and $Y$ is randomly $-1$ or $+1$ with probability 0.5 if $X=1$.
Clearly $X$ and $Y$ are highly dependent (since knowing $Y$ allows me to perfectly know $X$), but their covariance is zero:  They both have zero mean, and
$$\eqalign{
\mathbb{E}[XY] &=&(-1) &\cdot &0 &\cdot &P(X=-1) \\

&+& 1 &\cdot &1 &\cdot &P(X=1,Y=1) \\

&+& 1 &\cdot &(-1)&\cdot &P(X=1,Y=-1) \\

&=&0.
}$$
Or more generally, take any distribution $P(X)$ and any $P(Y|X)$ such that $P(Y=a|X) = P(Y=-a|X)$ for all $X$ (i.e., a joint distribution that is symmetric around the $x$ axis), and you will always have zero covariance.  But you will have non-independence whenever $P(Y|X) \neq P(Y)$; i.e., the conditionals are not all equal to the marginal. Or ditto for symmetry around the $y$ axis.
Answer: Here is the example I always give to the students. Take a random variable $X$ with $E[X]=0$  and $E[X^3]=0$, e.g. normal random variable with zero mean.  Take $Y=X^2$. It is clear that $X$ and $Y$ are related, but
$$Cov(X,Y)=E[XY]-E[X]\cdot E[Y]=E[X^3]=0.$$
Comment: +1 but as a minor nitpick, you do need to assume that $E[X^3] = 0$ separately (it does not follow from the assumption of symmetry of the distribution or from $E[X] = 0$), so that we don't have issues such as $E[X^3]$ working out to be of the form $\infty - \infty$.  And I am queasy about @ocram's assertion that "**a** N(0,1) rv and **a** chi2(1) rv are uncorrelated." (emphasis added)  Yes, $X \sim N(0,1)$ and $X^2 \sim \chi^2(1)$ are uncorrelated, but not **any** $N(0,1)$ and $\chi^2(1)$ random variables.
Comment: I like that example too. As a particular case, a N(0,1) rv and a chi2(1) rv are uncorrelated.
Comment: @DilipSarwate, thanks, I've edited my answer accordingly. When I wrote it I though about normal variables, for them zero third moment follows from zero mean.
Comment: @Dilip Note, though, that the zero third moment is an immediate consequence of symmetry **and** a zero mean, making this example more general than it might appear. A distribution with these properties can be generated from *any* starting distribution with finite absolute third moment simply by symmetrizing it, giving arbitrarily rich examples.
Comment: @Dilip That's why I specified that the absolute third moment must be finite.
Answer: The image below (source Wikipedia) has a number of examples on the third row, in particular the first and the fourth example have a strong dependent relationship, but 0 correlation (and 0 covariance).
Answer: Some other examples, consider datapoints that form a circle or ellipse, the covariance is 0, but knowing x you narrow y to 2 values.  Or data in a square or rectangle.  Also data that forms an X or a V or a ^ or < or > will all give covariance 0, but are not independent.  If y = sin(x) (or cos) and x covers an integer multiple of periods then cov will equal 0, but knowing x you know y or at least |y| in the ellipse, x, <, and > cases.
Comment: That if should be "if x covers an integer multiple of periods beginning at a peak or trough", or more generally: "If x covers an interval on which y is symmetric"
Comment: @user1993,  Look at the formula for covariance (or correlation).  Then think about the circle/ellipse.  Subtracting the means gives a circle centered on (0,0), so for every point on the circle you can reflect the point around the x-axis, the y-axis, and both axes to find a total of 4 points that will all contribute the exact same absolute value to the covariance, but 2 will be positive and 2 will be negative giving a sum of 0.  Do this for all of the points on a circle and you will be adding together a bunch of 0's giving a total covariance of 0.
Comment: could you explain why the covariance is zero for a circle?
Answer: Inspired by mpiktas's answer.
Consider $X$ to be a uniformly distributed random variable, i.e. $X \sim U(-1,1) $. Here, $$E[X] = (b+a)/2 = 0.$$ $$E[X^2] = \int_{-1}^{1} x^2  dx = 2/3$$ $$E[X^3] = \int_{-1}^{1} x^3 dx = 0$$
Since $Cov(X, Y) = E[XY] - E[X] \cdot E[Y]$, $$ Cov(X^2, X) = E[X^3] - E[X] \cdot E[X^2] \\ = 0 - 0 \cdot 2/3= 0 $$ Clearly $X$ and $X^2$ are not independent. But their covariance is computed to be zero. Since a counter example has been found, the proposition is false in general.
Comment: Wait, why did you undo my edit?

Covariance and independence?


Easiest way to install a GUI backend for matplotlib?

Question: I have been struggling to get plot using matplotlib.pyplot. Obviously, the problem is
temp.py:58: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  plt.show()

I realised that there are multiple backends to switch to, and 's snippet helped me list all inactive GUI backends.
import matplotlib
gui_env = [i for i in matplotlib.rcsetup.interactive_bk]
non_gui_backends = matplotlib.rcsetup.non_interactive_bk
print ("Non Gui backends are:", non_gui_backends)
print ("Gui backends I will test for", gui_env)
for gui in gui_env:
    print ("testing", gui)
    try:
        matplotlib.use(gui,warn=False, force=True)
        from matplotlib import pyplot as plt
        print ("    ",gui, "Is Available")
        plt.plot([1.5,2.0,2.5])
        fig = plt.gcf()
        fig.suptitle(gui)
        plt.show()
        print ("Using ..... ",matplotlib.get_backend())
    except:
        print ("    ",gui, "Not found")

To which I got
testing GTK3Agg
     GTK3Agg Not found
testing GTK3Cairo
     GTK3Cairo Not found
testing MacOSX
     MacOSX Not found
testing nbAgg
     nbAgg Not found
testing Qt4Agg
     Qt4Agg Not found
testing Qt4Cairo
     Qt4Cairo Not found
testing Qt5Agg
     Qt5Agg Not found
testing Qt5Cairo
     Qt5Cairo Not found
testing TkAgg
     TkAgg Not found
testing TkCairo
     TkCairo Not found
testing WebAgg
     WebAgg Not found
testing WX
     WX Not found
testing WXAgg
     WXAgg Not found
testing WXCairo
     WXCairo Not found

Some methods to setup a GUI backend suggest reinstalling python after installing some dependencies but I am looking for a simpler method (if any exists) .
Answer: I went across methods and found the simplest method: Use TkAgg backend.

Install tkinter

$ sudo apt-get install python-tk
$ sudo apt-get install python3-tk

Specify this backend in your Python script

import matplotlib
matplotlib.use('TkAgg', force=True)
import matplotlib.pyplot as plt

Now you can freely call plt.show() for your plots and stay happy :)
Comment: I installed tkinter on Windows upon setup, and I tried your solution, but when I run `plt.show()`, nothing is produced. When I run the snippet posted in the question, it says that `TkAgg` is not found. Do you know what the problem might be?
Comment: @MRichards can you check what all backeds do you have available (after the installation), using the script mentioned in the question?


How to load doctrine fixtures if we have multiple databases and connections

Question: I used this documentation : https://symfony.com/doc/4.4/doctrine/multiple_entity_managers.html
So now I can create new databases named legacy and Project like this
doctrince.yaml:
doctrine:
  dbal:
    default_connection: legacy
    connections:
      legacy:
        driver: pdo_mysql
        host: "%env(database_host)%"
        port: "%env(database_port)%"
        dbname: "%env(database_name)%"
        user: "%env(database_user)%"
        password: "%env(database_password)%"
        charset: UTF8
      project:
        driver: pdo_mysql
        host: "%env(database_host_project)%"
        port: "%env(database_port_project)%"
        dbname: "%env(database_name_project)%"
        user: "%env(database_user_project)%"
        password: "%env(database_password_project)%"
        charset: UTF8
  orm:
    default_entity_manager: legacy
    entity_managers:
      legacy:
        connection: legacy
        mappings:
          Legacy:
            is_bundle: false
            type: annotation
            dir: "%kernel.project_dir%/..."
            prefix: '...'
            alias: Legacy
      project:
        connection: project
        auto_mapping: true
        mappings:
          Project:
            is_bundle: false
            type: annotation
            dir: "%kernel.project_dir%/src/Entity"
            prefix: 'App\Entity'
            alias: Project

Now I have several Fixture classes all of them depend on each other and also some will create fixture for legacy and some will create for project.
Now my question is when I do:
php bin/console doctrine:fixtures:load --em=legacy
It runs the appfixtures of the project but not the of the bundle.
and then i get this error:

The class .. was not found in the chain configured namespaces ....

My question is now how can I load fixtures on multiple databases with multiple connections.
Thanks in advance.
Answer: You should read this doc : https://symfony.com/doc/current/doctrine/multiple_entity_managers.html
I think it may solve your problem as this is exactly what you trying to do.
If you have to create a fixture for legacy just use :
$entityManager = $this->getDoctrine()->getManager('legacy');`

else if it is for project use
$entityManager = $this->getDoctrine()->getManager('project');`

Also, if you change doctrine.dbal.default_connection, entityManager will run against the defined connection.
So you can try to create group of fixtures.
And then run fixtures for project :

Edit config for test environment

#config/packages/test/doctrine.yaml
doctrine:
    dbal:
        default_connection: 'project'

Then run fixture for 'project' group

> php bin/console doctrine:fixtures:load --group=project

Then do the same thing for 'legacy'
Comment: Isn't ```$this``` a ```Fixture```? From what I can see in Symfony 5, ```Fixture``` has no ```getDoctrine()```.   Is see the OP is for Symfony 4, has this changed then?
Comment: But for the fixtures we are using `ObjectManager` like so ```public function load(ObjectManager $manager): void
    {...```
Comment: You are right, I have edited my answer so I hope you it'll help you.


PyCharm does not have write access to /usr/share/pycharm. Please run it by a privileged user to update

Question: Need Help to update build version of Pycharm Community Edition 17.1.1 installed on Ubuntu 17.04. When "Check for Updates", the following message appears, and I am not sure how to proceed from here.

How do I run it as privileged user?
Comment: @Hadi: when editing questions, product/brand names like Ubuntu, and version numbers like 17.x, do not need to be formatted using inline code. Broadly they are proper nouns, and so just need upper case initials. Thanks.
Comment: @halfer thanks for advising :)
Answer: Please try this it works for me (do it by root):
cd /usr/lib/
chmod 777 -R pycharm-community/

Then open pycham and update.
Comment: For PyCharm Professional on MacOS, use `sudo chmod -R 777 /Applications/PyCharm.app/Contents/`.
Comment: for me it adding the same permissions to the directory specified in the error message (where I installed PyCharm Professional): `sudo chmod -R 777 /opt/pycharm/`
Comment: A better solution would be to change the ownership of the folder. In my case; exracted directory was owned by `root`. you can use `sudo chown $(id -u):$(id -g) -R pycharm-2020.3.4`.
Comment: For 2023 version onwards, I had to run `sudo chmod 777 -R pycharm-community-2023.1.1/` in folder where pycharm is installed which was `/opt` in my case
Answer: Please try this it works for me:
sudo updatedb && sudo locate pycharm.sh
sudo /path/to/pycharm.sh

Don't do anything else during that session, just apply the update.  Then close PyCharm and reopen normally, and you should find you are running the new version with no need to download or mess with folder permissions.
for more details check https://intellij-support.jetbrains.com/hc/en-us/community/posts/206601265-Fixed-PyCharm-automatic-update-fails-on-Linux-due-to-permissions
Comment: Another way to get the path to the pycharm.sh file is to check the *.desktop file using: `cat $(ls /usr/share/applications | grep pycharm)`. This contains the path to the pycharm.sh.
Answer: sudo chown -R  /opt/yourdirectory
Answer: The issue came up when I upgraded Ubuntu from 16.04 to 17.04. I tried sudo but did not worked. So had to uninstall and install again Pycharm. Now all good and gets new updates.
Answer: Sounds like a permissions issue. I think it will work if you run Pycharm via sudo.


How safe is it to allow www-data to run sudo quota?

Question: I manage the hosting of a custom Software-as-a-Service (SAAS) CMS and Ecommerce system. This system is powered by a cluster of LAMP servers behind an HAproxy instance, and each customer / domain has their own unix account on the cluster and in LDAP. Each customer purchases a given amount of data storage which we manage using a cPanel server, so the quotas are enforced by standard linux kernel / NFS quotas.
I want to be able to provide disk space usage statistics in my customers' web admin dashboard. On the LAMP cluster as root I can run /usr/bin/quota domain.name to get the disk space used by any given domain. However our Apache instances run as UID www-data.
Is it safe to allow www-data to run sudo /usr/bin/quota with NOPASSWD?
Answer: If your sudoers configuration ensures that /usr/bin/quota is the only thing that www-data is allowed to run with root privileges, then yes, this sounds reasonably safe.
However, it still is riskier than needed. A safer approach would be to set up a cron job to retrieve this information periodically (say, every 1-5 minutes) and output it to a file that www-data has access to read.
Comment: Thanks. My concern with a cron job is that it might be too delayed, e.g. if a user is trying to delete files to free up space. But if it ran every minute, that would probably be OK...
Answer: Miles answer is right.. the correct approach is tie in some task queue system into your application and workers check the task queue for jobs to run.. they could check every second and have better control over the user they run as.. So you can avoid the cron delay.
Comment: Yep, this would work even better!


Anomaly detection in Text Classification

Question: I have built a text classifier using OneClassSVM.
I have the training set which corresponds to only one label i.e("Yes") and I don't have the other("NO") label data.
My task is to build a classifier which classifies the new unseen sentence(test data) as 1 if it is very similar to the training data. Else, it classifies as -1 i.e,(anomaly).
I have used Word2Vec to build the word embeddings for my training data.
Then, I am using word-vector averaging with OneClassSVM to build a anomaly detector classifier.
This classifier is currently giving accuracy of about 50%-55%. I have to enhance this further to build a robust classifier.
Any suggestions to this problem would be helpful...
Comment: NB works well when there is a labeled training data. But in my case I have the data of one label only.
Comment: You would probably have to play around with SVM kernels, which is not trivial. Have you tried other methods, for ex. clustering?
Comment: Clustering didnot help. I tried all other kernels in SVM, but polynomial kernel worked well compared to other ones.
Comment: Naive Bayes is also widely used for text classification, have you tried it?
Answer: The question is than about your data - how representational your cases from training set are for the whole "yes" subset - ?
And what type of errors your classifier does?
You may also try to use word2vec to produce embeddings of the whole texts.
Comment: My training data is about 7000 sentences in length. In this training set, I have some outliers in this set as well. For example, "We provide authorization to our users." is a sentence in my training set. I am crawling the web to get my test set. It's not performing well on my  test set even after tuning the hyper-parameters.
Comment: Sorry for not answering earlier, hectic time... Any luck with improving accuracy?

If I understood you correctly you have 7000 sentences of class '1' and you pick a sentences from the web for tests. And what type of errors your classifier does more frequently - false positive or negative?

7000 sentence would have to be a very compact scope of meaning to be representative vs random sentence from the web... You should consider using pretrained embeddings. And ponder how representative is your training set for the scope of language (sentences) you want to classify as '1'.
Comment: I couldn't construct a confusion matrix in order to tell you whether model is making more false positives or negatives since i don't have labels in my data neither in my training  set not in my test set. And I have also used pretrained embeddings to build a model using GoogleNews-vectors-negative300 , but that didn't work out well.
Comment: Hm, how have you measured 50-50% accuracy?
Comment: Just by manual check on the predictions by the model.
Answer: This paper Outlier Detection for Text Data discussed similar problem. I believe for a robust classifier you need to understand latent topics in the corpus, either with LSI approach as discussed in this paper or via a clustering approach in latent space. I think using de-noising autoencoder for learning features from sentence embedding is the most straight forward approach to obtain robust classifier.


How I can find the elements from two data frame with differnt length in R?

Question: I have two Matrix with different width.

Matrix_A
  'data.frame':412 obs. of  5 variables:
 $ R : num  2 18 18 2 2 18 18 2 2 2 ...
 $ NS: num  4.82e+09 4.82e+09 4.82e+09 4.82e+09 4.82e+09 ...
 $ NP: chr  "20000070000" "20000000090000" "20000000060000" "20000000010000" ...
 $ NG: chr  "TE" "EC" "ET" "HT" ...
 $ DC : logi  NA NA NA NA NA NA ...

Matrix_B

  'data.frame': 2687 obs. of  4 variables:
 $ R : num  18 2 2 2 18 2 2 2 18 2 ...
 $ NS : num  4.81e+09 4.81e+09 4.81e+09 4.81e+09 4.81e+09 ...
 $ NP :chr  "20000000000400" "2000000000600" "2000000001000" "20000000007000" ...
 $ NG: chr  "HT" "HT" "TT" "TY" ...

I would like to know what elements of the Matrix A are present in the Matrix B, and to do this I wrote this code.

Matrix_B$Results <- ifelse((Matrix_A$R %in% Matrix_B$R),
                           ifelse((Matrix_A$NS %in% Matrix_B$NS),1,0))

This dosen't give me a error, but the result is not correct.
I tried this

Matrix_B$Results <- ifelse((Matrix_A$R %in% Matrix_B$R) &
                        (Matrix_A$NS %in% Matrix_B$NS),1,0))

but dosen't work.
Comment: The other possible dupe is [Why are these numbers not equal?](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal). See column `Matrix_A$NS`.
Comment: @phiver i don't think this question directly asks about `merging`.
Could you please give me a feedback about my solution?
Comment: I think that is not a duplicate, because I don't want to join these two table.
I would like to know if one element of Matrix A is present in Matrix B.
But maybe the correct way is to use the merge or join.
Answer:
I would like to know what elements of the Matrix A are present in the
  Matrix B

Indeed it is subtraction of two collections:
A<-matrix( sample(1:5,12,replace = T ), 4, 3)

 B<-matrix( sample(1:10,10,replace = T ), 2, 5)

So, the matrix A, and B could be:
> A
     [,1] [,2] [,3]
[1,]    4    3    3
[2,]    2    1    5
[3,]    4    4    5
[4,]    1    4    4
> B
     [,1] [,2] [,3] [,4] [,5]
[1,]    4    3   10    8    9
[2,]    1   10   10    9    6

Now if you wish to know, which elements are in both matrixes, you have 2 options:
Approach 1:
intersect(B,A)

Approach 2:
existInANotB<-setdiff(A,B)
intersect<-setdiff(A,existInANotB)

Comment: Thank you for your answer, but I'm studying  another solution. Have a good day.
Comment: thank you for your answer.
My problem is to know which element is present in both Matrix.
Comment: @Francesco is it good now?


While loop designed to break on null user entry, doesn't break on null user entry

Question: I'm making an app that lets people make surveys. My idea is to let people enter unlimited choices for a question, and to signal when they're done with that question by pressing Enter on a new line, at which point I let them enter the next question and that question's choices. I thought that pressing Enter on an empty line would result in a null, and wrote the while loop condition to break on null, but as the code is, below, it doesn't break on null, but carries right on asking users for more choices. Then I thought maybe an empty line is actually "" instead of null. But when I do that...NullPointerException. I hope I'm making sense here.
Essentially, the question is, how do I make the inner loop break and proceed to the next iteration of the outer loop?
Thanks!
public class Survey implements Serializable {
    String title = "";
    ArrayList<Question> questions;
    String surveyFileName;
//survey entry code
//entry is a Scanner defined in the Main class
while ((currentQn.questionContent = (Main.entry.nextLine())).equals("") == false) {
            currentQn.choices.clear();
            System.out.println("Please enter the text of question " + currentQnNo + ": ");
            String currentChoice = "";
            int currentChoiceNo = 1;
            System.out.println("Please enter choice " + currentChoiceNo + " for question " + currentQnNo + ": ");
            while ((currentChoice = (Main.entry.nextLine())) != null) {
                System.out.println("Please enter choice " + currentChoiceNo + " for question " + currentQnNo + ": ");
                currentQn.choices.add(currentChoice);
                currentChoiceNo++;
            }
            currentQnNo++;
            questions.add(currentQn);
        }

and here's Question's implementation:
package surveyor;

import java.io.Serializable;
import java.util.*;

class Question implements Serializable {
    public String questionContent = ""; //initialize these so no NPEs
    public ArrayList<String> choices = new ArrayList<String>();

}

Comment: Please stop calling empty strings ("") `null`.  They aren't null, they're empty.  There's a difference.
Comment: Yes, there's a difference. Then which one does Scanner get when you press Enter? Empty string, or null? That's my question.
Comment: Which line in your program raises the `NullPointerException`?
Comment: This should be very simple to test in a simple main() method - call Scanner.nextLine() and print "null!" or "empty!" depending on the return value
Comment: She isn't calling empty strings `null`. She originally thought `nextLine()` would return `null` for an empty line, but then decided it must return an empty string.
Comment: @erickson: great question. That's exactly the problem! The NPE was thrown when I added the new question to the ArrayList of questions, not when entering data. Also, what makes you think I'm a "she"? :P
Comment: Enter usually corresponds to carriage return or carriage return + new line, and this varies by platform. http://en.wikipedia.org/wiki/Newline http://lists.samba.org/archive/samba/2001-January/023997.html
Comment: Additionally, this is a very basic and ugly implementation. Suggest you refactor it to : create a method to make a question, create a method to make choices, create a class Choices and have Question have an ArrayList of that (this allows you nice things, like the ability for multiple selections via an boolean isValid property in the Choice class, etc)
Answer: before inner while loop
 bool shouldContinue = false;

in inner while loop
if ("".equals(currentChoice.trim())) {
    shouldContinue = true;
    break;
}

after inner while loop
if (shouldContinue) continue;

Answer: Whoops, never mind. The NPE was not for the empty string. It was for the ArrayList<Question> questions, which wasn't initialized. Scanner indeed gets an  empty string, not null.


Difference between creating an object within the constructor vs outside of the constructor?

Question: Within my program, I am trying to create a toolbar within a frame. Within the toolbar, I have three buttons that are represented with a picture instead of text.
The problem is that I have found that there is a difference in how the buttons are displayed if I create the JButton objects within the constructor, compared to if I did this outside of the constructor (but still within the JFrame class).
My code when I create the buttons within the constructor :
public class Tool extends JFrame
{
    public Tool()
    {
         JToolbar bar = new JToolBar();

         JButton button1 = new JButton(img1);
         JButton button2 = new JButton(img2);
         JButton button3 = new JButton(img3);

         bar.add(button1);
         bar.add(button2);
         bar.add(button3);
    }
}

Then the buttons are added nicely and neatly to the toolbar.
However, if I do this:
public class Tool extends JFrame
{
     JButton button1 = new JButton(img1);
     JButton button2 = new JButton(img2);
     JButton button3 = new JButton(img3);

public Tool()
        {
             JToolbar bar = new JToolBar();

             bar.add(button1);
             bar.add(button2);
             bar.add(button3);
        }
 }

Then, the buttons are still added to the toolbar. BUT instead of being formatted nicely, they seem to have a border around them (similar to if you just copied an image off of google and paste it onto a powerpoint presentation, for example, and you get a square border around the image).
Why is this the case? Why does it matter where I create the JButton objects?
Thank you in advance.
Edit (complete CORRECT code):
In the code below, button1 and button2 are created within the constructor, whereas button3 is created outside of the constructor. As you can see, there is a faint white border around the button with the text "Java", compared to the two other buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Tool extends JFrame
{
        JButton button3 = new JButton("Java");

    public Tool()
    {
        super("Tool");
        setLookAndFeel();
        setSize(370, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button1 = new JButton("Help");
        JButton button2 = new JButton("SOS");

        //build toolbar
        JToolBar bar = new JToolBar();
        bar.add(button1);
        bar.add(button2);
        bar.add(button3);

        // build text area
        JTextArea edit = new JTextArea(8, 40);
        JScrollPane scroll = new JScrollPane(edit);

        // create frame
        BorderLayout border = new BorderLayout();
        setLayout(border);
        add("North", bar);
        add("Center", scroll);
        setVisible(true);
    }

    private void setLookAndFeel()
    {
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        }
        catch(Exception e)
        {

        }
    }

    public static void main(String[] arguments)
    {
        Tool loot = new Tool();
    }
}

Comment: I don't see any functional difference between them. BTW, what are `img1`, `img2`,..
Comment: Post compilable code, and explain how it's less attrractive. We can't see your screen.
Comment: There is no functional difference, but it changes the display in a way that is less attractive (if I create the objects outside of the constructor). Sorry, img1, img2, and img3 are images that represent the buttons in the GUI (they are created in the JFrame class as well).
Answer: In the first case, you just have three local variables declared in the constructor.
In the second case, your Tool class has three fields. You can then refer to those fields in other methods, and they are part of the state of the object.
That's a significant difference in itself, but shouldn't affect the behaviour in itself. However, it also affects the timing of when the JButton instances are created - when they're fields, the initializer is being executed before you call setLookAndFeel and before you call setSize.
After experimenting a bit, it seems that it's the look and feel which is important here. I suggest you change your code to make setLookAndFeel a static method, and then call that from main before you create any GUI components. You'll then get a consistent experience. (I would suggest only catching UnsupportedLookAndFeelException and ReflectiveOperationException, and at least logging any exception, instead of just continuing without any trace of what's wrong, too...)
Comment: Why does this change the appearance of the GUI though, with respect to the buttons on the toolbar?
Comment: @vmck: As I say in my edited answer, given that you don't do anything with the `bar` variable, I'm surprised that a toolbar is created at all. It would really help if you'd post complete code so that we can reproduce the issue.
Comment: I have posted the complete correct code (the difference is small, it's what I stated in the original question). However, I think you'd need three images saved to be able to run it the way I did... or do you want me to change that so that the buttons are represented by text in the GUI and not images?
Comment: @vmck Could you post screenshots of a comparison of the GUI differences you are seeing?
Comment: I just tried... apparently I don't have enough reputation. If the object is created outside of the constructor, there is a thin white border around it, compared to the other buttons that ARE created within the constructor.
Comment: @JonSkeet  I have edited my question to include new text with buttons with text.
Comment: @JonSkeet Does it have something to do with the size and look and feel?
Comment: @JonSkeet Sorry, I don't understand. You want me to create a new Tool object in the main and then use that object instance to call the setLookAndFeel() method?
Comment: @vmck: No, I said to make the `setLookAndFeel` method `static` (it doesn't use `this` at all) and then call it from `main`. Once it's `static`, you don't need to create an instance of the class in order to call the method. (I wouldn't just swallow the exception, mind you...)
Comment: @JonSkeet Wow thank you so so much. But if I may ask, why exactly DID that work?
Comment: @vmck: Because when you create a UI component, presumably it looks at the current look and feel to find out various aspects of how it should look. Changing look and feel when you've already created some of the UI therefore ends up with some components using one L&F, and others using a different one...
Comment: @JonSkeet so what does static mean? (Sorry I'm really new at this)
Comment: @vmck: At this point you should look in a good Java book. This is a fundamental part of understanding Java, and can't be adequately dealt with in comments on a question which is about something entirely different...
Comment: @JonSkeet okay. I'm currently trying to teach myself this language. Are there any good Java books that you recommend?
Comment: @vmck: It's been a long time since I've looked at any beginner books, so I wouldn't know what to recommend, but this is now *way* off topic for your question. You might want to ask in the Java chat room. You should also read the Java Tutorial: http://docs.oracle.com/javase/tutorial/