Pythonic way to name derived classes

Question: I can't figure out what is the more acceptable naming convention for derived
classes. Let's say we have a base class Fruit, from which we derive, classes for apple,
orange and passion fruit. It is a concensus that the name of the base class should appear in the
derived ones, but should it appear in the beginning of the class name or at the end?
Which is more Pythonic: FruitApple, FruitOrange and FruitPassionFruit or AppleFruit,
OrangeFruit and PassionFruitFruit?
Comment: "It is a concensus that the name of the base class should appear in the derived ones ..." - really? It makes sense in many cases, sure, but I don't think it's imperative. The `Fruit` in `AppleFruit` doesn't add any information. The `FruitPassionFruit` is particular atrocious. Also, you can only take this so far in larger hierarchies. You don't include `object` in all your class names, do you?
Comment: Maybe others will disagree, but I would just go with `Apple`, `Orange`, and `PassionFruit`.  The purpose of the name of the class is to give an idea of what it does, not to list implementation details.  Besides, if you decided that `OrangeFruit` should derive from `CitrusFruit`, you wouldn't want to have to rename it to `OrangeCitrusFruit` everywhere.
Comment: Do you really think [`gtk.ColorSelectionDialog`](http://developer.gnome.org/pygtk/stable/class-gtkcolorselectiondialog.html) should be renamed to `gtk.ColorSelectionDialogWindowBinContainerWidgetObject`? :)
Comment: @SvenMarnach: Non! `ObjectWidgetContainerBinWindowDialogSelectionColor` sounds *so* much better!
Comment: The ``Fruit`` in ``AppleFruit`` may seem to add no information but I presume your real use case doesn't involve fruit and that multiple class hierarchies may need to exist side-by-side. :-)  Sometimes toy examples don't lead to good general purpose rules that apply to more complex software.
Answer: Use common sense.
In your example,  as others have discussed, the Fruit part is obviously redundant. Use just Apple, Orange, etc. Let's consider use another example instead.
If I had a base class called Plugin, I would name the derived class FormattingPlugin, which I read as "plugin that does formatting". The alternative, PluginFormatting, reads as "formatting of plugins". I guess the reading is subjective, so use your own best judgment.
But don't name it just Formatting, because, unlike in the fruits example, that's not a complete enough description of what the class does.
Answer: "Concensus" is an elusive concept.  What you can do though is look to naming conventions used in the standard library to get a sense of what is the norm within the Python community.
For example, here's one extensive list of related classes and subclasses:  http://docs.python.org/library/internet.html
In the end though, it is a matter of taste guided by the principle that class names which are the clearest to the user are the best names.
Answer: In the specific example you list above, everyone knows these things are fruits, so I think it is unnecessary to include Fruit in the subclass names.
More generally, whatever you chose is fine as long as it is consistent.
I tend to like the French way of naming the object first and descriptors (adjectives) afterwards, so if I had to choose, I would prefer FruitApple, FruitOrange, etc. over AppleFruit, OrangeFruit (and the redundant PassionFruitFruit :)). It also has the advantage of showing all the subclasses in a cluster when listed alphabetically, which might help some IDEs or code completers.
If, on the other hand, you take the standard library as the model, you'll find a preference for naming subclasses in SpecificBase format. For example, the logging module defines StreamHandler and FileHandler as subclasses of Handler.
Comment: The flip side of showing all the subclasses is that you have to type more until the name is unique and you can tab-complete it.

Pythonic way to name derived classes


Where are the windows firewall logs stored?

Question: I don't know where Windows 7 stores the logs for the windows firewall. Can anybody tell me? Thanks in advance.
Answer: %systemroot%\system32\LogFiles\Firewall\pfirewall.log


C / Como trocar o for por um while?

Question: Escreva a função imprime usando a estrutura de repetição while ao invés de for. Caso necessite posso editar e inserir todo o código.

void imprime(Ccc *p)
{
    Ccc *r;
    for (r = p; r!=NULL; r = r->proximo)
        printf("%c",r->caracter);
}

Completo
#include <stdio.h>
#include <stdlib.h>

typedef struct ccc {
    char caracter;
    struct ccc *proximo;
} Ccc;

void imprime(Ccc *p)
{
    Ccc *r;
    for (r = p; r!=NULL; r = r->proximo)
        printf("%c",r->caracter);
}

void liberar_memoria(Ccc *p)
{
    Ccc *q, *r;
    q = p;
    while (q!=NULL) {
        r = q->proximo;
        free(q);
        q = r;
    }
}

main()
{
    Ccc *p1, *p2, *p3;

    p1=(Ccc *)malloc(sizeof(Ccc));
    p2=(Ccc *)malloc(sizeof(Ccc));
    p3=(Ccc *)malloc(sizeof(Ccc));

    if ((p1==NULL)||(p2==NULL)||(p3==NULL))
        return;

    p1->caracter='A';
    p1->proximo=p2;

    p2->caracter='L';
    p2->proximo=p3;

    p3->caracter='O';
    p3->proximo=NULL;

    imprime(p1);
    liberar_memoria(p1);
 }

Comment: Mas a pergunta que eu fiz foi "Poderia descrever com palavras o que você entendeu sobre a função do `for` nesse código", não "por favor, poste o código completo", embora possivelmente será melhor com o código completo.
Comment: Você entendeu o que o `for` está fazendo? Poderia descrever com palavras?
Comment: Sim,vou postar o código completo.
Answer: A diferença entre o for e o while, é que o for permite que se faça atribuição e declaração de variáveis somente dentro daquele escopo, então o for irá realizar tanto a verificação da condição como a atualização do "indicador" automaticamente, não sendo necessário colocar dentro do escopo
Já o while só irá verificar uma condição simples e já irá para o escopo, então qualquer atribuição ou declaração de variável deve ser feita depois do formato
while (condição){
   (escopo);
}

entao seu codigo será:
 void imprime(Ccc *p){
    Ccc *r;
    r = p;
    while(r!=NULL;){
      printf("%c",r->caracter);
      r = r->proximo;
    }
 }

Comment: acho que seu código responde a pergunta, sim; só uma observação de que é possível tanto usar variáveis de escopo _"extra for"_ quanto apenas no escopo _"dentro do while"_, mas isso seria outra discussão :P de qualquer forma, existem várias leituras interessantes sobre escopo de variáveis, [como esta](http://linguagemc.com.br/funcoes-e-escopo-de-variaveis/)
Comment: Correto! só o ponto e virgula depois do NULL que acusou erro, removi e tudo certo while(r!=NULL;)...

C / Como trocar o for por um while?


Using Ruby Watir, how can I select a checkbox that has a changing ID?

Question: This is the HTML I'm working with:

                    Becomes Asset

                    <input id="00Ni0000003bw8O" type="checkbox" value="1" tabindex="8" name="00Ni0000003bw8O" checked="checked">

I need to select the checkbox.
I cannot use the ID because I'm doing this across multiple orgs, and the ID is different in every org.  Is there a way I can select by the label text or by the tabindex?
Answer: It is probably safer to get the checkbox by the label text rather than the tabindex.
Solution 1 - :label locator:
If you are using watir-webdriver, it possible to locate an element directly based on its label text - via the :label locator. You can do the following:
#Exact match of label text:
b.checkbox(:label => 'Becomes Asset').set

#Partial match of label text using regex:
b.checkbox(:label => /Asset/).set

Note that this assumes that the 'for' attribute of the label matches the 'id' attribute of the input element.
Solution 2 - Matching label to input:
For a solution that works in watir-classic (as well as watir-webdriver), you can:

Get the label element by text
Get the for attribute of the label element
Get the associated checkbox by its id, which matches the label element's for attribute

The following will work for your page to clear the checkbox:
label = browser.label(:text => 'Becomes Asset')
browser.checkbox(:id => label.for).set

Comment: FYI, locating by :label checks "for" attribute or if label is parent. See https://github.com/watir/watir-webdriver/issues/200 for details.
Comment: Thanks for the link @p0deje. From the watirspec changes I realized that watir-classic also supports the :label locator. However, I would argue that there are some bugs, which is why it does not work in this scenario. I hope to finish investigating and reporting the issue(s) this weekend.
Comment: [Issue 56](https://github.com/watir/watir-classic/issues/56) has been opened for the :label locator not working in watir-classic.
Answer: To select the checkbox based on the tabindex, using a :css or :xpath locater should do the trick:
b.checkbox(:xpath => "//input[@tabindex='8']").set
b.checkbox(:css => 'input[tabindex="8"]').set


Show that a Torus has an Isometry of Order4.

Question: If the fundamental region for a torus T is a square, show that T has an isometry of order 4 induced by a rotation of the plane.
Secondly, if the fundamental region is a rhombus with angles $\pi/3$ and $2\pi/3$, show that T has an isometry of order 6 induced by a rotation of the plane.
We have defined the torus T as T=$R^2$$ /  \Gamma$, where $\Gamma$ is generated by two linearly independent translations, $t_1$ and $t_2$. The fundamental region of a T is a parallelogram, but in this special case we are assuming that this parallelogram is actually a square. I have no clue where to start with this problem, so any help is appreciated.
Answer: Suppose $R^2$ is generated by $u,v$ and $\Gamma$ is generated by the translations $t_u$ and $t_v$. The linear map $f$ defined by the matrix $A=\pmatrix{0 & -1\cr 1& 0}$ in $u,v$ is the matrix of the rotation of angle ${\pi\over 2}$.
Since $f\Gamma f^{-1}=\Gamma$, $f$ induces an automorphism of $T^2$. Its order is 4.
Comment: I don't know why the matrix A is the matrix of the rotation $\pi/2$
Comment: $\pmatrix{ cos(\theta) & -sin(\theta) \cr sin(\theta) & cos(\theta)}$ is the matrix of the rotation of angle $\theta$. Take $\theta=\pi/2$.
Comment: Got it. That part makes sense now. How does this lead us to conclude that the order of f is 4 though?
Answer: You can evaluate this explicitly using complex algebra and roots of unity.
Since all that matters is the square's shape, we can WLOG assume $\Gamma$ is generated by $t(z)=z+1$ and $t_2(z)=z+i$. We wish to show the rotation $r(z)=iz$ induces an isometry of order $4$ in $\mathbb{T}=\mathbb{C}/\Gamma$.
Let $$z=a+bi,\quad u=c+di$$ be points in the fundamental square $S$. The distance between any two $\Gamma$-orbits of $z$ and $u$ is $$d(z',u')=\sqrt{(a+N_1-c-N_2)^2+(b+N_3-d-N_4)^2},\tag{*}$$ where $N_i\in\mathbb{Z}$. Under the rotation $r$ we get $$rz=-b+ai,\quad ru=-d+ci.$$ The distance between $\Gamma$-orbits of rotated points is $$d(rz',ru')=\sqrt{(b+N_3-d-N_4)^2+(a+N_1-c-N_2)^2}\tag{**}.$$ As the minimums of $*$ and $**$ are equal, $r$ induces an isometry of $\mathbb{T}$.
To show $r$ has order $4$, it suffices to follow the orbits of $z\in S$ under rotation. Note that, after a rotation of $\pi/2$ radians any point of $S$ will have shifted into the square on the left. Thus to work out repeated rotations in $\mathbb{T}$, each $r$ must be followed by a $t$, and the problem reduces to showing $$trtrtrtr(z)=z.$$ This is straightforward: $$tr(z)=iz+1$$ $$tr(iz+1)=-z+i+1$$ $$tr(-z+i+1)=-iz+i$$ $$tr(-iz+i)=z.$$
This setup also works for the case that the fundamental region is a rhombus $R$ with angles $\pi/3$ and $2\pi/3$. Some extra care is required this time, but not much, and it unearths a neat connection between tori and the roots of unity.
This time, let $$t(z)=z+\omega,\quad t_2(z)=z+\omega^2$$ where $\omega=e^{\frac{i2\pi}{3}}$ is a cube root of unity. We consider the rotation $r$ of $\pi/3$ radians about the origin. We will show $r$ maps $\Gamma$-orbits to $\Gamma$-orbits and thus is an isometry. Let $a=e^{\frac{i\pi}{3}}$.
For a rotated point $rz$ $$\Gamma rz=\{az+n\omega+m\omega^2:n,m\in\mathbb{Z}\}.$$ Let $z'\in\Gamma z$, then $$rz'=az+aN\omega+aM\omega^2$$ $$=az-N-\frac{M}{\omega^2}$$ $$=az+(\omega+\omega^2)N-M\omega $$ $$=az+(N-M)\omega+N\omega^2 .$$ Thus $rz'\in\Gamma rz$ and we conclude $r$ induces an isometry in $\mathbb{T}$.
So, we are left to show the order of $r$ in $\mathbb{T}$ is $6$.  Let $z$ be a point in the upper half of $R$, then the figure below shows that $tr^2(z)$ is a point in the upper half of $R$. Hence, we need only show $$tr^2tr^2tr^2(z)=z,$$ which follows once again from some simple properties of cube roots of unity: $$tr^2(z)=\omega z+\omega$$ $$tr^2(\omega z+\omega)=\omega^2z+\omega^2+\omega$$ $$tr^2(\omega^2z+\omega^2+\omega)=z+1+\omega+\omega^2=z.$$ The case for $z$ in the lower half being essentially the same, we conclude the result.

Clearly, Tsemo's proof via group actions is a slicker path to the result. There is something nice, however, about "seeing" the two geometries differ and connecting this to the roots of unity. I doubt this method would work for general $n^{th}$-roots of unity (maybe $6^{th}$), since really we were exploiting symmetries of regular tilings of the plane, of which there are only three (square, equilateral triangle, and hexagon). Basically, we used the  neat algebraic properties of the Gaussian and Eisenstein rings.


No module named 'polls.apps.PollsConfigdjango'; Django project tutorial 2

Question: So, I've been following the tutorial steps here https://docs.djangoproject.com/en/1.9/intro/tutorial02/ and I got to the step where I am supposed to run this command:
python manage.py makemigrations polls

When I run it, I get this error:
python manage.py makemigrations polls
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 2218, in_find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/tgumm/pythonenv/tutorial/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
  File "/home/tgumm/pythonenv/tutorial/lib/python3.4/site-packages/django/core/management/__init__.py", line 327, in execute
django.setup()
  File "/home/tgumm/pythonenv/tutorial/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/tgumm/pythonenv/tutorial/lib/python3.4/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
  File "/home/tgumm/pythonenv/tutorial/lib/python3.4/site-packages/django/apps/config.py", line 116, in create
mod = import_module(mod_path)
  File "/home/tgumm/pythonenv/tutorial/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2212, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_an``d_load
  File "<frozen importlib._bootstrap>", line 2221, in _find_and_load_unlocked
ImportError: No module named 'polls.apps.PollsConfigdjango'; 'polls.apps' is not a package

Here are my models:
from django.db import models

# Create your models here.
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Answer: The first problem is this warning in the traceback:
No module named 'polls.apps.PollsConfigdjango'

That means that you are missing a comma after 'polls.apps.PollsConfig in your INSTALLED_APPS setting. It should be:
INSTALLED_APPS = (
    ...
    'polls.apps.PollsConfig',
    'django....',
    ...
)

The second problem is the warning 'polls.apps' is not a package. That suggests that you have installed Django 1.8, but you are following the Django 1.9 tutorial.
If you are using Django 1.8, then follow the 1.8 tutorial so that you don't hit problems like this. Adding the polls app to INSTALLED_APPS is covered here in the Django 1.8 tutorial. Note that it doesn't use PollsConfig.
INSTALLED_APPS = (
    ...
    'polls',
)

Comment: Commas and Semi-Colons are nightmares.
Comment: OMG - YES!  :ROFL:
Comment: I had almost the exact same problem.   But, for me I had misspelled my class name.   And ShogunT, if the answer solves your problem, will you accept the answer?
Comment: This is the right answer for the question... I had made exactly the same mistake as the OP.  I don't think I've ever seen so many "almost right" other answers coming and confusing the "comma issue" ... add to that that yours was the first answer chronologically.  Odd.
Answer: ImportError: No module named 'polls.apps.PollsConfigdjango'

You forgot to add ',' in the list
Answer: check for comma "," after 'polls.apps.PollsConfigdjango'
Comment: Awesome. Fixed my issue!
Answer: You just missed a comma after 'polls.apps.PollsConfig'.
Don't worry, it happens for the best of us!
Answer: Anyone who is getting
ModuleNotFoundError: No module named 'pollsdjango'
And INSTALLED_APPS :
INSTALLED_APPS = [
    'polls.apps.PollsConfig'
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Solution:
You forgot to add comma(,) at the end of line 'polls.apps.PollsConfig'
INSTALLED_APPS = [
    'polls.apps.PollsConfig', <----this comma
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Answer: Quoted from https://code.djangoproject.com/ticket/27139
Description
In tutorial 02, Writing your first Django app, part 2, typing in
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
   ....

will cause an ImportError: No module named 'polls.apps.PollsConfig'; 'polls.apps' is not a package
This is resolved by instead putting
INSTALLED_APPS = [
    'polls',
   ....

Comment: Solved my problem. But my django version is 2.0.4, python version 3.6.5. According to the document, django will generate apps.py since version 1.9 ...So don't know why
Answer: I was getting a similar error: ImportError: No module named 'polls'
The cause was that I stored my apps inside the "apps" directory.
The solution is to change the code inside apps.py
from:
class PollsConfig(AppConfig):
    name = 'polls'

to ("apps" is the name of my django apps directory):
class PollsConfig(AppConfig):
    name = 'apps.polls'

Answer: you forget to add "," after  'polls.apps.PollsConfig'  ","
must include a comma "," ... 'polls.apps.PollsConfig',
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: If you come from Django Tut here's the problem You just missed a comma after 'polls.apps.PollsConfig'. so it should be
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    ....
]

Answer: If none of the above/below fix your problem and you came here with the same errors make sure that you do not have a __init__.py in your top level directory. Hope this helps someone out there!
Answer: If we are getting error regarding not a package than most of the time it may happen that we missed to add __init__.py file within the directory where we are getting this error.


probability of sequential, exponential and independent events

Question: My question is related to my job and asking to learn.
Simplified case is:
Event A and Event B failure rates are exponentially distributed.
Event A (failure of item A) => failure rate (lambda): 0,0002
Event B (failure of item A) => failure rate (lambda): 0,0008
for a duration of 500.
I want to understand the probability that both events occurs but event A occurs before event B.
Event A and B are independent. One does not trigger (not change the prob.) the other.
I made 200,000 trials monte carlo sim. and get 0,01533 for probability that both events occurs but event A occurs before event B.
Q1) But where is this coming from? What is the analytical solution for this case?
Q2) Which specific statistics topic  should I read on web if the number of sequential items increases and the problem gets more complex?
thanks
Comment: Do you know how to apply conditioning?
Comment: Hi Soakley, thanks for dealing. If you mean conditional prob., yes I'm aware of it but here I think *Prob B given that A already occured* which is *P(B)* because of independence won't help me. I can understand the answer (if provided) but I'm stucked to create mine since I'm an engineer (not a statistician) and it's been 15-16 years since I got 2 semester of statistics courses. Can you please lead me? Thanks again.
Answer: If we let $X$ be the time until event A and $Y$ be the time until event B, then both $X$ and $Y$ have exponential distributions (let's call their rates $\lambda_1$ and $\lambda_2,$ respectively) and it appears you want to find $P[X < Y, X<500,Y<500]$
We know by independence that the probability that both $X$ and $Y$ are less than 500 is given by $T=\left( 1-e^{-500 \lambda_1} \right) \left( 1-e^{-500 \lambda_2} \right)$
I'm not sure why I did it this way, but within the domain (a square) of both variables being less than 500 I found the complementary area $U=P[X>Y, X<500, Y<500]$ to what you are interested in by using a double integration.
Then your desired quantity is $T-U.$
I found that to be
$$T-U =\frac{1}{\lambda_1+\lambda_2} \left[ \lambda_1 + \lambda_2 e^{-500 \left( \lambda_1 + \lambda_2 \right) } \right]-e^{-500 \lambda_2} $$
For your rates this evaluates to $0.0149045,$ in good agreement with your simulation result.
Now let's set up the direct approach. We want to evaluate the probability that $X<Y$ constrained by both variables being no more than 500. Call the answer $Q.$
$$Q=\int_0^{500}\int_x^{500}\lambda_1 e^{-\lambda_1x} \lambda_2e^{-\lambda_2y} \ dy \ dx$$
If you solve this, you will get the same answer as above. Can you take it from here?
Comment: I think the event of interest is not $X<Y$ but $X<Y<500$
Comment: Ah, I couldn't figure what the "duration of 500" meant.
Comment: @soakley  It's good to see that my simulation result is acceptable and the solution has a closed form. However *what I couldn't understand was how to deal with P(X<Y)* and I didn't understand the **U**. I suppose integrals are using the **PDF** function so I also couldn't get the idea of double integral because in my mind a double integral of a line will give a volume and I couldn't match a volume with my question logically. (I drawed the PDFs and tried to see the geometry but...) Sorry for bothering and taking your time.
Comment: @soakley Can you please give the integrals or describe the geometry in your mind **for U or for P(X<Y)**. I can get it in that way. As I've said I want to understand the logic, not only got the answer in numbers. Thanks for your efforts.


how to start a proof of a system of congruences

Question: Let $a$, $b$, $m$, and $n$ be integers with $m > 0$, $n >0$, and $gcd(m,n) = 1$. Then the system $x\equiv a$ (mod n) and $x\equiv b$ (mod m) has a unique solution modulo mn.
This is not the Chinese Remainder Theorem just yet. That is the next proof. This is a proof leading up to it.
Help please!
Comment: Try using $x = mq + b$ and using $mq + b \equiv a$ (mod n)
Comment: Do you want to show *existence* too, or only *uniqueness*. If both then it is already CRT.
Comment: For some people CRT is for a general system, and a $2\times 2$ system is the lemma that makes the proof simple.
Comment: This is just the uniqueness.
Comment: @vadim123 Right, the many variations on what CRT denotes are almost too many to count.
Comment: The previous theorem states, the system $x\equiv a$ (mod n) and $x \equiv b$ (mod m) has a solution if and only if $gcd(n,m) | a-b$. It may be useful to use?
Comment: @Franky That yields the *existence* of solutions. This exercise yields the *uniqueness*. Presumably the next exercise combines them into CRT. Do you already know that $\, m,n\mid k\,\Rightarrow\,{\rm lcm}(m,n)\mid k\, ?\ \ $
Comment: We know that $gcd(a,b) \times lcm(a,b) = ab$.
Comment: @Franky From that you have $\ m,n\mid k\,\Rightarrow\,mn\mid mk,nk\,\Rightarrow\,mn\mid \gcd(mk,nk)=\gcd(m,n)k\,$ therefore $\,{\rm lcm}(m,n) = mn/\gcd(m,n)\mid k.$ But there are [more direct,  conceptual ways](http://math.stackexchange.com/a/322153/242)
Comment: For more on lcm see [here](http://math.stackexchange.com/a/3149/242) and [here.](http://math.stackexchange.com/a/127344/242)
Answer: Hint $\ $ If $\,x',x\,$ are two solutions then $\,m,n\mid x'-x\,$ so $\ \ldots\mid x'-x$


Regular expression to match links containing "Google"

Question: I want to use PHP regular expressions to match out all the links which contain the word google. I've tried this:
$url = "http://www.google.com";
$html = file_get_contents($url);
preg_match_all('/(.*google.*?)<\/a>/i',$html,$links);
echo '
';
print_r($links); // it should return 2 links 'About Google' & 'Go to Google English'

However it returns nothing. Why?
Comment: The "problem" here is that you are using Regex when there perfectly good parsers and XPath available.
Answer: Better is to use XPath here:
$url="http://www.google.com";
$html=file_get_contents($url);

$doc = new DOMDocument;
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);
$query = "//a[contains(translate(text(), 'GOOGLE', 'google'), 'google')]";
// or just:
// $query = "//a[contains(text(),'Google')]";
$links = $xpath->query($query);

$links will be a DOMNodeList you can iterate.
Answer: You should use a dom parser, because using regex for html documents can be "painfully" error prone.
Try something like this
//Disable displaying errors
libxml_use_internal_errors(TRUE);

$url="http://www.google.com";
$html=file_get_contents($url);

$doc = new DOMDocument();
$doc->loadHTML($html);
$n=0;
foreach ($doc->getElementsByTagName('a') as $a) {
    //check if anchor contains the word 'google' and print it out
    if ($a->hasAttribute('href')  && strpos($a->getAttribute('href'),'google') ) {
        echo "Anchor" . ++$n . ': '. $a->getAttribute('href') . '
';
    }
}

Comment: wahoo~~  dom could do this. Thanks a lot. I learn some new one.
Comment: This is different from that the OP wants (at least by looking at his code). It seems he wants to get links where the *text* contains Google, not the URL. But as this is the accepted answer... either he didn't specify it correctly or does not care.


Problem with PCA in R (suspiciously high explained variance)

Question: I have always been confused about how to properly interpret PCA results.
My data looks like this and it's a big table with more than 5 million rows and 12 columns.(the first few lines are all 0...) Each column is for an individual which has more than 5 million observations (numbers).
<code>> head(data)
       YC1CO YC1LI YC4CO YC4LI YC5CO YC5LI YM1CO YM1LI YM3CO YM3LI
f1     0     0     0     0     0     0     0     0     0     0
f2     0     0     0     0     0     0     0     0     0     0
f3     0     0     0     0     0     0     0     0     0     0
f4     0     0     0     0     0     0     0     0     0     0
f5     0     0     0     0     0     0     0     0     0     0
f6     0     0     0     0     0     0     0     0     0     0
</code>
Then I run PCA using prcomp in R:
<code>pca<-prcomp(data,scale=T,center=T)
</code>
The outputs are:
pca$rotation:
<code>> pca$rotation
        PC1        PC2          PC3         PC4         PC5         PC6
YC1CO 0.2888377 -0.1511474  0.354970405 -0.14922899  0.29263063 -0.42756650
YC1LI 0.2887845  0.2891378  0.006931811 -0.11867753  0.10465221  0.32239652
YC4CO 0.2888937 -0.1073097  0.376083559 -0.16145206  0.28844683 -0.19929480
YC4LI 0.2888576  0.2899107  0.032538093 -0.10721970  0.11537841  0.19513249
YC5CO 0.2885639 -0.2200563  0.393267987 -0.13833481 -0.80160742  0.20303762
YC5LI 0.2887792  0.2926729  0.010423117 -0.11994739  0.12149153  0.31232174
YM1CO 0.2889243 -0.2483682  0.100978896  0.12858598  0.04456687 -0.19313330
YM1LI 0.2891586  0.2571790 -0.112257791  0.05154060 -0.01859997 -0.02233253
YM3CO 0.2872954 -0.5242998 -0.631712144 -0.47494155  0.05150495  0.08749259
YM3LI 0.2891991  0.2441790 -0.131464167  0.06272038 -0.03712138 -0.03534204
YM5CO 0.2881663 -0.3741525 -0.033566125  0.75538412  0.17427960  0.33801997
YM5LI 0.2886363  0.2481463 -0.369342316  0.27066649 -0.33590255 -0.57941556
        PC7           PC8         PC9        PC10        PC11
YC1CO  0.658953472 -0.0032299313  0.19565297  0.02889161  0.06028938
YC1LI  0.075935158  0.7256745487  0.10496762 -0.36161999 -0.17252148
YC4CO -0.733333390  0.0315817680  0.26028561  0.06764965  0.05879949
YC4LI  0.050613636 -0.0400665068 -0.25306478  0.74445447 -0.38210226
YC5CO  0.040387219 -0.0106509021  0.07336791  0.04776528  0.03597253
YC5LI  0.040072049 -0.6856737279  0.16012889 -0.41945134 -0.17527656
YM1CO -0.085165645 -0.0130678334 -0.78767928 -0.33407254 -0.22202704
YM1LI -0.004723194 -0.0087215382 -0.16061437  0.06378812  0.58204927
YM3CO -0.003226445 -0.0019793258  0.06649693  0.05308833  0.01803736
YM3LI -0.006287346 -0.0087025271 -0.14028837  0.03396984  0.52810233
YM5CO  0.048983778  0.0009123461  0.21714944  0.10450049  0.01040703
YM5LI -0.081931860  0.0139306658  0.26532068 -0.02864126 -0.34310790
              PC12
YC1CO -0.005335094
YC1LI  0.007632148
YC4CO -0.006459107
YC4LI -0.012083181
YC5CO  0.002861339
YC5LI  0.009554891
YM1CO  0.007425773
YM1LI  0.682200634
YM3CO  0.007334849
YM3LI -0.730105933
YM5CO  0.004956218
YM5LI  0.032252049
</code>
summary(pca)
<code>> summary(pca)
Importance of components:
                          PC1     PC2     PC3     PC4     PC5     PC6     PC7
Standard deviation     3.4418 0.20675 0.13369 0.11872 0.11105 0.10690 0.10325
Proportion of Variance 0.9872 0.00356 0.00149 0.00117 0.00103 0.00095 0.00089
Cumulative Proportion  0.9872 0.99072 0.99221 0.99338 0.99441 0.99536 0.99625
                          PC8     PC9    PC10    PC11    PC12
Standard deviation     0.10054 0.09888 0.09789 0.09215 0.08375
Proportion of Variance 0.00084 0.00081 0.00080 0.00071 0.00058
Cumulative Proportion  0.99709 0.99791 0.99871 0.99942 1.00000
</code>
The eigenvalues are:
<code>> pca$sdev^2
 [1] 11.845894818  0.042746822  0.017872795  0.014093498  0.012331364
 [6]  0.011428471  0.010660422  0.010107398  0.009777983  0.009582267
[11]  0.008490902  0.007013259
</code>
I just took the values from pca$rotation above for PC1 and PC2 and plot it.

And the biplot
<code>>biplot(pca)
</code>

I have a few specific questions and I would really appreciate it if you can comment to help me understand the plot.

Based on the proportion of variance, I know PC1 explains almost all the variance. I have one question here, does the x axis and y axis values matter at all here? PC1 values are much more closer than those of PC2 values although PC1 is the dominant PC.
Can I see the difference among points YC1CO, YC4CO, YC5CO and YM1CO, YM3CO, YM5CO are what drives PC1?
The initial thought was to show relationships among the 12 individuals (YC1CO, etc) and see if they cluster/separate from each other and if there is some meaningful patterns. That's why I want to plot PC1 and PC2 to show the relative location of 12 individuals. Now I'm confused about how to plot it..

Thanks!
Comment: The graph looks like the _loading plot_ which is showing variables in the space of PCs. The coordinates are loadings. If that is true, check that sum of the squared coordinates onto a PCs must be the variance (squared st. dev.) of that PC.
Comment: If the coordinates are _eigenvectors_ then their sum of squares for each PC is 1. [Read](http://stats.stackexchange.com/a/35653/3277) about what are eigenvectors and loadings.
Comment: @ttnphns, I have calculated the sum of the squared coordinates of the 6 points and it's about 1. So I think the coordinates are eigenvectors
Comment: @ttnphns if the coordinates are eigenvectors, are the values on the axises eigenvalues?
Comment: @ttnphns i think the plot is wrong.. the eigenvalues are pca\$sdev^2 which is the square of (3.4418, 0.20675, 0.13369 ...) and I think somehow the values on the axises are not the projection of each individual onto eigenvectors, which is what I want... they are from pca$rotation in prcomp package in R and they are loadings? but the sum of the squared coordinates is 1.. they seem contradictory...
Comment: @ttnphns in the prcomp site (http://stat.ethz.ch/R-manual/R-patched/library/stats/html/prcomp.html), it says rotation is the matrix of variable loadings and the first plot took values from the first two columns of rotation so I think they are indeed loadings and the sum of squares is 1. Right?
Comment: @user2157668: No, this does not make sense. The dimensionality of your space is 5 million, so the eigenvectors of the covariance matrix should be of that length. I guess you should transpose your data variable so that features are in columns! Alternatively, center your data yourself! Default centering by the prcomp function probably does not work, because it centers columns, not rows. This is my guess, as I do not know R.
Comment: @amoeba yeah, you made a good point. I've read a few more tutorials and they all say the observations/samples should be rows and variables should be columns. They all the above results/figures are just wrong. I also read that they say when the number of samples are smaller than that of variable (which is my case), PCA is technically impossible. So I shouldn't really use PCA I guess? maybe clustering makes more sense.
Comment: @user2157668: The statement that in your case PCA "is technically impossible" is wrong; it is still possible. I have no idea what the proper way of doing it in R is. However, if "pca$rotation" should contain eigenvectors when the input has variables in columns, it will most probably contain normalized principal components when the input has variables in rows (it's a mathematical trick, see [my answer here](http://stats.stackexchange.com/questions/101344/linear-pca-versus-linear-kernel-pca/101519#101519)). But you need to center the data manually before calling prcomp().
Comment: @amoeba right, i guess to make it right, I transposed the original data table and then used center=T in prcomp() and the result is a lot different. Now the first two PCs only explains < 50% of the variance..
Comment: @user2157668: Good. Does it solve your problem? Otherwise, I suggest you edit your question.
Comment: @amoeba I think it solved my problem although i'm not sure how to correctly interpret the meaning of the plots, need to do more reading I guess. some previous questions helped a bit like this one: http://stats.stackexchange.com/questions/62034/are-there-examples-of-more-informative-pca-plots
Comment: @amoeba thank you very much for the hints and help for the past few days!
Comment: @user2157668: No problem at all. However, it would be nice to mark this question as resolved, so maybe you could accept one of the answers (I have just provided one summarizing our discussion, but you can certainly accept any other).
Answer: Before your two numbered questions can be addressed:  Somehow PC1 has a standard deviation listed as 3.4, but all the values are shown as lying between .287 and .290.  There must be an error somewhere; this combination of results is not possible.  Perhaps you have graphed only of few of many points used in the PCA?
EDIT:  I say "not possible" because a standard deviation (here, 3.4) can be no greater than the variable's range (here, .003). And at an intuitive level the SD represents, informally, something like a "typical" deviation from the mean, whereas typical in this graph would be about .0005.
You asked about eigenvalues:  they summarize entire variables, whereas what's plotted on your graph are scores for individual points.
Comment: @user2157668: Can you please explain what you mean by "YC1CO etc are individuals and each has many observations (millions)"? Millions of observations -- are these data points or features? What is the original dimensionality of the dataset? How many data points are there in the dataset? If each individual contributes multiple data points, then how do you project individuals on the PC1-PC2 plane?
Comment: ok, i got what you meant,  why is the combination of results not possible..? what are the values of x axis and y axis? are they eigenvalues?
Comment: http://stackoverflow.com/questions/19993980/prcomp-function-in-r-rotation-values-difference-by-sign this example have similar small rotation values but ~2 standard deviation.
Comment: Since you referred to YC1CO, etc. as "points" I believed that they were observations/cases/individuals.  Are they actually variables?  In that case maybe what you've plotted is a set of variables' loadings on the components.
Comment: ...But even then it's hard to imagine how all variables could have PC1 loadings within such a tiny range.
Comment: sorry I didn't explain them. YC1CO etc are individuals and each has many observations (millions). so i'm trying to see the relationship among individuals with those observations. Those values on the axises are something I don't get either. They are from pca$rotation
Comment: My advice is not to try to interpret output from someone else's possibly inapplicable procedure, but to exert your own control.  Do you want to plot millions of observations?  compare individuals?  show relationships among variables?  Then choose a procedure (or design your own) to accomplish your goal.
Comment: @amoeba YC1CO is an individual and it has about 5 million values (numbers) and there other individuals have the same number of values and I have as input a big 5 million rows by 12 columns table. I just run PCA in R with prcomp(data,scale=T, center=T) on the above input and my understanding is each individual is projected based on the sum of all the values with in them. Does this sound OK to you?
Comment: @rolando2 I don't want to plot millions of observations and yes I want to compare individuals and see their relationship. PCA is a common tool used in the field and it does reduce those millions of dimensions into several..
Comment: @user2157668: Yes. So in machine learning jargon, you have 5 million features and 12 data points; you perform PCA and reduce the dimensionality from 5 million to 2. The problem is that it if PC1 accounts for 99% of the variance, the "spread" of numbers on the PC1 axis has to be quite a bit larger than on the PC2 axis. So either your figure, or your variance computations are **wrong** (likely the figure). That is precisely what rolando said in his reply.
Comment: @amoeba yeah, the comments by ttnphns on the question and my calculation seems to suggest the coordinates for eigenvectors, not loadings. does that mean the coordinate values of each individual are eigenvalues, they are not, right? how do i get the eigenvalues?
Comment: @user2157668: Ah! I think I have just had an eureka moment and realized what probably had happened: you did not center your data! So the sum of squares on PC1 is large, even though the variance is tiny. However, your last question shows that you are very much confused about the meaning of eigenvalues/eigenvectors/etc in PCA. I suggest you read something basic about PCA, maybe start with the highest voted questions with "pca" tag.
Comment: @amoeba yeah..i don't get PCA yet... but I did center the data, with the command in R: pca<-prcomp(data,scale=T,center=T)
Comment: @user2157668: Then I have no idea what is going on. Maybe you want to update you question and paste your full R code that you used to process the data and generate the figure. Then somebody who knows R (I do not) might be able to find the mistake.
Comment: @amoeba yeah, i should have put all the info there, just edited it. thanks!
Comment: @rolando2 i updated my question and the PCA i did was on scaled input data and i tried to set the scale to FALSE and the sdev of PC1 became 1.52.
Answer: I fully agree with what @rolando2 wrote, but let me add a bit to the discussion addressing the questions you posed.

Based on the proportion of variance, I know PC1 explains almost all the variance. I have one question here, does the x axis and y axis values matter at all here? PC1 values are much more closer than those of PC2 values although PC1 is the dominant PC.

It is not completely clear what you mean by matter, but yes, they do play a role. Once the your data is projected onto the PC, these are the new representations of the original data. But it is always tricky to compare in a two-dimensional way along two vectors with such a different standard deviation associated as PC1/PC2. Note that the PC are normalized by their own standard deviation, so a plot on the PC space will not reveal much of the original variation, in case that's what you're looking for.

Can I see the difference among points YC1CO, YC4CO, YC5CO and YM1CO, YM3CO, YM5CO are what drives PC1?

I think it is more correct to say that the difference between these points along the axis that defines PC1 are what let to the creation of PC1 as the most representative vector of the variance.
Hope this helps.
Comment: thanks. i was wondering the meaning of those axis values and whether bigger means higher variance... so in my plot, x axis values are much smaller than y axis although x axis is the first principle component
Comment: Indeed, bit to understand this one has to remove the normalization effect knowing the variance along the PC's.
Comment: @pedrofigueira: The variance of the e.g. PC1 projection *according to the OP figure* is definitely << 1, so I don't think it was normalized.
Answer: The confusion has already been clarified in the comments above, but I would like to provide an answer so that this thread can be closed.
R's function prcomp() takes as an input a data matrix with variables in columns. In your example you have variables in rows, which results in center=T argument not working correctly (it centers columns, not rows) and renders PCA invalid. The solution is to transpose the data matrix.


Is variance of mean equals mean of covariance?

Question: I am trying to finish a problem, my method requires to prove variance of mean equals mean of covariance, but I have trouble proving it. Is it correct? Or more condition needed?
Now I use $$Var(X)=E(X^2)-E(X)^2$$
$$Cov(X_i,X_j)=E(X_iX_j)-E(X_i)E(X_j)$$
but fail to show whether$$Var(E(X_i))=E(Cov(X_i,X_j))$$is true.
id.est.$$\frac{1}{n}\sum_{i=1}^{n}{(E(X_i)-E(X))^2}=\frac{1}{n^2}\sum_{i=1}^{n}\sum_{j=1}^{n}{Cov(X_i,X_j)}$$
It seems that this problem assumes$$E(X_i)=E(X)$$and$$Var(X_i)=Var(X)$$
$X_i$ is a finite set consisting of $n$ real numbers for each $i \in \left\{1,...,n\right\}$.
$X$ means the set of all $n^2$ real numbers from $X_1,...,X_n$.
Comment: Are you trying to ask if $$ \sum_i \left(E(X_i) - \sum_j E(X_j)\right)^2 =\sum_{i,j} Cov(X_i,X_j)$$ or some variant of this?
Comment: @CalvinKhor no...
Comment: Well as written, the answer below is right. Once you take an expectation, there is no more randomness. The expectation of a random variable is not random. Since variance is defined with expectations, the same is also true for variance. Maybe you want to consider conditional expectations?
Comment: @CalvinKhor but $Cov(X_i,X_j)$ is not a constant.
Comment: It is a constant. For each index $i$ and $j$. That is why I introduced a discrete sum which can be interpreted as making the index uniformly random
Comment: I think that expectation $E(\cdot)$ in this question is understood as the arithmetic mean value.
Comment: The pages of a book are numbered but they are not random. The same with Cov(Xi,Xj)
Comment: @NikPronko hence my comment above
Comment: @CalvinKhor do you mean $Cov(X_1,X_2)=Cov(X_1,X_3)$?
Comment: @user571299 absolutely not.
Comment: @CalvinKhor then the first line of the answer below is not right...
Answer: Counterexample. Suppose $n=2$, $X_1 = (1,0)$ and $X_2 = (1,0)$, so $X = (1,0,1,0)$. Then $X_1X_2 = (1,0) = X_1$ by multiplying the entries termwise, and under the interpretation that $\mathbb E((x_1,\dots,x_n)) = \frac{1}{n}\sum_{i=1}^n x_i$,
$$ \mathbb E (X_1) = \mathbb E(X_2) = \mathbb E(X) =1/2,$$
$$ \operatorname{Var}X_1 = \operatorname{Var}X_2 =  1/4, $$
$$\operatorname{Cov}(X_1,X_2) = \operatorname{Cov}(X_2,X_1) = E(X_1 X_2)-E(X_1)E(X_2) = 1/4, $$
So $\text{LHS} = 0$ but $\text{RHS} =1/4 $.


Good books for romantic/contemporary period performance?

Question: Can anyone suggest me good books for improving knowledge (and performance) of 19th and 20th century music?
Comment: What instrument? Level? Country of origin?
Comment: Orchestral, opera genres. High level. Western world.
Answer: The Memoirs of Hector Berlioz.
Everyman's Library Edition is excellent.
This is an amazing book, not a history book, but a book that describes in vivid detail the emotions that inspired Berlioz's music, and gives a detailed account of what his life was like as a major composer in 19th century Europe. Most importantly, it is a very entertaining read.


Allow shared folder access only to specific clients

Question: I am kind of new to networking and I am trying to resolve the following situation. I tried to find a solution but I couldn't find anything proper that suits my needs. Maybe anyone here could give some clarification whether it's possible or not in the first place.
The Situation:
At home I have set up a Windows Server 2008 R2 standard edition mainly as a file server.
I added some shared folders for everyone at home to access. Including a folder backup.
In that folder there is a sub folder for every family member at home. Right now, everyone is able to access all folders without asking for username / password.
What I want
That when someone tries to access the backup folder for user1, that it asks for the credentials of user1 (accessed from his/her desktop). So that only the specific user is able to access his or her backup.
I tried

Creating an account for every user and give only that user rights on the shared folder.
Changing the shared settings of the backup-folder itself.
Re-sharing the user1backup folder for that user only, but this creates a complete new share (and still doesn't work).

Would it be possible to prompt for username/password (which the account has been manually made on the server) when someome tries to access that folder?
If not, are there any alternatives for this (third party tools, other methods) which someone could point out to me?
Answer:
Every user will need a separate account. (All access control in Windows is based on users.)
Decide to either use permissions on shares, or have a share with full access for everyone and use permissions on the underlying folder.

#2 is to avoid making things very confusing: two sets of permissions being applied just makes working out what is going on much harder.
The simplest approach would be for each user to have their own share (only they have read and write access to it) over their own folder.
Alternatively you have one share, with the subfolders with permissions limiting it to that user.
You can create an access control list (ACL: the structure that is applied to files and folders1 to defined permissions) that would allow everyone to read everything but only the creator of a file can change/delete it but that is more advanced.
The easiest way is to create on each user's folder an ACL:

Do not inherit parent permissions.
The user has full control.
Administrators have full control.
Applied to this folder and all child files and folders.

1 And to anything else in Windows with access control.
Comment: for each user to have their own share seems most easy yes, but since we're not having network-wide credentials would it still be possible for them to access it from their desktops? Would it prompt for a login, or just give them plain access?
Comment: @FlorisPrijt If the username & password is the same on client and server they'll just connect. If not they should be prompted (but once a connection is established to the server the same credentials will be used for each further connection).
Comment: ah okay thanks for the clarification. I'll give it a shot once I am home, and will let you know the results.


Diferença de velocidade entre Plink e OpenSSH

Question: Tenho um setup com alguns repositórios Mercurial. Por questões de segurança e padronização recentemente o acesso https aos repositórios Mercurial foram desabilitados, o que obrigou todos os desenvolvedores a usarem ssh.
No Linux tudo funcionou muito bem, porém no Windows os programadores começaram a reclamar de lentidão. Usando a máquina de um colega para troubleshooting (Windows 7 + Mercurial 3.8.4) percebi que de fato mesmo clonar repositórios relativamente pequenos leva um bom tempo:
$ time hg clone ssh://email@example.com/meuprojeto
destination directory: meuprojeto
requesting all changes
adding changesets
adding manifests
adding file changes
added 52 changesets with 216 changes to 55 files
updating to branch default
33 files updated, 0 files merged, 0 files removed, 0 files unresolved

real    2m58.229s
user    0m0.000s
sys     0m0.015s

Seguindo algumas dicas (como esssa), tentei habilitar compressão no TortoisePlink. Também tentei usar uma versão beta do Plink (teoricamente mais rápida) com pouca ou nenhuma diferença.
Instalei então o Cygwin com OpenSSH e a diferença foi brutal:
$ time hg clone ssh://firstname.lastname@example.com/meuprojeto
destination directory: meuprojeto
requesting all changes
adding changesets
adding manifests
adding file changes
added 52 changesets with 216 changes to 55 files
updating to branch default
33 files updated, 0 files merged, 0 files removed, 0 files unresolved

real    0m15.794s
user    0m0.000s
sys     0m0.015s

O clone foi ~11 vezes mais rápido! Ainda assim 3 vezes mais lento do que no Linux, mas 15 segundos é um tempo aceitável.
Gostaria de saber se alguém tem ideia do que faz o OpenSSH tão mais rápido do que o Plink quando usamos Mercurial no Windows? Existe alguma coisa que possa ser feita para melhorar a performance do Plink?
Acredito que OpenSSH seja uma solução aceitável uma vez que o público alvo são desenvolvedores. Dito isso o pessoal do Windows não está muito acostumado com o mundo Linux e a integração do TortoiseHG + Plink + Pageant acaba sendo bem menos alienígena do que Cygwin + OpenSSH + ssh-agent. Existe alguma outra opção bom boa performance e usabilidade para o Windows?
Answer: Futuramente: Windows Subsystem for Linux
Atualmente, não parece existir muitas opções interessantes.
É um tiro no escuro, mas poderia tentar usar o Win32 OpenSSH.
Comment: Entendo, não é nada prático. Mas se você começar a usar repositórios intermediários, como RepoDraft -> RepoPublic -> RepoCanonico, pode vir a ser interessante. O RepoDraft, seria no Windows na fase Draft, o público seria no seu VirtualBox/Linux, e o canônico é o servidor externo. Com o Windows se comunicando via HTTP com o Linux, sendo numa rede virtual interna, seria seguro. O Linux continuaria se conectando com o servidor externo utilizando o SSH. Para completar, o Linux poderia estar no pendrive, e o VirtualBox poderia iniciar diretamente de lá, facilitando a mobilidade entre computadores.
Comment: Pois é Marcos. Suporte oficial da Microsoft vai ser lindo. Eu dei uma brincada com o OpenSSH no PowerShell em casa ontem e toda a parte de `ssh-agent` funcionou direitinho. Para  o `TortoiseHg` tudo ficou transparente (o `ssh-agent` registrado como serviço levanta as chaves). Em termos de performance, no momento o Cygwin é um pouco mais rápido (mas isso não deve ser verdade por muito tempo)... Vou ver se consigo colocar isso para rodar no Windows 7 (meu colega não conseguiu).
Comment: Estava pensando numa idéia maluca aqui. Já tentou instalar o Linux no VirtualBox, e rodar o TortoiseHg por lá? Será que a performance seria melhor?
Comment: Olá Marcos, por curiosidade eu fiz o teste. Operações como `clone` tem *performance* muito próxima do ambiente original Linux (são mais rápidas que no Cygwin). Dito isso, o trabalho de colocar uma VM para rodar, configurar pastas compartilhadas, etc faz do `Cygwin` uma opção mais viável. Não surgindo nenhuma outra alternativa nativa (até agora não encontrei nada) acho que a melhor opção será inicializar o `ssh-agent` como serviço e adicionar as chave no *startup*. Encontrei até [um script](https://github.com/ericblade/ssh-agent-cmd) para isso.
Answer: Voltando para responder minha própria pergunta um ano e meio depois.
Muita coisa mudou nesse meio tempo, inclusive, o Windows 10 está ganhando uma versão nativa de OpenSSH. Nada mais do que o Win32-OpenSSH mencionado na resposta do Marcos Zolnowski que agora pode ser instalado como uma funcionalidade opcional do Windows.
O WSL também funciona bem, apesar de não ser substituto para um cliente nativo (a integração com programas externos ao WSL ainda deixa a desejar).
A performance do Mercurial no Windows ainda não está em pé de igualdade com o Linux. No Linux em média clonar via SSH costuma ser bem mais rápido do que via HTTPS. Dito isso todos os clientes SSH que testei estão conseguindo clonar repositórios de tamanho médio (50 - 100 MB) em questão de segundos e não minutos. Sinceramente eu não tenho mais utilizado o Cygwin para muita coisa (e isso é ótimo).
Seguem alguns tempos com os clientes SSH mais populares na minha máquina pessoal (Mercurial Distributed SCM 4.4.1 + Windows 10):
HTTPS
hg clone https://email@example.com/tortoisehg/thg --time
time: real 23.926 secs (user 13.125+0.000 sys 2.891+0.000)

Win32-OpenSSH 0.0.24.0 (OpenSSH_7.6p1, LibreSSL 2.5.3)

ssh = "C:\Program Files\OpenSSH-Win64\ssh.exe" -C -a -x

hg clone ssh://firstname.lastname@example.com/tortoisehg/thg --time
time: real 22.402 secs (user 13.203+0.000 sys 2.859+0.000)

WSL openSUSE Leap 42.3 (OpenSSH_7.6p1, OpenSSL 1.0.2n-fips  7 Dec 2017)

ssh = ssh -C -a -x

hg clone ssh://email@example.com/tortoisehg/thg --time
time: real 23.990 secs (user 11.940+0.620 sys 4.620+0.760)

Git For Windows  18.104.22.168 (OpenSSH_7.6p1, OpenSSL 1.0.2m  2 Nov 2017)

ssh = "C:\Program Files\Git\usr\bin\ssh.exe" -C -a -x

hg clone ssh://firstname.lastname@example.com/tortoisehg/thg --time
time: real 28.191 secs (user 13.703+0.000 sys 2.734+0.000)

PuTTY (Release 0.70)

ssh = "C:\opt\PuTTY\PLINK.exe" -ssh -2 -C -a -x

hg clone ssh://firstname.lastname@example.com/tortoisehg/thg --time
time: real 28.630 secs (user 14.281+0.000 sys 2.641+0.000)

Answer: Existe um artigo que fala sobre a lentidão do git no Windows:
https://github.com/msysgit/msysgit/wiki/Diagnosing-why-Git-is-so-slow
Uma forma de resolver é com git lfs clone..., veja aqui.
Boa parte dos comandos executados no Windows são lentos, como git, ruby, python, etc... Tecnicamente não sei explicar o motivo, mas esta relacionado a Arquitetura e Kernel do SO. O Cygwin emula um Linux.
Comment: Oi Vitor, pois é, eu vi que o pessoal do Git no Windows também sofre tanto com a diferença no sistema de arquivos quanto com versões [defasadas  / lentas de clientes ssh](https://gitlab.com/tortoisegit/tortoisegit/issues/107). Infelizmente por se tratar de mercurial em repositórios razoavelmente pequenos estou refém da velocidade do cliente ssh (que esse é o gargalo já ficou claro para mim). Será que existe algum tipo de configuração que possa ser feira para aumentar a performance?
Comment: Não sei se seu repositório aceita, mas voce poderia tentar clonar o repositório e trabalhar via http. O Github por exemplo permite clonar pelo http.


How to implement RSS feed in our website in drupal 7?

Question: Can anyone help me out with steps as how to implement RSS Feed in a node in drupal 7?
Comment: What do you need to import? Nodes? Easiest way is to install views and views rss and build view.
Comment: @Frione:I want to implement rss feed at specific nodes so it can be published ,can you be more precise a show to do it via views also as i am new to drupal .
Comment: Difficult to describe in two words. I don't know maybe somebody post you instruction but I doubt. So here link where you could see example http://confluence.tapcrowd.com/display/dev/Setting+up+RSS+feeds+in+Drupal
Answer: You will need the Feeds module. It deals with all things feeds related. Or if you just want to set up an rss feed check out this tutorial which runs you through the process http://www.inmotionhosting.com/support/edu/drupal-7/configure-rss-feeds


Can someone help me with contextual filters in profile2

Question: I would like to single out a second profile with a views page using basic taxonomy reference or user information. Can you help me get my contextual filter to work with either user id, profile id, or taxonomy reference. I have my view to show users of a particular roll type. All users of this type will have a unique taxonomy reference ( or tag). When I choose fields for this tag in contextual filters and test it using the tag I don't get any results.
Answer: I was able to (finally) populate something on the user id. I guess it's the best way because I am going to be using rules to handle the information after the profile is created. Unfortunately, for some reason when I create a new user sometimes one of my profile id's is set to '0' shrugs which throws off the population of the field (check this especially if you use profile2_regpath).
How I was able to do it was to like this

I referenced the profile based on user id... then I drew three relationships on the profile, the profile type, and the user id.  I finally chose fields that substantiate the information I needed the user to see (in this case they are just testing it out). Please let me know if there is another way. I'm assuming there has to be something else out there or something I am missing. It populates one user at a time based on the profile owner's user id.


Show node for specific content type using views contextual filter

Question: Let me explain the issue in detail. I have created two views. The first view displays listing of content for content type named Invoice. The View has a page display. This view is working fine.
I want when a user clicks on any content item the resulting page should use the another view which I have created to show the items for a specific content item based on the node id passed.
How to pass the node id as a contextual filter for second view. I have given the path for second view as node/%, but then the view just work for all content types. I don't want that thing to happen. I just wants to have that view called for Invoice content type items.
I have also used validation criteria for contextual filter, but that doesn't work.
Comment: You mean to say like the second view will render the items based on the content type of the node-id passed as a contextual filter..? OR just invoice..?
Comment: Yes exactly the second view will accept contextual filter as a nodeid passed from first view..
Answer: A simple query alter will do the job.
Say example you are using a module my_views_invoice
<code>    function my_views_invoice_views_query_alter(&$view, &$query) {

    $nodeid = $view->args[0][1]; // get the node id from contextual filters. Ex :Array ( [0] => node [1] => 1 )

   $content_type =  node_load($nodeid) ;// get the content type from the node load : Ex $content_type->type

      if ($view->name == '<Your view name>') {
// Add a where condition in the query like below..

        foreach ($query->where[0]['conditions'] as $key => $conditions) {
          if ($conditions['field'] == 'node.type') {
            $query->where[0]['conditions'][$key]['type'] = $content_type->type;

          }
        }
    }
</code>


The origin of the Wilkinson-style notation such as (1|id) for random effects in mixed models formulae in R

Question: Model formulae in R such as
y ~ x + a*b + c:d

are based on the so called Wilkinson notation: Wilkinson and Rogers 1973, Symbolic Description of Factorial Models for Analysis of Variance.
This paper did not discuss notations for mixed models (which might not have existed back then). So where did the mixed model formulae used in lme4 and related packages in R such as
y ~ x + a*b + c:d + (1|school) + (a*b||town)

come from? Who introduced them for the first time, and when? Is there any agreed upon term such as "Wilkinson notation" for them? I am specifically referring to the terms like
(model formula |  grouping variable)
(model formula || grouping variable)

Answer: The notation | has been around in nlme docs since version 3.1-1 and that is probably late 1999; we can easily check that on CRAN nlme code archive. nlme does use this notation, for example try library(nlme); formula(Orthodont); the | comes up - so 2000's are off. So let's dig.... "Graphical Methods for Data with Multiple Levels of Nesting" Pinheiro & Bates (1997) where the groupedData constructor is introduced. And they say: "The formula in a grouped data object has the same pattern as the formula used in a call to a Trellis graphics function in S-PLUS, such as xyplot" Which.... makes sense as are P&B working in... Bell Labs (RIP) which developed the Trellis graphics system which actually used the operator | already to indicate groups. Which probably means... "The Visual Design and Control of Trellis Display" by Becker et al. (1996) has something to do with this. Notation is not introduced in this paper but it is the first electronic Trellis display reference I can find.
Essentially we need to dig-up visualisation literature at this point. Probably I would check Cleveland's book Visualizing Data (1993) and early works of Deepayan Sarkar (who developed lattice). Notice that the actual operator |  (and ||) are true primitive operators as they are associated with OR operators, so it was just a matter of time till someone overloads them.
While not a full answer, I strongly suspect P&B checked their colleagues cool visualisation system (the plots in that 1996 paper are quite good for late 2010's standards) and realised that someone (Becker, Cleveland and Shyu) already did some work on this (maybe even discussed this with them at the time) and just followed up what was already there. I.e. the | operator  originates in graphics notation. Trellis almost certainly used it; potential predecessors of Trellis may have done so too but their e-footprint is very hard to track.
In general, I think you might want this page on NLME: Software for mixed-effects models by Bell Labs for more historic information on nlme.
Comment: I think you are reading a bit too much into the presence of the parentheses; I strongly suspect they exist for parsing purposes given `lme4` uses a unified syntax for all terms. For example `fm1 <- lmer(Reaction ~  Days | Subject, sleepstudy)` works fine without any parenthesis.
Comment: Thanks a lot! It's true that `nlme` uses `|` but I don't think it uses `()` to denote random effects, right? Random effects are listed as a separate argument to the function call. Was it `lme4` that introduced `(x|id)` as part of the *same* formula?
Comment: Oh. Indeed. Never thought about it this way :)
Comment: Bates just confirmed that the random part was introduced by the nlme authors (of which he is one): https://twitter.com/BatesDmbates/status/1111283948615802881
Comment: @JonasLindeløv: Cool! Thanks for sharing, I will make a link to the answer tomorrow night.


Warning pandas, 2 loopings!

Question: Pessoal estou com problema neste looping, por que é uma situação que nao consigo resolver com np.where, por que tem que correr o DataFrame para achar o valor do ganho ou da perda apartir de outra condição, qual vier primeiro.
Está funcionando mas fico recebendo este warning:

C:\Users\Jair\Anaconda3\lib\site-packages\ipykernel_launcher.py:14: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

def estrategia_2_alta(candles):

    for i in range(1,len(candles)):
        if candles['Twintower'][i]== 1:
            loop2 = i
            for twin in range(loop2+1, len(candles)):
                if candles['askclose'][twin]>=candles['Gain'][i]:

                    candles['Resultado'][i] = candles['Tamanho_Twin'][i]*GainC
                    break

                elif candles['askhigh'][twin]>=candles['Gain'][i]:

                    candles['Resultado'][i] = candles['Tamanho_Twin'][i]*GainC
                    break

                elif candles['askclose'][twin]<=candles['Loss'][i]:
                    candles['Resultado'][i] = candles['Tamanho_Twin'][i]*(-StopC)
                    break

                elif candles['asklow'][twin]<=candles['Loss'][i]:

                    candles['Resultado'][i] = candles['Tamanho_Twin'][i]*(-StopC)
                    break

Answer: Esse problema está acontecendo por causa da sua atribuição candles['Twintower'][i]. O pandas não "gosta" muito dessa atribuição. Experimente fazer:
candles[i, 'Twintower']

Esse artigo explica um pouco o iloc e o loc.
https://medium.com/horadecodar/data-science-tips-02-como-usar-loc-e-iloc-no-pandas-fab58e214d87
Ah..
Saiba que np.where também aceita condições dentro.
np.where(<condição>, <se verdadeiro> , np.where(<condição>, <se verdadeiro>, <se falso>))

Warning pandas, 2 loopings!


PHP class method named print... not allowed?

Question: I am writing a Controller for Codeigniter with a method named "print".  The name is important, because I would like to be able to access the page at "http://www.mysite.com/mycontroller/print".
However, I cannot do this because there is the syntax error:
Parse error: syntax error, unexpected T_PRINT, expecting T_STRING

Is there any special syntax to make the PHP interpreter "think" that when I say:
class MyClass extends Controller {
    function print() {
        // print method here
    }
}

... that I am talking about a method with a T_STRING name of "print" and not the T_PRINT that it is expecting it to be?
Answer: This won't work because print is a language construct in php. I know it looks like a function, but it is treated the same way as (for example) function, while, include, and so on.
Answer: See the list of Reserved Keywords in PHP. You cannot use any of them as constants, class names, function or method names.
Answer: I found that you can get around the naming restriction for some reserved words in PHP 5.3 using the __call magic method.
public function __call( $name, $arguments )
{
  $fn = 'do_' . $name;
  if ( method_exists( $this, $fn ) )
  {
    return call_user_func_array( array( $this, fn), $arguments );
  }
  else
  {
    throw new Exception( 'Method "' . $name . '" does not exist.' );
  }
}

protected function do_print( /* $arg1, $arg2,...*/ )
{
  //whatever
}

I'm not saying this is necessarily a good idea, but it does allow you to make a call like $foo->print().
I really see no reason why reserved words can't be used as method names for classes. I haven't been able to come up with an ambiguous case that would need to be solved.
Answer: print like echo or isset are language constructs and can not be used as function or classnames.
Answer: If you called the print function 'hardcopy()' for example, you could use a mod-rewrite rule to accomplish the same thing.  ie:
RewriteRule ^/mycontroller/print /mycontroller/hardcopy [L]
Answer: As everyone has pointed out, you can't use language constructs as function names.
Your solution is probably URI Routing so that you can use print in your url but something safe as your method name.


Does anyone know when the following definition was formulated.

Question: I am curious when the following Definition was formulated.  Is this a product of Dan Shanks' work?
The following algorithm computes the simple continued fraction expansion of $\frac{P+\sqrt{D}}{Q}$, where $D$ is a nonsquare positive rational and $P$, $Q\neq0$ are any integers.  Let $P_0=P$, $Q_0=Q$, and $a_0=\left\lfloor \sqrt{D}\right\rfloor$.  For $i\geq1$, define
$$P_i=a_{i-1}Q_{i-1}-P_{i-1} \tag{A}$$
$$Q_i=\frac{D-P_i^2}{Q_{i-1}} \tag{B}$$
$$a_i=\left\lfloor \frac{P_i+\sqrt{D}}{Q_i} \right\rfloor. \tag{C}$$
Comment: It could very well go back to Lagrange, or even to Euler.
Answer: It's a well-known ancient algorithm for computing the continued fraction of quadratic irrationals. Below is what Knuth says about the history in TAOCP vol. $2$, solution to exercise $18.104.22.168$ (which contains a complete derivation and proof of correctness)

Probably much more can be said on the history. A good place to start is David H. Fowler's The Mathematics of Plato's Academy: A New Reconstruction (which, in addition to history, also provides a nice introduction to the main algebraic properties of continued fractions; see also Chrystal's Algebra).
Comment: Bill, Why do you think that the fact that $X^2-PY^2=a$, $P=a^2+(2b)^2$ an odd prime, has integer solutions did not get proved until 2000?  It seems that it should have been proved much earlier, considering the proof given by Robertson/Matthews using continued fractions in 2005?
Comment: @Jason What proof in 2000 do you refer to?
Comment: Feit and Mollin proved this using Algebraic Number Fields.   Robertson and Matthews proved in using Continued Fractions.    Walsh generalized the result.   Mollin has since given a major generalization.
Comment: @Jason Perhaps the result was proved earlier, did you check Dickson's History? In any case, there are plenty of simple proofs in elementary number theory that have not been presented simply because they have never been investigated.
Answer: It's not a definition, it's an algorithm. I first saw it in an early edition of the textbook by Niven and Zuckerman, but I don't know where they might have found it.
Comment: Ok definition of an algorithm but thank you.


Mysql - Query para retornar do dia 01 ao dia corrente do mês

Question: alguém consegue me dar uma ajuda?
Preciso de uma query que retorne por exemplo, do dia 01/11 até o dia de hoje, 22/11. Amanhã, retorne do 01, até dia 23. No inicio do mês, preciso por exemplo que retorne do 01, até o dia 2, supondo que o dia corrente é o dia 02. Não tenho ideia como fazer isso.
Alguém conseguiria ajudar?
Obrigado.
Comment: Bom, dia 1 sempre é dia 1, independente do mês. Não bastaria você buscar pelo dia 1 do mês corrente?
Answer: Segue um exemplo:
<code>SELECT STR_TO_DATE(CONCAT(DATE_FORMAT(NOW(),'%Y-%m'), '-01'), '%Y-%m-%d') AS DATA_INICIAL, STR_TO_DATE(DATE_FORMAT(NOW(),'%Y-%m-%d'), '%Y-%m-%d') AS DATA_FINAL
</code>
Explanação:

NOW() -> Data/hora atual
DATE_FORMAT -> Converte uma data para string no formato especificado
CONCAT -> Concatenação de textos. No caso, concatenamos o ano + mês
com "01" para ter o primeiro dia do mês.
STR_TO_DATE -> Converte uma string para data

Mais detalhes sobre cada uma das funções, vc encontra na documentação neste link.
Pode-se usar tanto para listar como fiz no exemplo acima quanto na cláusula where...
Comment: Orra Ricardo, muito obrigado pela ajuda. Vou olhar a documentação e agora já tenho como me virar aqui.

Valeu mesmo.


Determine the equation of a line that passes through point $A(1,0,2)$ and intersects the line $r=(-2,3,4) +s(1,1,2)$, at a right angle.

Question: Vector/Linear algebra question. I already have the solutions manual but I still don't understand how to arrive at the answer. Would appreciate some help, thank you. $r$ is a vector equation for a line by the way.
Comment: First think about a line that goes through the point of interest ($(1,0,2)$) and some point on the other line. There are lots of lines like this, one for each point on the given line. Then you need to find the one that is perpendicular to the given line.
Comment: I'm still not completely clear.
Answer: The equation of a plane perpendicular to the line is
$$x+y+2z=a$$ if it passes through $(1,0,2)$ then $a=5$.
Now the intersection of $x+y+2z=5$ with the line is given when
$$-2+s+3+s+2(4+2s)=5$$
or $s=\frac{2}{3}$ so now we just take the line through these two points.
Comment: I've been trying to go off of what you and Mhenni said but I still don't fully understand. Can you explain a little more please?
Comment: I usually like to use projections for these types of problems, but this is really nice.
Answer: Hint: The directional vector $u=(a,b,c)$ of the line is perpendicular to the vector

$$ v=(1,1,2), $$

which is the directional vector of the line $(-2,3,4)+s(1,1,2)$. To find $u$ then solve the system which is resulted from the dot product

$$ (1,1,2).(a,b,c)=0 $$
Comment: You mean $(1,1,2)\cdot (a,b,c) = 0$. $(-2,3,4)$ is not the directional vector.
Comment: @Braindead: Yes you are right. It is a typo. Thank you for the comment.
Answer: A parametric equation of a line is given by the formula:
$f(s) = p + v s$
Here, $p$ is some point on the line and $v$ is a vector pointing in the direction of your line.
You are trying to find an equation of the line that has the following properties:

The line goes through $(1,0,2)$.
The line is perpendicular to $(-2,3,4) + s(1,1,2)$.

The first condition gives you a point on the line. So you can make $p = (1,0,2)$.
The second condition, at least in theory, tell you how to get the vector $v.$
Rather than giving you the answer to the problem you posted, which seems like a homework assignment, I will perform essentially the same problem with different numbers. Apply the steps I am taking to your problem, and you should be able to get a solution that works.

Determine the equation of a line that passes through point $A(0,2,1)$ and intersects the line $r=(2,-3,-4)+s(-2,1,1)$, at a right angle.
As I said before, equation of a line is given by $l = p + v s$, where $p$ can be ANY point on your line.
My problem specifies that the line goes through $(0,2,1)$. So it makes a lot of sense to make $p = (0,2,1)$.
This is only half of the problem, as we need to determine what $v$ is. Whatever $v$ is, it must be perpendicular to line $r=(2,-3,-4)+s(-2,1,1)$. (See picture.)

Now, pick a random point on the line $r=(2,-3,-4)+s(-2,1,1)$. You can literally choose ANY point. Let's call this point $R$ ("R" for random). You can pick a point by choosing ANY value of $s$.
You can pick $s = 0, 1, 2, 3\dots -1, -2, -3\dots$ or even a fraction or an irrational number. But the easiest one to choose is $s=0$, so let's go with that.
$r(0) = (2,-3,-4) + 0 (-2,1,1) = (2,-3,-4)$. So let's call this point $R = (2,-3,-4)$
In the picture, you should see a picture of a right triangle formed by $A(0,2,1)$, your random point $R=(2,-3,-4)$, and $S$, the point where our line would intersect the original.
Now, observe that the vector $A(0,2,1) - R(2,-3,-4) = (-2,5,5)$ is essentially the hypotenuse of our triangle. Let's call this vector $h = (-2,5,5)$ (blue arrow)
The base of the triangle is in the direction of the line, which is given by $(-2,1,1)$ (shown as the green arrow). As the picture shows, we don't really know if $(-2,1,1)$ makes up one of the sides of the right triangle, but it is certainly along the right line.
To find the side of the triangle that is along $(-2,1,1)$ (shown as the red arrow), we can perform a procedure called orthogonal projection.
$$\mathrm{Proj}_w v = \dfrac{v\cdot w}{w\cdot w} w,$$
where $v\cdot w$ means the scalar product.
What it does is that it finds a "shadow" of one vector onto another one. In this situation, we can take $A(0,2,1) - R(2,-3,-4) = (-2,5,5)$, the hypotenuse (blue arrow), and project it onto $(-2,1,1)$ (green arrow), and this will give us exactly the base of the triangle (red arrow).
\begin{align}
\mathrm{Proj}_{(-2,1,1)} (-2,5,5)&= \dfrac{(-2,5,5)\cdot (-2,1,1)}{(-2,1,1)\cdot (-2,1,1)} (-2,1,1)\\
&=\dfrac{(-2)(-2)+5(1)+5(1)}{(-2)(-2)+(1)(1)+(1)(1))} (-2,1,1)\\
&=\dfrac{14}{6} (-2,1,1)\\
\mathrm{Proj}_{(-2,1,1)} (-2,5,5)&=\dfrac{7}{3} (-2,1,1) = (\frac{-14}{3}, \frac{7}{3}, \frac{7}{3})\\
\end{align}
Now, we have a vector $w = (\frac{-14}{3}, \frac{7}{3}, \frac{7}{3})$ on the base (red arrow in the picture.) We have our hypotenuse vector $h = (-2,5,5)$ (blue arrow). The third side of the triangle is then just the difference of $w$ and $h$ (not pictured).
\begin{align}
 w - h &= (\frac{-14}{3}, \frac{7}{3}, \frac{7}{3}) - (-2,5,5)\\
&= (\frac{-14}{3}, \frac{7}{3}, \frac{7}{3}) + (2,-5,-5)\\
&= (\frac{-8}{3}, \frac{-8}{3}, \frac{-8}{3})
\end{align}
By construction, you should be able to see that $(\frac{-8}{3}, \frac{-8}{3}, \frac{-8}{3})$ is a possible candidate for $v$. Because it is perpendicular to our original line: $r=(2,-3,-4)+s(-2,1,1)$.
So one possible equation is: $l = A + v s = (0,2,1) + (\frac{-8}{3}, \frac{-8}{3}, \frac{-8}{3})s$
Now, emphasized that $(\frac{-8}{3}, \frac{-8}{3}, \frac{-8}{3})$ is a possible candidate, because ANY multiple of this vector points along the same (or opposite) direction.  $(\frac{-8}{3}, \frac{-8}{3}, \frac{-8}{3}) = \frac{-8}{3}(1,1,1)$, so this vector points in the opposite direction as $(1,1,1)$, but this will still give you the same line.
So another possible equation is: $l = A + v s = (0,2,1) + (1, 1, 1)s$
Another possible equation is: $l = A + v s = (0,2,1) + (2, 2, 2)s$
Another possible equation is: $l = A + v s = (0,2,1) + (-2, -2, -2)s$
Etc.
I like: $l = A + v s = (0,2,1) + (1, 1, 1)s$
Now here is a final check.

$l$ goes through $(0,2,1)$? Yes, it happens when $s=0$.
Is $l$ perpendicular to $r$? Use the dot product to see if we get zero. (Zero dot product means perpendicular):

$$(-2,1,1)\cdot(1, 1, 1) = -2 +1 +1 = 0$$


Why are runouts not recorded in cricket?

Question: In international cricket, the number of catches taken by a player is recorded, but not the number of runouts effected by a player, even though effecting a runout is as important as taking a catch.
Is there a specific reason for leaving out runouts from the record book?
Comment: The problem for mine with the second answer here is that clearly sometimes (often even) a catch is also the fault of the batsman and the fielder just happens to be the one standing near by. So by that rationale fielders wouldnt have their career catches recorded within their records either. I have always had an issue with the lack of run out dismissals being recorded. A direct hit run out affected by a brilliant piece of individual athleticism can be a game changing effort. The result of this individual effort should be recorded within the players career records.
Answer: I think it's tradition more than anything, combined with the fact there can be ambiguity over who actually effects the runout when more than one fielder is involved e.g. outfielder throws to wicketkeeper who takes the bails off.
The only online reference I can find is at http://www.dangermouse.net/cricket/statistics.html in the Fielding Statistics section, but even here all it says is that this a tradition.
Comment: Not only can there be doubt about who really effected the runout, but sometimes it's entirely the batsman's fault. The fielder just happens to be the one near the ball when it happened.
Answer: Historically runouts have not been recorded in cricket, however the good people at the ACS have gone through the old newspaper reports and attributed runouts retroactively to players, although the ICC do not recognise these, they are largely respected by scorers.
In modern T20 International [and most domestic] Cricket, which has largely been televised, it usually is, at least, noted .... like this from the CPL the other day.

RJ Peterson   run out (Brathwaite/Cottrell)   7   9   0   0   77.77
    18.2 Cottrell to Pollard, comes round the wicket, low full toss wide outside off, powers it down the ground, long-on comes around and fires
  it to the bowler who removes the bails. KP wants to keep the strike as
  they comes back for the second, Peterson way short of his crease 101/6
Comment: While this is all true, it doesn't actually answer the question which is *why* the players contributing to runouts aren't/weren't recorded.


Why is gets() not consuming a full line of input?

Question: I'm trying to use gets() to get a string from the user, but the program seems to be passing right over gets(). There is no pause for the user to give input. Why is gets() not doing anything?
char name[13];
printf("Profile name: ");
gets(name);
printf("\n%s", name);

Comment: please use `fgets(name, sizeof name, stdin)` instead of `gets()` issue is answered many times see one of the answer http://stackoverflow.com/questions/7231349/getsstring-function-skipping-first-gets-request?rq=1
Comment: Don't use `scanf` for reading strings either. Just use `fgets`.
Comment: @DerekDrummond 12 characters of input, the last has to be `'\0'`.
Comment: I believe you can leave a white-space at the end of the `scanf` format to make it consume any white-space (such as the trailing new-line) in the input. But don't quote me on that.
Comment: I tried fgets(name, sizeof name, stdin) but it get passed over.  It's sad that gets() used to be so simple and now is replaced by something bulky.
Comment: Have you tried scanf? Also are you sure the input is no more than 12 characters long. What test values have you used?
Comment: Good call I forgot about that sentinel character.
Comment: Yes I have used scanf and it works.
Comment: @Kninnug If I used scanf previously in my code will fgets still be passed over?
Comment: Does this answer your question? [Gets(string#) function skipping first gets request](https://stackoverflow.com/questions/7231349/getsstring-function-skipping-first-gets-request)
Answer: Call getchar() before you call gets() or fgets(). Since gets() or fgets() is getting skipped due to an already present '\n' from previous inputs in stdin, calling getchar() would lead to itself getting skipped instead of gets() or fgets() or any other similar function. But remember its more of a hack and not a standard solution (I think so), and also  use of gets() is forbidden.
        printf("\nEnter a String: ");
        getchar();
        //fgets(inputString, 100, stdin);
        gets(inputString);
        printf("\n%s", inputString);

Answer: It's because gets() it's so incredibly dangerous to use, that some C libraries have removed it completely and replaced it with a version that does nothing.
Use fgets() instead.
Comment: `gets` has also been officially removed in C11 and depricated in C++.
Answer: Use fflush(stdin); before gets()
Comment: This is the solution that worked for me, the other didn't. thank you @Aadil Ansari
Answer: You get lot of troubles using gets()
Instead go for  fgets()
fgets(name,13,stdin);

See this SO question Why is the gets function so dangerous that it should not be used?
The reason why fgets() does not work, may be you are not handling the newline left behind by scanf in your previous statements.
You can modify your scanf format string to take it into account:
   scanf("%d *[^\n]", &N);
*[^\n] says to ignore everything after your integer input that isn't a newline, but don't do anything with the newline (skip it).
When you use scanf("%d",&num) you hit 13 and enter and 13 is stored in num and the newline character is still in the input buffer when you read fgets from stdin it treats \n as the data you have entered and the fgets() statement is skipped
You cannot flush input buffer however you can do this fseek(stdin,0,SEEK_END); add this before your every fgets statement
Comment: @Andre could you post us your complete code? its working here
Comment: void createProfile()
{
 char name[13];
 printf("Profile name: ");
 fgets(name,13,stdin);
 printf("\n%s", name);
}
Comment: did u use scanf in any part of your code @Andre because scanf() reads exactly what you ask it to; it's leaving everything else unread, notably the newline following the data.
Comment: Yes I used it a few times earlier. So are you saying I should only use fgets?
Comment: Suggest `fgets(name, sizeof(name), stdin)`.
Comment: Really don't think you want the space in `scanf("%d *[^\n]",&N);` as it _will_ consume the newline after the integer.
Comment: The asker wants to get a "%s", not "%d".  Numbers are easier to handle.  I also want to get a string, without the tailing `/n`, and I want to get a null string if the user merely pressed enter.
Answer: Take a look at gets() reference
Get string from stdin
Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.
The newline character, if found, is not copied into str.
A terminating null character is automatically appended after the characters copied to str.
Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
So, basically gets() is not only unsafe (can lead to buffer overflows) but also reads what's in the input buffer.
I recommend you to use fgets(), but if you want a quick (and lazy and stupid) solution, just flush the input buffer:
char name[13];
printf("Profile name: ");
fflush(stdin);
gets(name);
printf("\n%s", name);

Comment: The call to `fflush(stdin)` is undefined behavior in C.
Comment: Yes, however the language standard considers it as undefined behavior. And its use should not be encouraged.
Comment: You're right, it's meant to be used with output buffers. However, [some](http://msdn.microsoft.com/en-us/library/9yky46tz.aspx) compilers implement `fflush(stdin)` as an extension. It works as expected but it compromises portability.
Answer: Add this below function to your code and enjoy it.
string GetString()
{
   char ch;
   string Line="";

   while(1)
   {
       ch=getchar();

       if(ch=='\n')
          break;
       else
          Line+=ch;
    }

    return Line;
}

This function can effect all Spaces and Backspaces too!!!
Answer: You might need to discard the rest of the line and move on to the beginning of the next one. You can do:
int c; while((c=getchar()) != '\n' && c != EOF);

This discards the rest of the current line (which might have been partially read with scanf(), etc.) and moves on to the next one.
Although fflush(stdin) might also discard the input, it is non-standard behaviour and discouraged.
You should never ever use gets(myString), as it has been completely removed from the C standard due to how unsafe it is. It doesn't enforce the length of the string, so you can go past the end of the buffer and overwrite other values in RAM, causing a buffer overflow, which can be a security vulnerability. Use fgets(myString, myStringSize, stdin); instead. To get rid of the newline in the resulting string, use myString[strcspn(myString, "\n")] = 0;.


Android custom layout with different number of childs in row

Question: I have been developing android for a while and I have been facing many similar layouts to the one in screenshot (in both iOS and Android)
So what I would like to achieve is the different number of childs in each row.
Well, first I would like to ask is there a specific name for this layout type, it is not gridview although very close to it.
The structure seems like it can be populated with an adapter since all child buttons look alike
Any help, suggestion, solution or example library is much appreciated.

Taken from Foursquare for Android
Comment: What's stopping you from using a normal ListView and calculating the number of rows based on how many children fit the width of the list?
Answer: Since there is a chance of more than two childs (as you said) therefore what i think is that you can't accommodate so many childs as they would not be visible unless the listview row is horizontally scrollable.......I think you can use gallery widget as an item of listview and then you can have different childs in each row... You can google about the gallery widget, instead of images add your custom layout as gallery item.


A circular permutation question: selecting a team of knights so that no two knights hostile to each other are selected

Question: $16$ knights are sitting on a circular table, $7$ knights are required to rescue a girl. Every pair of consecutive knights are hostile to each other. How many number ways when selecting $7$ knights such that no $2$ hostiles can be teamed up? Please guide.
Comment: What have you tried?  Draw a picture, pick one knight to send for now.  How many ways are there to select the other six?
Comment: Sir .i brake the circle into linear form.
Answer: If $k$ is the total number of knights in a line and $p$ is the number of knights chosen in a party, there are $p$ selections (Y's) and $k - p$ knights left (N's), with at least one N in between two Y's. Here, $p - 1$ N's are in between the $p$ Y's, because of the 1 N separating two Y's. For this, you can count linear arrangements for $k - 2p + 1$ N's and $p$ selections. There are $\frac{(k-2p+1+p)!}{p!(k-2p+1)!} = \binom{k-p+1}{p}$ methods to do so.
If the selecting knight is part of the team, then $p = 6$ and $k = 13$, as the selected knights cannot be consecutive to the choosing one. Here, $\binom{13-6+1}{6} = 28$.
If the selecting knight is not part of the party, then $p = 7$ and $k = 15$, as there are no restrictions on the knights adjacent to the selecting one. In this scenario, $\binom{15-7+1}{7} = 36$.
These possible scenarios are added to find the total possible combinations.


Getting undefined variable when calling function from another function

Question: Scratching my head. I'm getting an undefined error when trying to call a function. Thing is, when I print to the console I can see the data being passed clearly.

Uncaught TypeError: convos is undefined

function1
function fetchConversation(userID){

//loop through
usersms.forEach(function (sms,counter) {

//get userid from  iteration
var userid_loop = sms.details[0].user.id;

//only display convo from specific user
if(userid_loop === userID){

//get all messages from this one user
var conversation = sms.details;

//transfer conversation to next function to display
showConversation(conversation);
//
}
//
});
}

function2
function showConversation(myconvo){

var convos = myconvo;

//iterate and append conversion
convos.forEach(function (msg,counter) {

console.log(msg.message);//prints all messages in the log

});
}
showConversation()//Uncaught TypeError: convos is undefined

Comment: Try doing `showConversation(myconvo)` instead of `showConversation()`
Comment: @Endothermic_Dragon: yes I did try that. It would have been an easy fix. I wouldn't be here.
Comment: Why are you calling `showConversation()` on its own?
Comment: @Nick: display result in html from the index page. I do this with a different function and it works. This one is undefined
Comment: Well just to be totally clear what your error is: if you do `showConversation()`, you have passed no arguments, meaning `myconvo` is `undefined`. Then you try to do `undefined.forEach`, which will explode because it's not an array.
Comment: @Nick: I'm listening. So it's a big bug then because if it's not an array how am I able to loop through and log result in the console? Weird.
Comment: Yeah, I mean you clearly use it correctly _inside_ the `fetchConversation` function
Comment: First error - you are not passing in arguments into your function. Second error - msg.message doesn't exist, it's just msg. https://stackoverflow.com/questions/65649486/getting-undefined-variable-when-calling-function-from-another-function#answer-65649649. Also, the counter is unnecessary in this case.
Answer: I believe that you need to enter something within the brackets of showConversation().
You are assigning convos to myconvo, but myconvo doesn't exist because you didn't enter it as a parameter (value in the brackets).
Comment: What would that variable be? I tried with different variables and get undefined
Answer: Your first error is that you are not passing in any arguments to the function.
Your second error is that msg.message doesn't exist - it's just msg by itself.
Also, the counter is unnecessary in this case.

function showConversation(myconvo) {
  var convos = myconvo;
  //iterate and append conversion
  convos.forEach(function(msg) {
    console.log(msg); //prints all messages in the log
  });
}
showConversation(["element1", "element2"])

You also have an error here:
function fetchConversation(userID){

//loop through
usersms.forEach(function (sms,counter) {

//get userid from  iteration
var userid_loop = sms.details[0].user.id;

//only display convo from specific user
if(userid_loop === userID){

//get all messages from this one user
var conversation = sms.details; //actually gets the details of the element it is iterating through, not all of them

//transfer conversation to next function to display
showConversation(conversation); //sends the details one by one for each iteration
//
}
//
});
}

Fix:
function fetchConversation(userID){
var conversation=[]
//loop through
usersms.forEach(function (sms,counter) {

//get userid from  iteration
var userid_loop = sms.details[0].user.id;

//only display convo from specific user
if(userid_loop === userID){

//get all messages from this one user
conversation.push(sms.details);
}
});
//transfer conversation to next function to display
showConversation(conversation);
}

Comment: What would be those elements?
Comment: That depends on what you are trying to do. I just fixed it so it works. It looks like you are trying to pass through snippets of a chat.


Why has soccer become so famous worldwide?

Question: This article shows an image where most popular sport by country can be checked. It's a bit old (from 2006), but I guess not old enough for having changed a lot since then.
Clearly, soccer is the most famous sport worldwide by far, I haven't calculated it precisely, but easily 2/3 of the world population live in countries where soccer is  the most famous sport.
What factors have brought soccer to be so famous worldwide? I'd like a brief explanation of why it has expanded so much at cost of other sports, as, although I don't know exactly what were in old times the most famous sports in other countries, it's sure that it's not like a lot of them got to develop soccer or something similar on their own.
Comment: Not enough for an answer but a strong governing body (FIFA) helps.   World Cup is shown pretty much world wide.
Answer: The basic rules are simple, it can be played almost anywhere, for the game you only need a ball, even two players are enough.
So almost everyone can play it almost anywhere without any special equipment. This makes football affordable and accessible for anyone and thus so popular.
And of course the worldwide broadcasting of major international competitions makes the game even more popular.
Answer: I agree with the answer. Not to mention the Federation has split up with many small regional confederations where a lot of the countries can participate. Not all the countries participating are good or maybe not all have international exposure but in one way or another, the game has become popular among the masses for its simplicity and ease of play. All you need is a ball a wall or another player and off you go. Here you can find the rankings for all the countries that are registered or have participated in some sort of tournament help by FIFA. I know the list has grown somewhat in the past years with new countries forming a national team and being added to the ranks.
https://www.fifa.com/fifa-world-ranking/ranking-table/men/index.html


How to pass a String value from one servlet to another servlet using session?

Question: Please i cheked for the answer of this question and i found this one : enter link description here
how can i do that using session:
request.setAttribute("attributeName",yourStringVAlue);
RequestDispatcher rd = request.getRequestDispatcher("yourServletPattern");
rd.forward(request,response);

and to retrieve :
String someName = (String)request.getAttribute("attributeName");

Answer: You stated "using session".
Set variable:
HttpSession session = request.getSession();
session.setAttribute("myId","myVariable");

Retrieve variable:
HttpSession session = request.getSession();
String var = (String) session.getAttribute("myId");

Comment: And finally, `session.removeAttribute("myId");`