Templated recurrent type error

Question: I am facing a weird problem with VS2010. The following code fails to compile (while being perfectly accepted by gcc):
// Instantiate each type of a type array (which is a template<int>)
// void is taken as the end of the array
template<template<int> class A, int n = 0, typename obj_type = typename A<n>::type>
struct Instantiate : public Instantiate
{
   obj_type object;

   Instantiate() : object() {}
};

template<template<int> class A, int n>
struct Instantiate
{
};

// Does not compile
template<typename O>
struct test
{
   template<int n, bool=true> struct array { typedef void type; };
   template<int n> struct array2 { typedef typename array<n>::type type; };

   template<bool u> struct array<0,u> { typedef int type; };
   template<bool u> struct array<1,u> { typedef float type; };
   template<bool u> struct array<2,u> { typedef bool type; };

   Instantiate<array2> objects;
};

int main()
{
   test<int> obj;
}

With the following error:
C1202: recursive type or function dependency context too complex
see instanciation of class template 'Instantiate'
with
[
    A=test<O>::array2,
    n=1
]
(and so on, up to n=497...)

Making test a non-template (ie, juste removing the line template<typename O>) solves the error. However, despite it is possible in this simple example, it is not possible in my code (which is a lot more complex).
The questions are:

Which is right, VS or GCC ? Or is it a VS bug ?
In the case VS is wrong, is there a workaround ?

EDIT:
 - From jerry's answer, it seems it is a compiler bug... and it is fixed on VS2012.
 - The generated class hierarchy should be:
Instantiate<array2, 3, void> // end of recursion
      ^
      |
Instantiate<array2, 2, bool>
      ^
      |
Instantiate<array2, 1, float>
      ^
      |
Instantiate<array2, 0, int>

Comment: This may be useful http://stackoverflow.com/questions/4357854/c-template-compilation-error-recursive-type-or-function-dependency
Comment: @Shafik I've already seen it, and it is not that error. Thank you anyway.
Comment: Have you tried to move array2 template below array<2,u> specialization? Does it make a difference?
Comment: @Tomek Yes, I've tried that, but it doesn't compile either.
Answer: I can reproduce this in VS 2010 (with Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86) and I believe it is is a bug. Truth be told, I'm having a hard time wrapping my head around the scope issues involved here, but that seems to have no bearing on the problem at hand (as the base templates and specializations are nested together and VS is complaining about recursion level, not an undefined symbol). In any case, it's a very interesting example.  I also see the same behavior in VS 2005 (with Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86). It doesn't seem that Microsoft is still accepting bug reports on VS 2010 (judging by the Microsoft Connect Visual Studio page and feedback form). Hopefully someone with access to VS 2012 will be able to test your original code and file a bug report if the problem hasn't been fixed yet (which I think is likely, I see no indication that it's been brought to Microsoft's attention before).
To work around the issue, forward declare the class template that's causing the recursion:
// Forward declaration of problematic inherited class template
template<template<int> class A, int n = 0, typename obj_type = typename A<n>::type>
struct Instantiate;

template<template<int> class A, int n>
struct Instantiate
{
};

// Now compiles!
template<typename O>
struct test
{
    template<int n, bool=true> struct array { typedef void type; };
    template<int n> struct array2 { typedef typename array<n>::type type; };

    template<bool u> struct array<0,u> { typedef int type; };
    template<bool u> struct array<1,u> { typedef float type; };
    template<bool u> struct array<2,u> { typedef bool type; };

    Instantiate<array2> objects;
};

// Instantiate each type of a type array (which is a template<int>)
// void is taken as the end of the array
template<template<int> class A, int n, typename obj_type>
struct Instantiate : public Instantiate
{
   obj_type object;

   Instantiate() : object() {}
};

int main()
{
    test<int> obj;
    return 0;
}

EDIT
Synxis, thanks for the rise4fun link, that's sure to come in handy later. The amazing thing is that while your original code works fine in VS2012 CTP, it's still broken in VS2012 RTM! See http://rise4fun.com/Vcpp/aRh. Why CTP is the default option instead of RTM is beyond me. This example is definitely a strange one.
Is there anything other than Instantiate in your library header that is used by test? If not, the user can explicitly forward declare the Instantiate template define test, and then include your header. Otherwise, you can create a header file that has the forward declaration in it along with the other things that are needed. Most likely you'll want to create special workaround headers for users affected by this problem. This certainly makes things very messy and error prone (mostly due to the default template arguments), but it will work:
myLib_workaround_forward_declaration.hpp:
#ifndef MYLIB_WORKAROUND_FORWARD_DECLARATION // or #pragma once if supported
#define MYLIB_WORKAROUND_FORWARD_DECLARATION

// amount of error checking is up to you
// eg, are workaround header files mixed with the regular ones
// or included in the wrong order

template<template<int> class A, int n = 0, typename obj_type = typename A<n>::type>
struct Instantiate;

#endif

myLib_workaround_implementation.hpp:
#ifndef MYLIB_WORKAROUND_IMPLEMENTATION  // or #pragma once if supported
#define MYLIB_WORKAROUND_IMPLEMENTATION

// amount of error checking is up to you
// eg, are workaround header files mixed with the regular ones
// or included in the wrong order

template<template<int> class A, int n, typename obj_type>
struct Instantiate : public Instantiate
{
   obj_type object;

   Instantiate() : object() {}
};

template<template<int> class A, int n>
struct Instantiate
{
};
#endif

userFile.cpp:
// Forward declaration of problematic inherited class template
#include "myLib_workaround_forward_declaration.hpp"

// Now compiles!
template<typename O>
struct test
{
    template<int n, bool=true> struct array { typedef void type; };
    template<int n> struct array2 { typedef typename array<n>::type type; };

    template<bool u> struct array<0,u> { typedef int type; };
    template<bool u> struct array<1,u> { typedef float type; };
    template<bool u> struct array<2,u> { typedef bool type; };

    Instantiate<array2> objects;
};

#include "myLib_workaround_implementation.hpp"

int main()
{
    test<int> obj;
    return 0;
}

Comment: @Synxis now a reported bug: https://connect.microsoft.com/VisualStudio/feedback/details/782271/recursively-inherited-class-template-with-parameter-default-arguments-fails-to-compile-despite-explicit-specialization
Comment: I will test this code on VS2010 this evening, for the moment it works flawlessly on VS2012 (the version in the question also [compiles on this compiler](http://rise4fun.com/Vcpp/1TL)). The problem with this solution is the definition of `Instantiate` after `test`. In my case, `test` is provided by the user, and `Instantiate` by the my library... +1 anyway. If you find another workaround / solution, feel free to post :) !
Comment: So... CTP != RTM. Nice >.< ... I thought of the workaround you put in your edit, not that practical (you have to be sure the user does not forget to include the implementation header). While messing with r4f rtm, I found another solution that does not involves including 2 headers. Thank you for the answer!
Comment: Ah, and forgot to say: [here is a list of online compilers](http://isocpp.org/blog/2013/01/online-c-compilers). Enjoy !
Answer: It's not a bug, it's compiler configuration. Compile-time stack is limited just like run-time stack. IIRC in VS the maximum depth of compile-time stack is 512. Might worth seeking in the documentation, maybe it's configurable, though not sure.
Comment: It is the same for gcc. Moreover, the type array only have 3 elements. So it should stop the recursion at `n == 3`, which correspond to the `void` specialization. GCC does that.
Answer: While messing with rise4fun and jerry's workaround, I found that putting the whole definition of Instantiate inside test 'solved' the problem (see jerry's answer for more information on VS2012CTP vs VS2012RTM):
template<typename O>
struct test
{
    template<template<int> class A, int n = 0, typename obj_type = typename A<n>::type>
    struct Instantiate : public Instantiate
    {
        obj_type object;
        Instantiate() : object() {}
    };

    template<template<int> class A, int n>
    struct Instantiate
    {
    };

    template<int n, bool=true> struct array { typedef void type; };
    template<int n> struct array2 { typedef typename array<n>::type type; };

    template<bool u> struct array<0,u> { typedef int type; };
    template<bool u> struct array<1,u> { typedef float type; };
    template<bool u> struct array<2,u> { typedef bool type; };

    Instantiate<array2> objects;
};

int main()
{
   test<int> obj;
}

Which is perfect for my use case as it can be included in a macro already used by the user.
Comment: Glad you found a solution that works in your library's case. Out of curiosity, is it going to be publicly available?
Comment: Yes. It will be part of [SPARK Particle Engine](http://spark.developpez.com/index.php?lang=en) (the home page is bugged, you will probably find more info on the forums and in the source).

Templated recurrent type error


Modify a listbox from other class

Question: I'm making a GUI for a database with pyqt. The database is coding in mysql. Furthermore, the main Window has a QListWidget which allows to see database's data through a update Function.
def update(self, bd1='',sql1=''):
try:
    cur = bd1.cursor()
    cur.execute(sql1)
    data = cur.fetchall()
    #print data
    for registro in data:
        #Asignacion de registros a variables
        n = registro[0]
        LName= registro[1]
        Name = registro[2]
        ID = registro[3]
        LName1= registro[4]
        Name1 = registro[5]
        ID1 = registro[6]
        Tip = registro[7]
        Cel = registro[8]
        Tel1 = registro[9]
        Tel2 = registro[10]
        Email= registro[11]
        City = registro[12]

        print 'Entro'
        #Colocacion de datos al listbox
        self.list.addItem(LName + "," + " " + Name)
        self.list.addItem("CC" + " " + ID)

        #Arreglo Cel
        if (Cel==None or LName1==None) or (Tel1==None and Tel2==None) or Email==None:
            pass

        elif Tel1!=None and Tel2==None:
            self.list.addItem("Tel: " + Tel1)
        elif Tel1==None and Tel2!=None:
            print "Error Telefonos en la base de datos"
        else:
            self.list.addItem("Cel: " + Cel)
            self.list.addItem(LName1 + "," + " " + Name1)
            self.list.addItem("CC" + " " + ID1)
            self.list.addItem("Tel: " + Tel1 + " - " + Tel2)
            self.list.addItem("Email: " + Email)

        #Arreglo Ciudad
        if City==None:
            self.list.addItem("Ciudad: " + "Bucaramanga")
        else:
            self.list.addItem("Ciudad: " + City)

        #Arreglo Tipologia
        if Tip==None:
            self.list.addItem(" ")
        else:
            self.list.addItem("Tipologia: " + Tip + "\n")

except:
    print "Error en obtencion de datos"
#Desconexion de la BD
bd1.close()

Moreover, I created another class that allows to add a new user but when I call the function "update", the list doesn't update with the new data. On the other hand, I have to restart the program for watch the latest updates in the database. What should I do to avoid restart the program and makes update immediately?
Answer: If your other function, you need to call update() at the end.
def add_user():
    # Code to add user to database
    # remember to commit()
    self.list.clear()
    self.update(#appropriate parameters)

This clears the self.list widget prior to your update call, otherwise you will have duplicate data appearing. When self.update() is called, with the appropriate parameters, self.list will be repopulated with data from your query.
One thing to remember, after you add a user to the database, be sure to commit your changes. If you don't, your update() won't see the new user's information.
Comment: I made that and appeared a mistige                                Traceback (most recent call last):
  File "pyqt2.py", line 367, in nuser
    self.list.clear()
AttributeError: 'AddWin' object has no attribute 'list'
Comment: Not self.list when called from another class: replace self with whatever you named the instance (mainwindow, maybe?).

Modify a listbox from other class


How to arrive at the conclusion of an implication using the hypothesis when proving R is an equivalence relation.

Question: How do i prove that this is a equivalence relation
I'm aware this may get removed as a dupe but I can't comment on that post since I'm below 50 reputation. I think the answer the post got just highlighted the thing I don't understand about relations (It's not that the answer isn't clear)
Symmetry:  $(x,y)\in R\implies y=x\times e^n$ for some integer $n$. But then $x=y\times e^{-n}$ and, of course, $-n$ is still an integer.  Thus $(y,x)\in R$ as desired.

How did they specifically come to the conclusion that $(y,x)\in R$ from their workings out, which I understood. It feels like they assumed the conclusion instead of working towards it (This sounds like a shot on them but it's just me not understanding)

Transitivity:  $(x,y)\,\&\,(y,z)\in R$ means that there are integers $n,m$ with $y=x\times e^n$ and $z=y\times e^m$.  But in that case we have $z=x\times e^n\times e^m=x\times e^{n+m}$.  And of course $n+m$ is still an integer, so we have $(x,z)\in R$.

I have the same confusion with this one as the previous one. I get all the steps behind it but how do you get $(x,z)\in R$ from such steps?
For example does $(x,xe^n),(xe^n,xe^{n+m})$ imply $(x,z)\in R$?

I hope I can clear this confusion before it gets shut. I'm just really puzzled with the last steps. Can anyone help me please
Answer: In the first case, it is proved that for some integer $k$ ($k=-n$) $x=ye^k,$ i.e. $(y,x)=(y,ye^k),$ which is exactly the definition of $(y,x)\in R.$
Similarly, in the second case, it is proved that $z=xe^k$ for some integer $k$ ($k=m+n$), i.e. $(x,z)=(x,xe^k),$ hence $(x,z)\in R.$
Comment: Right, I think I understand. Thanks!
Comment: Quick question. Given $x=ye^{-n}$ and $y=xe^n$, can I substitute these expressions in the already known pair $(x,y)$ in R, let n = 0 and get $(ye^0,xe^0) = (y,x)$ as required?


Process tables by number of rows, row height, and alert if no tables exist in jquery

Question: I have this code right now:
var table = $(source).children('table').map(function() {
if (this.rows.length >= 4) {
    return $(this).outerHTML();
} else {
    return null;
}
}).get();

This will get tables by number of rows, but how would I get the tables by row height (if height < 100 px) also and also alert if no tables are in the array (if the array is empty).
Answer: Not sure what you mean by the first question, but for the alert:
if($(source).children('table').length===0){
   alert("no tables!");
}

Answer: You could use .is() method, like this:
var table = $(source).children('table').map(function() {
if ($(this).find("tr").is(function(){ $(this).height() < 100 }) {
    return $(this).outerHTML();
} else {
    return null;
}
}).get();
//Now check size:
if(table.length == 0) alert("There are no tables");

What are we doing with .is()? We are searching if at least one of the children tr has height lower than 100, and ignore the table if this condition is not fulfilled.
Hope this helps. Cheers
EDIT For your new demands:
  var table = $(source).children('table').map(function() {
    if (!$(this).find("tr").is(function(){ $(this).height() >= 100 } &&
         $(this).find("tr").size() > 4  ) {
        return $(this).outerHTML();
    } else {
        return null;
    }
  }).get();
  //Now check size:
  if(table.length == 0) alert("There are no tables");

Comment: I would also want to include if there are greater than 4 rows or not
Comment: and I also want ALL the rows to be less than 100


Closure operation is not necessarily preserved

Question:
If $(X,d)$ and $(Y,d')$ are metric spaces and if $f:X\rightarrow Y$,
  show that $f$ is continuous if and only if for every $A\subset X$,
  $f(\overline{A})\subset\overline{f(A)}$, and construct an example to show that the closure operation is not necessarily preserved by a continuous mapping. Moreover, if $f$ is a $1:1$ onto, show that $X$ and $Y$ are
  homeomorphic is and only if  $f(\overline{A})=\overline{f(A)}$ for all
  $A\subset X$.
Comment: What are your thoughts on the problem?
Answer:
Suppose first that $f$ is continuous and let $x\in\overline{A}$, which
           means that for any open set $f(x)\in O\subset Y$ we have $f^{-1}(O)\cap
         A\ne\varnothing$ because $x\in f^{-1}(O)$ and $f^{-1}(O)$ is open, but
           $f^{-1}(O)\cap A\ne\varnothing\Rightarrow O\cap f(A)\ne\varnothing$ indeed
           if $O\cap f(A)=\varnothing$ then
           $$\varnothing=f^{-1}(O\cap f(A))=f^{-1}(O)\cap f^{-1}(f(A))\supset
         f^{-1}(O)\cap A$$
           which is a contradiction with our initial assumption, so
           $O\cap f(A)\ne\varnothing$ for any open $O$ containing $f(x)$ so
           $f(x)\in\overline{f(A)}\Rightarrow f(\overline{A})\subset \overline{f(A)}$.
           Now suppose that for any $A\in X$, $f(\overline{A})\subset \overline{f(A)}$,
           Let $U=f^{-1}(O)\in X$ where $O$ is arbitrary open set of $Y$ we claim that
           $U$ is open. But for this note that $x\in \overline{U^{c}}
         \Rightarrow x \notin U$, indeed if $x\in U$ when we note that
           \begin{eqnarray*}
            &&f(U^{c})=f(X)\cap O^{c}\\
            &&f(\overline{U^{c}})\subset\overline{f(U^{c})}=\overline{
            f(X)\cap O^{c}}\subset\overline{f(X)}\cap\overline{O^{c}}=
            \overline{f(X)}\cap O^{c}
         \end{eqnarray*}
           which is certainly a contradiction, because $f(x)\in f(\overline{U^{c}})$
           but as we assume that $x\in U\Rightarrow x\notin U^{c}\Rightarrow
         f(x)\notin O^{c}$. So for every open $O$ $f^{-1}(O)$ is open and so $f$ is
           continuous. Now define,
           \begin{eqnarray*}
            f : \mathbb{R} & \rightarrow & \mathbb{R}\\
            x &\mapsto & e^{x}
         \end{eqnarray*}
           with the usual metric $f(\mathbb{R})=(0,\infty)$ which is not closed. Nos
           suppose that $f$ is one-to-one and that $f(\overline{A})=\overline{
         f(A)}$ for all $A\subset X$ then by what we have just proven $f$ is
           continuous, furthermore as $f$ is one-to-one we can rewrite
           $\overline{A}=f^{-1}(\overline{f(A)})$ now call $B=f(A)$ and recall that
           $f$ is a one-to-one map onto $Y$ so
           $$\overline{f^{-1}(B)}=f^{-1}(\overline{B})$$
           and so $f^{-1}$ is continuous too, and so $f$ is a homeomorphism.
           Conversely let $f$ be a homeomorphism. The as $A\subset\overline{A}
         \Rightarrow f(A)\subset f(\overline{A})$ recall that $f$ is a homeomorphism
           so $f(\overline{A})$ is closed and so $f(A)\subset f(\overline{A})
         \Rightarrow \overline{f(A)}\subset\overline{f(\overline{A})}=
         f(\overline{A})$, now let $y=f(x)\notin \overline{f(A)}$ then for some
           $\varepsilon>0$, $S_{\varepsilon}(y)\cap f(A)=\varnothing
         \Rightarrow f^{-1}(S_{\varepsilon}(y))\cap A=\varnothing \Rightarrow
         f^{-1}(y)\notin\overline{A}\Rightarrow y\notin f(\overline{A})$ so we
           have just proven that
           \begin{eqnarray*}
            \overline{f(A)}^{c}\subset f(\overline{A})^{c}\Rightarrow
            \overline{f(A)}\supset f(\overline{A})
         \end{eqnarray*}
           then $f(\overline{A})=\overline{f(A)}$, which finishes the solution.


In how many ways we can choose $k$ squares on $n \times n$ chessboard, given certain restrictions?

Question:
In how many ways we can choose $k$ squares on $n \times n$ chessboard, so that none of these squares are on the same column nor the same row?

Sorry, but the question is the same as in the title. Here are my poor attempts to the problem.

First we can choose one square from $n$ rows and $n$ columns so there are $n^2$ ways to do it.
Now we can choose one square from $n-1$ column and rows.
And so on...

Please help me
Comment: See the 'Choosing squares from a grid ....' under Related questions on the right
Answer: We can choose the rows that are used in $\binom nk$ ways, the columns that are used in another $\binom nk$ ways, and then choose which column get assigned to which row in $k!$ ways, for a total of $k!\binom nk^2$ arrangements.
Answer: We can go row by row. First, there are $\binom{n}{k}$ ways to choose which rows are in use. Then, there are $n$ ways to make the choice on the top row in use. Then there are $n-1$ ways to make the choice on the next row. In general the $i^{th}$ row will have $n+1-i$ choices, so in total there will be
$$
\binom{n}{k}\cdot (n\cdot(n-1)\cdots (n-k+1))=\binom{n}{k}\cdot\frac{n!}{(n-k)!}=\frac{(n!)^2}{k!(n-k)!^2}
$$
choices.


Solving equation with change of variable

Question: $$x^4+x^3-10x^2+x+1=0$$
I know the whole solution, but i can't understand some parts
So first we divide whole equation by $x^2$, then
$$\begin{eqnarray}
x^2+x-10+1/x+1/x^2 &=& 0 \\
\frac{x+1}{x} &=& t
\end{eqnarray}$$
So why exactly $\frac{x+1}{x}$ ? How do i need to know what i need to change?
Then $x^2+1/x^2=t^2-2$
Where did the 10 went?
Thanks instantly for help.
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: Your substitution here is not, in current form, expressed correctly - you need $t=x+\frac 1x=\frac {x^2+1}x$
Comment: Please, if you are ok, you can accept the answer and set it as solved. Thanks!
Answer: Setting
$$x+\frac1x=t$$
we have
$$x^2-10+\frac1{x^2}=\left(x+\frac1x\right)^2-12=t^2-12$$
thus
$$x^2+x-10+\frac1x+\frac1{x^2}=0\implies t^2+t-12=0$$
Answer: For all real $k$ we obtain:
$$x^4+x^3-10x^2+x+1=\left(x^2+\frac{1}{2}x+k\right)^2-\frac{1}{4}x^2-k^2-kx-2kx^2-10x^2+x+1=$$
$$=\left(x^2+\frac{1}{2}x+k\right)^2-\left(\left(2k+\frac{41}{4}\right)x^2+(k-1)x+k^2-1\right).$$
Thus, for $k=1$ we obtain:
$$x^4+x^3-10x^2+x+1=\left(x^2+\frac{1}{2}x+1\right)^2-\frac{49}{4}x^2=$$
$$=(x^2-3x+1)(x^2+4x+1).$$
Now, solve two quadratic equations.
Comment: always original (+1)!
Comment: I need a full course on inequality from you!
Comment: Thank you! I think it's very difficult to make it.
Answer: Because the coefficients are palindromic (read the same backwards as forwards), whenever $x=a$ is a solution of the equation, so is $x=\frac 1a$.
Thus the roots will be $x=\pm 1$ (which are easily identified and factored out) or come in pairs which will give factors of the form $$(x-a)(x-\frac 1a)=x^2-(a+\frac 1a)x+1$$If we set this equal to $0$ and rearrange we get $x+\frac 1x=a+\frac 1a$, from which we see that if we substitute $y=x+\frac 1x$ these two factors become a linear factor in $y$. Once you have the value of $y$ it is a simple matter of solving a quadratic to find the roots of the original equation.
"The substitution works" is one justification, but I hope this gives an idea as to why it works.
Answer: The idea here is to find some change of variable which makes the equation easier to solve. We might have guesses as to what to change, but we know we were right only if it ends up working out.
Here, you might guess to substitute $t = x + \frac{1}{x}$ because there are four different powers of $x$ in the equation -- $x^2$, $x$, $x^{-1}$, and  $x^{-2}$ -- and this substitution lets us combine $x$ and $x^{-1}$ into $t$, and hopefully $x^2$ and $x^{-2}$ into $t^2$, so that we'll only end up with two different powers of $t$, which is much easier to solve.
So let's try it and see how it works out.
From $t = x + \frac{1}{x}$ we compute $t^2 = (x + x^{-1})^2 = x^2 + x^{-2} +2$. So $x^2 + x^{-2} = t^2 - 2$. This is good because $x^2 + x^{-2}$ appears in our equation.
Our main equation is (rewritten to show where we will substitute):
$$ (x^2 + x^{-2}) + (x + x^{-1}) - 10 = 0 $$
(The $10$ is still there, we just won't substitute for it.) We now place our substitutions:
$$ (t^2 - 2) + (t) - 10 = 0$$
$$ t^2 + t - 12 = 0$$
And now we can proceed to solve for $t$.
Answer: Another technique worth considering is that on the real field you can theoretically factor polynomials into polynomials of degree at most $2$.
Can all real polynomials be factored into quadratic and linear factors?
When the coefficients are favourable, like in the present case the coefficients of $x^4$ and $x^0$ are both $1$, we can restrict our search for $$\begin{align}x^4+x^3-10x^2+x+1&=(x^2+ax+1)(x^2+bx+1)\\&=x^4+(a+b)x^3+(ab+2)x^2+(a+b)x+1\end{align}$$
Identifying the coefficients gives $\begin{cases}a+b=1\\ab+2=-10\end{cases}\iff a,b=-3,4$
And we are left with two quadratics we are able to solve.

Now we will see how this method relates to the suggested substitution $t=x+\frac 1x$
$f(x)=x^4+x^3−10x^2+x+1$
We can notice that $f(\frac 1x)=\frac 1{x^4}+\frac 1{x^3}-\frac{10}{x^2}+\frac 1x+1=\dfrac{f(x)}{x^4}$
So since $f(0)\neq 0$, if $r$ is root of $f(x)=0$ then $\frac 1r$ is a root as well.
It means we can factor
$\begin{align}f(x)
&=(x-a)(x-\frac 1a)(x-b)(x-\frac 1b)\\
&=\left(x^2-(a+\frac 1a)x+1\right)\left(x^2-(b+\frac 1b)x+1\right)\\
&=(x^2-t_ax+1)(x^2-t_bx+1)
\end{align}$
With the substitution $t_a=a+\frac 1a$ and $t_b=b+\frac 1b$, this is exactly what we solved in the first method.


What is the right way to use the "in" operator to compile a histogram?

Question: I'm working on implementing a histogram function for arrays in order to return an object that counts how many times an item appears in that array. However whenever I run this code I'm hit by an error message that suggests that the "in" operator cannot be used to search within the object.
var histogram = function(collection) {
  collection.reduce(function(combine, item){
    if(item in combine){
    combine[item]++;
    } else{
    combine[item] = 1;
    }
  }, {});
}
var arr = "racecar".split("");
console.log(hist(arr));

I'm guessing the problem here caused by either in or reduce but I can't figure out which it is. Any ideas?
Comment: You will probably want to avoid the [in operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in), it might not do what you expected.
Answer: A couple of things: 1) hist isn't the function name, 2) you're not returning anything from the function. I'm not sure how you're getting that error if you're not even calling the function properly, and something the console log would have warned you about.
var histogram = function(collection) {
  return collection.reduce(function(combine, item) {
    if (item in combine) {
      combine[item]++;
    } else {
      combine[item] = 1;
    }
    return combine;
  }, {});
}

DEMO
Here's a shorter version that doesn't rely on the use of in:
var histogram = function(collection) {
  return collection.reduce(function (combine, item) {
    combine[item] = (combine[item] || 0) + 1;
    return combine;
  }, {});
}

DEMO
Comment: Thanks Andy! Can't believe I left off two return statements, that fixes it. I guess I got thrown off by an error message that drew my attention the wrong way.
Answer: The problem with in operator is that it searches not only in array indexes, but also in all inherited properties of an Array object.
var ar = [];

'toString' in ar; // prints true
'length' in ar; // prints true

When used in an incorrect context (looking for indexes in an array) it may introduce potential problems that are hard later to debug.
In your case the best is to use Array.prototype.indexOf() or Array.prototype.includes() (from ES6).


Why do F1 drivers move towards the pit wall at the end of the race?

Question: On the last lap, at the start-finish straight, just as they are ending the race, F1 drivers (especially those at the front) move their car off the racing line towards the wall.
I'm guessing that they do that to make sure they won't be overtaken, but I can never find an explanation anywhere.
Why do they do so? Is there a rule that says you can't be overtaken on the outside at the end of the race?
Comment: AFAIK there's no such rule, but they might want to be as close as possible to the public to celebrate?
Answer: There's definitely no rule precluding being overtaken on the last lap / corner; it's all fair game (yellow "no overtaking" flags permitting in the event of an incident). Drivers simply do this "for show" and/or to acknowledge their team who may be gathered and celebrating on the pit wall as they cross the line. It's not limited to the leader either. For example a driver finishing unexpectedly higher than normal (e.g. 4th or 5th place) may do the same thing whereas a driver who is unhappy with their finishing position would typically not (even if they were in second place).
For example in this clip, Vettel (red car) crossed the line first but knew he had a penalty so knew he was effectively in second place. He very much did not celebrate as he crossed the line. Behind him, Hamilton (silver car) won and was happy so he swerved to his to team to celebrate:
Answer: At first this question seems to be off topic because any possible answer would be opinion based. However, if we analyse the speed and trajectory of all race winners when crossing the finishing line we could back up an answer with actual data. Of course, such data would be very hard to collect, so we have to use our (sometimes imperfect) memory.
I've been watching F1 races since the 70's. Back then it was very common (actually we could say it was the "rule") to cross the finishing line at full speed. The iconic image that comes to any F1 fan's mind is Colin Chapman throwing his hat in the air:
https://youtu.be/pSS6zONI0Zk?t=419
Look at the speed of the car, with a bunch of people on the track! The one at 7:20 is particularly scaring, completely unacceptable by modern safety standards.
The first driver I remember seeing slowing down at the finishing line and driving next to the pit wall was Schumacher. He started doing that during his Ferrari years, because during his Benneton years it was still common the race official waving the checkered flag at the track, which made impossible driving next to the wall1, as you can see here: https://youtu.be/aklM6-sjdl0?t=73. Then, almost all other drivers started imitating Schumacher and now it's quite common.
The reason? The other answer already explained: celebrating with the crew. By the way, until today I always pay attention to the driver crossing the finishing line, just to see if he will cross at full speed, like Leclerc at the last race on Monza (on that occasion because Bottas was on his tail).

1 Actually, we can argue that slowing down and crossing the finishing line next to the pit wall became possible only after the checkered flag started to be waved at an elevated position. Since the checkered flag being waved at an elevated position was part of the mid-90s safety improvements, even if my memory fails and Schumacher was not the first one, we can determine that drivers started crossing the finish line next to the pit wall around that period.
Comment: @Criggie well, it's complicated because most of the times the cameras shooting the main straight are at the end (of the straight) or opposite to the pit wall. Actually, since F1 cars are so low, driving too close to the pit wall will hide the car (from the cameras positioned in the pits). But I agree that the car with the crew cheering gives a good photo, which is only possible driving next to the pit wall, so there is a "framing" reason for that.
Comment: Is there a cynical answer in that's where the cameras are, so being closer to the lens will give a better photo ?


Uniform $L^1$ convergence of a double sequence of random variables.

Question: Let $X_n^m$ be a double sequence of integrable random variables such that $X_n^m \rightarrow_n X^m$ in probability, where $X^m$ is another sequence of integrable random variables. Assume that such convergence is uniform in $m$ and that $X_{n}^m \rightarrow_n X^m$ in $L^1$.
Does it follow that $X_{n}^m \rightarrow_n X_m$ in $L^1$ uniformly in $m$?
Thanks
Answer: It does not follow from the assumptions: take $X_{m,n}:=mn\cdot \chi_{(0,n^{-2})}$ on $(0,1)$ endowed with Lebesgue measure. We have for $\varepsilon\lt 1$ and each integer $n$,
$$\sup_{m\in\mathbb N}\mathbb P\{|X_{m,n}|\gt \varepsilon \}=n^{-2},$$
hence there is uniform convergence in probability to $0$. We also have $\mathbb E[X_{m,n}]=\frac mn$, hence we have convergence in $\mathbb L^1$ to $0$, but this convergence is not uniform in $m$.


For a real valued function $f(x,y)$ on $\mathbb{R}^2$ which is in $L_2$, show that $f(x+ε,y+ε) → f(x,y)$ in $L_2$ when $ε → 0.$

Question: For a real valued function $f(x,y)$ on $\mathbb{R}^2$ which is in $L_2$, show that $f(x+ε,y+ε) → f(x,y)$ in $L_2$ when $ε → 0.$
Not sure how to go about this problem.  I tried Fubini.  But that didn't seem to work well.  I tried doing t straight from the definition.  It seems the point is that it epsilon is changing the $x$ and $y$ coordinate at the same speed.
Comment: Have you tried dominated convergence? [The same speed isn't really an issue at all.]
Comment: Yea.  What could you dominate it by?
Comment: Oh I see you can use the alternative version where you dominate each of the $f_n$ individually by $g_n$ and then show that you can bring the limit in for the $g_n$.
Answer: Approximate $f$ in $L^2$ by a sequence $f_n$ of smooth compactly supported functions. Take a $\delta>0$. For sufficiently large $n$, one has $||f-f_n||<\delta$ and $||T_\epsilon f-T_\epsilon f_n||<\delta$ for all $\epsilon$, where $T_\epsilon g(x,y)=g(x+\epsilon,y+\epsilon)$. Fix such an $n$ and take $\epsilon$ small enough that $||f_n-T_\epsilon f_n||<\delta$. Then $||f-T_\epsilon f||<3\delta$.
Answer: Hint. For $f \in C_c(\mathbb R^2)$ the property follows by using uniform continuity of $f$ and dominated convergence (note that $f$ is bounded on its compact support). Now use that $C_c(\mathbb R^2)$ is dense in $L^2(\mathbb R^2)$.


array with 1 element causing error in for loop

Question: I'm using the array length as the test condition in my for loop. But if there is only one element in the array, I receive an 'Index was outside the bounds of the array' error. What am I doing wrong? Thanks.
string templateList;
string[] template;

string sizeList;
string[] size;

templateList = textBox1.Text;
template = templateList.Split(',');

sizeList = textBox2.Text;
size = sizeList.Split(',');

for (int i = 0; i <= template.Length; i++)
{
    for (int j = 0; j < size.Length; j++)
    {
         //do something with template[i] and size[j]
    }
}

the values are coming from a textBox, the user may only enter one value. In which case it would only need to run once.
Comment: You would probably be better served using [foreach](http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx). Index math is really a waste of time in C#.
Answer: Array is zero-based index, i.e first element has zero index. template[0] points first element. When you have only one element template[1] will refer to second element which is not present and you will probably get out of index exception.
Change
for (int i = 0; i <= template.Length; i++)

To
for (int i = 0; i < template.Length; i++)

Answer: Using...
for (int i = 0; i <= template.Length; i++)

...on the last iteration i will equal template.Length.  template[template.Length] will always result in an IndexOutOfRangeException.  Since the last element of template actually has index template.Length - 1, you should instead use...
for (int i = 0; i < template.Length; i++)

Answer: Count start from zero, you have to change your first for statement into:
for (int i = 0; i < template.Length; i++) {....}


Drupal 6 adding iframe tag to content editor?

Question: hi how would I added the iframe tag to the content editor? I have the input format set to Full HTML but still it does not allow the iframe tag.
Answer: Goto admin >> input formats, and add the iframe tag to Full HTML filter you're using for pages. That should do it.
To Clarify:
If in your list of filters you have "HTML Filter" Checked then you can manage the list of HTML tags.
However if you do not then you will need to check the filter on the wysiwyg editor you are using, so go to the config for they wysiwyg editor section you have installed.
Comment: thats what I thought too, but apparently you can not add tags to the FULL HTML Filter
Answer: In this link: http://web.maetschl.com/node/14
I use a iframe.. with full html, and works
<code><iframe src="http://web.example" width=700 height=700>
</code>
Comment: are you using version 6? I'm using a node for a blog and it keeps showing the html coding when I preview.


Adding functionality to a static website using ruby on rails

Question: I am new to ruby on rails.
I have a website with a lot of static pages. I want to add a number of dynamic pages to the website and these I am going to develop in ruby on rails. The functionality offered by these pages will be triggered when the user clicks on one of the buttons which is on one of the static pages. I am thinking that I will put the dynamic pages in a directory and one of them will be called(executed) when the button, which is on one of the static pages, is clicked. I do not need to change the content of existing static pages.
Is it possible to add such dynamic pages to existing static website? If yes, how? Do I need to change routes?
Answer: you have to do it the other way round - put your static pages into your rails applications 'public' folder - if a file identified by an url exists, rails will serve these file, if no file exists, rails will try to find a suitable controller/action ...
Comment: if there is some php/python you should write it in your question and not after that somebody gave you an answer
Comment: And in case there are some php/python pages in addition to the static pages then also they will be preffered over rails?
Comment: I agree, I should have asked earlier. Actually as far as I know there is no php/python script but now I am thinking that I might need to add a script for some other purpose.
Comment: Akshey: The ability to handle php/python depends on your webserver. I expect passenger to be able to handle it with out problems, but not mongrel or webbrick.
Comment: follow up to EmFi: i have a few sites using rails + php / python on passenger (for example wordpress in a subfolder of public) - easy to setup, works without problems. depending on the passenger version and php/python application you might need a rewrite in your htaccess to redirect the url /myphpapp/ to /myphpapp/index.php
Answer: I would recommend that you set up the Rails app and then move all the static content to the public folder. Rails will prefer those files. Then begin to create your dynamic content with the Rails app and just link to the dynamic pages / "actions" from your static pages.


General-to-specific subset selection ("Autometrics") performing well in macroeconomics

Question:
I wonder why general-to-specific (GETS) subset selection and particularly the Autometrics algorithm are performing well in macroeconomic modelling/forecasting.

How does Autometrics work?

Doornik "Autometrics" (2009) offers a full description (see p. 7-8 for the algorithm scheme).
The algorithm is based on stepwise subset selection with qualifications and includes diagnostic testing.
A few main features are listed below.
The general model is formulated as a linear model with
(i) main variables,
(ii) generous lags thereof, and in later versions also
(iii) impulses (for impulse indication saturation (IIS) or step indication saturation (SIS) techniques - to account for possible structural breaks) and
(iv) nonlinear transformations.
The algorithm does stepwise selection starting from a general model and going down several paths.
Variables may not only be removed but also added at each step (except the initial step where all the variables are included).
Significance testing is used for variable removal/inclusion.
When the search terminates (based on significance of variables), diagnostic testing is carried out. Poor models are removed from further consideration.

How well does Autometrics perform?

Good performance of Autometrics is apparent from works of Sir David F. Hendry, Jurgen A. Doornik et al. (in the links, see works on model selection, Autometrics and related).
Of course, independent authors' experience would be more credible than the experience of the "fathers" of Autometrics.
Kock & Teräsvirta "Forecasting performances of three automated modelling techniques during the economic crisis 2007–2009" (2014) find:

[Autometrics] works well when the model is a reasonable approximation to reality, but less well when it is not. In direct forecasting, one is facing the latter situation... It appears that Autometrics may not be an appropriate tool for building models for direct multiperiod forecasting. However, it can be an excellent choice when the data-generating process is approximated well by a subset of variables in the data set of the researcher.

Epprecht et al. "Comparing variable selection techniques for linear regression: LASSO and Autometrics" (2013) find that Autometrics and LASSO outperform each other in different respects and different settings.
The typical setting in Hendry's own performance testing of Autometrics is when the correct model is a subset of the general model. Autometrics is shown to select a model that is either the true one or very close to it.
Meanwhile, under tapering effects or considerable misspecification of the general model Autometrics may perform less well, e.g. as in Kock & Teräsvirta (2014) above.

Why is good performance surprising?

With no shrinkage and having to select among a large number of variables (that is the setting in many of Hendry's and Doornik's works), I would anticipate GETS to fail. (E.g. Frank Harrell has condemned subset selection in several posts, e.g. 1 and 2, although the posts were not specific to macroeconomic time series.)
(Question) Could the good performance of GETS and Autometrics be specific to the applications (mostly macroeconomic time series modelling),
or is Autometrics just a really good method in a broad sense?

"LASSO/LARS vs general to specific (GETS) method" is a related question.
Comment: @luchonacho, lucky you! Hendry should probably have been awarded the prize together with Engle and Granger. In my humble and ill-informed opinion, all three of them were giants in the field. I especially admire Granger and then Hendry, I think.
Comment: Interesting post/question. It seems to me that autometrics is very taylored to time-series macroeconomics. Consider however model selection in panel data, where there is a whole array of other issues involved, e.g. clustering choices, unobserved heterogeneity, selection, missing data, and etc. I would be very keen to see a simulation of autometrics' performance in that context. Also, in models with heterogeneous agents, autometrics is helpless. Hendry said this himself to me once.
Comment: @luchonacho, glad you found it interesting. I also envy your for having discussed this with Hendry himself! My gut feeling about GETS/Autometrics is skeptical, and I cannot even say why exactly, but I have met some proponents (e.g. the author of the R package `gets`) who are quite enthusiastic about it.
Comment: He taught me econometrics :) Autometrics is a kind of religion around here. You know, he is the original author of the cointegration concept, which he discussed with Granger, who went on and published and became famous (even to the Nobel prize level) for it, without ever acknowledging Hendry. It's sad actually.
Answer: Frank Harrell does not rule out intelligent use of backward elimination. He includes as a possibility (page 97, RMS, 2nd edition):

Do limited backwards step-down variable selection if parsimony is more
  important than accuracy.

This, however, is only to be done in the context of an already well-specified model. It is the last step before the "'final' model."
As this paper linked from the related question emphasizes, the variable selection in GETS must begin with an already well-specified model:

The search should start from a congruent statistical model to ensure that selection inferences are reliable. Problems such as residual autocorrelation and heteroscedasticity not only reveal mis-specification. They can deliver incorrect coefficient standard errors for test calculations. Consequently, the algorithm must test for model mis-specification in the initial general model.

This is a good deal different from many questions on this site, where those without much evident statistical background often seem to want a plug-and-play approach to the entire problem. They start with some type of multiple regression, give little thought to underlying subject matter, data transformations, the peculiar problems in time series, or the like, and want to determine automatically "what are the most important variables"?
Also, GETS seems inherently inapplicable to the $p>n$ setting, where so much of the difficulty (and interest, and poor statistical technique) in variable selection arises. Although time series are outside my expertise, I suspect that large time series from which autocorrelations have been removed effectively provide $n\gg p$, with many degrees of freedom left. I also wonder (without any solid knowledge of time series) whether removing time-based autocorrelations may in practice help minimize other sources of non-orthogonality among predictors.
The various flavors of GETS pay a good deal of attention to tradeoffs between Type I and Type II errors in the steps of the reduction of the initial well-specified model to a reduced form, which may obviate shrinkage corrections (or include them implicitly in the estimates of the reduced model).
Comment: Actually, *Autometrics* specifically emphasizes that it works fine with $p>n$. The initial general model in the late versions of *Autometrics* is *by default* $p>n$ as it includes $n$ orthogonal dummies for structural breaks. But I am not sure if it works well when $p>2n$ where $n$ variables are orthogonal dummies but the remaining $p-n$ variables are not orthogonal dummies.
Comment: I also wonder how a smart GETS like *Autometrics* could *obviate shrinkage corrections (or include them implicitly in the estimates of the reduced model)*. If this is indeed the case, then GETS becomes an attractive modelling tool (because lack of explicit shrinkage in GETS is the most obvious drawback to me).
Comment: Any thoughts regarding my comments?


Measurable functions and compositions

Question: Let $(Y,S)$ a measurable space and $\phi :X\to Y$ any function where $X\neq \emptyset$.
Suppose that $f:X\to\mathbb{R}$ is measurable over $(X,S')$, where $S'=\phi^{-1}(S)$. I want to prove that there exists $g:Y\to\mathbb{R}$ measurable such that $f=g\circ\phi$.
How can we define such $g$?
Thanks!
Answer: This is a result due to Doob and Dynkin.

When $f$ is the characteristic function of an element of $\mathcal S'$, it is clear.
By linearity, we can deal with the case where $f$ is a linear combination of characteristic functions of measurable sets (simple function).
If $f$ is measurable and non-negative, there is a sequence $(f_n)_{n\geqslant 1}$ a sequence of simple functions such that for each $x\in X$, $f_n(x)\uparrow f(x)$.  Consider the $g_n$ obtained in 2. and notice that the sequence $(g_n)_{n\geqslant 1}$ is pointwise non-decreasing. The limit will be the wanted $g$.
To solve the general case, write $f$ as a difference of two non-negative measurable functions.

Measurable functions and compositions


Proof using Division Algorithm where divisor is the least element of the set $S$ = {$ma + nb$ : $m,n \in \mathbb{Z}$ and $ma + nb > 0$}

Question: Required To Prove: Let $a$ and $b$ be integers. Let $S$ = {$ma + nb$ : $m,n \in \mathbb{Z}$ and $ma + nb > 0$}, and $d$ be the least element. Show that $d$|$a$.

The following is how I attempted my proof:
Consider $d$ is not a divisor of $a$, i.e. by the Division Algorithm, $a = qd + r$ for $r \in \mathbb{Z}, 0 < r < d$. (Note that $0 < r$ since we are considering that $d$ is not a divisor, i.e. there must be a remainder of sorts).
Since $d \in S$, $d >= 1$.
It follows that $0 < r < 1$, since $d >= 1$.
However, $r \in \mathbb{Z}$, and since $0 < r < 1$, we have a contradiction. By definition of the remainder then, $0 <= r < 1$ i.e. $r = 0$.
Therefore, $d$ must be a divisor of $a$.

I am not entirely sure about the proof, however I have some doubts about the question as well. Consider the case where $a = 5$ and $b = 3$. In this case. Then the least element is 2 ($m = 1$, $n = -1$). In this case, 2|5 cannot be the case. I am not sure if the question is asking for some specific values of $a$ and $b$ in the set $\mathbb{Z}$, or if for all values of $a$ and $b$.
Regards,
Xandru
Comment: In your last paragraph, you say that $2$ is the minimal element, however note that $5 - 2 \cdot 2 = 1 < 2$
Comment: @Zestylemonzi oh good catch! Thanks for pointing that out. In that case, consider for example a = 11 and b = 7...the least element would be 4 in this case.
Comment: Again, $2 \cdot 11 - 3 \cdot 7 = 1 < 4$. In fact, the extended Euclidean algorithm shows that given $a,b \in \mathbb{N}$ then there exists $n,m \in \mathbb{Z}$ such that $an + bm = \text{gcd}(a,b)$. Hope this helps.
Comment: See [this answer](http://math.stackexchange.com/a/1835315/242) for a conceptual viewpoint on such proofs.
Answer: You're not using that $d\in S$, so your proof is surely flawed. In particular the fact that $d\ge1$ does not allow you to argue that $0<r<1$; for instance, if $a=6$ and $b=9$, we have $d=3$, so you can only say $0<r<3$.
Since $d\in S$, you can write $d=ma+nb$ for some $m,n\in\mathbb{Z}$. Therefore
$$
a=dq+r=mqa+nqb+r
$$
and
$$
r=(1-mq)+(-nq)b
$$
Also $0\le r<d$. If $r>0$ we'd have…

Note that for $a=5$ and $b=2$, we have $d=1$, because $1=1\cdot 5+(-2)\cdot 2$. Indeed, $d$ is the greatest common divisor of $a$ and $b$, in general.
Comment: However I did use that $d \in S$...in fact I wrote $d >= 1$, since if we let $d = ma + nb$ (as you have said), then $d > 0$, since by the definition of the set $S$, $ma + nb > 0$.
Comment: @XandruMifsud The fact that $d\ge1$ does not allow you to conclude that $0= 1$, then $r < 1$, no?
Comment: Yes I was aware of that particular case, and many others like it. However, if the definition of the set says that the smallest possible divisor is 1, then for what reason is my reasoning flawed? Why is saying $r < 1$ wrong is $r < d$?
Comment: @XandruMifsud Suppose $d=42$; then $0<23<42$. You could conclude if you had $d\le1$, but unfortunately it is not the case.


What to do with a svn-commit.tmp

Question: Every time I do a status on svn using terminal I get this file.
?      svn-commit.8.tmp
I know its a failed commit comment file but how do I get rid of it. I don't know if I should rm it or how to deal with it.
Comment: just delete it if you dont need the commit message anymore.
Answer: Removing it is just fine; it's unversioned and all of the text is stored in the SVN log anyways. If your commit fails, you can reuse it by calling:
svn commit -F svn-commit.tmp

subversion will then automatically remove your svn-commit.tmp file.
Comment: How in the world was this not chosen as the answer? This accurately shows what the tmp file was there for.
Comment: This will commit all files that have been modified, not just the one(s) listed in the .tmp file. Very annoying.
Comment: Let's assume two modified files, a.txt and b.txt. Initially you try to commit a.txt (svn ci a.txt -m "commit message). This fails for some reason, and the message is saved in svn-commit.tmp. Fix whatever caused the failing, and run svn with the -F switch (svn commit ci -F svn-commit.tmp). Now b.txt will be included in the commit, although it wasn't part of the intial faild commit.
Comment: However, the file is not deleted automatically.
Comment: @Maxime - My commit messages are always deleted after I use the `-F` option. Maybe it's the specific version I use...
Comment: I run svn, version 1.7.5 (r1336830) and the documentation (`svn help commit`) does not specify that the file is deleted : `-F [--file] ARG          : read log message from file ARG`
Comment: @Maxime - Yeah, the more I read about it across the web, it looks like I've experienced odd behavior. The SVN devs specifically made it to *not* remove the file in case you want to keep using your commit message. Since I've moved to git and no longer have SVN on this machine, I can't test it.
Comment: @klokop - The .tmp file contains the commit message that you typed in. Since the commit didn't happen due to a conflict, SVN saves your message so you can use it later...to commit all of your files that failed when the conflict happened. I think you're missing the point of the question.
Comment: @klokop - I'm operating from the assumption that your original commit command was `svn commit`, so you rerun that with your message as `svn commit -F svn-commit.tmp`. In your scenario, you start with `svn ci a.txt ...`, so you can reuse your message _without_ committing `b.txt` with `svn ci a.txt -F svn-commit.tmp`.
Answer: Just rm it.
The reason it's left behind when a commit fails is so that you don't lose the (potentially long) commit message that you just wrote -- you can open the file in a text editor and paste the text as the commit message of your next commit when you fix the problem that prevented your first commit.
Answer: Remove it using svn rm --force yourfilename
better than just rm because rm doesn't make it to version tracking
Comment: This is not better, it makes no sense for this file to be added / commited.
Comment: svn rm --force yourfilename can be useful when you did a svn add yourfilename before and you don't want to commit this file, the --force is needed in this case because svn will refuse to delete a file that is changed locally as this would remove the non-saved modifications to this file.
This is the only moment this is useful, else this is needless clutter.
I downvoted this answer because this is not better as this is not the problem. This is even a confusing answer as it makes it look like the svn-commit.tmp is tracked by svn, but it is not.
Comment: how is this different from RustyTheBoyRobot's answer?
Comment: I don't understand what is similar between your answer and RustyTheBoyRobot's one ?
Or maybe I wasn't clear when I used the term 'commited' ?
$ svn commit -F svn-commit.tmp is useful as it uses the message inside this file to explain the change behind the commit. The file itself is not commited, so using svn rm --force svn-commit.tmp instead of rm svn-commit.tmp is just trying to solve a problem that doesn't exist.
Comment: commit vs rm. gotcha. It's been a while. I had to use force to get rid of it. regular rm wouldn't do it. I'm not sure what the underlying theory behind it is. I'm just going by my empirical experience. There didn't seem to be any problems by removing it.
Comment: Thanks for your thoughts Tic. I value the thinking behind it.

What to do with a svn-commit.tmp


scala sbt-launch.jar - multiple projects ihe same directory?

Question: I'm sure this is simple, but I haven't figured it out yet...
I've installed sbt-launch.jar and a shell script to execute it (named sbt).
How do I put multiple projects in the same directory?
When I run sbt the directories project and target get created and populated, and the current project is default-XXXXX. The compile command picks up source files in the top-level directory and jar files in the top-level 'lib' directory.
How do I add another project under the same directory? Every time I run sbt in an empty directory it creates a 20+ MB project directory.
Note 1: when I run sbt I an not getting asked "Create new project?" or any other questions.
Note 2: I am using sbt-launch.jar from this url: http://typesafe.artifactoryonline.com/typesafe/ivy-releases/org.scala-tools.sbt/sbt-launch/0.10.1/sbt-launch.jar
and I'm following the instructions at: http://code.google.com/p/simple-build-tool/wiki/Setup
Answer: Found the answer (for sbt 0.10.1):
Create the file project/Build.scala that looks like this:
import sbt._
object MyBuild extends Build
{

  lazy val root = Project("root", file("."))
  lazy val sub1: Project = Project("proj1", file("dir1"));
  lazy val sub2 = Project("proj2", file("dir2"))
}

This creates three projects 'root' (in the top-level directory), 'proj1' (in the sub-directory 'dir1') and 'proj2' (in the sub-directory 'dir2')
For more info, see https://github.com/harrah/xsbt/wiki/Full-Configuration
Comment: Note that this is only for SBT 0.10.x, not 0.7.x (as suggested by the URL of the SBT binary). The same thing is possible in SBT 0.7 with a different syntax.


Weakening hypothesis without a cut

Question: I often find myself in the following situation, where I have proven a lemma which is an implication:
Lemma L1: A -> B

where in fact the equivalence A <-> B is provable, but the implication B -> A is a trivial and not a very interesting result. Then in the course of designing some proof, I end up with the hypothesis:
H : A

and I actually want to use B. I can use a cut:
cut (B).

and proceed from there, but I am sure there is a quicker way to formally weaken hypothesis H, replacing statement A by B.
What I have been doing lately is go back to my lemma and prove both side of the implication.
Lemma L1 : A <-> B

then use a simple rewrite L1 in H. So this works for equivalences but not in general of course. So how do I weaken an hypothesis without a cut from a simple implication?
Answer: indeed, this is a common occurrence and some Coq plugins such as ssreflect provide special support for it, called "hypothesis view". IMHO a rewrite may not be so bad in your case.
Coq 8.5 introduces an experimental p%term feature to perform "views" on the hypotheses, so you could do:
Variables (A B C : Prop).
Hypothesis U : A -> B.

Lemma L1 : A -> B.
intros h%U.

but note that this feature is likely to be removed. Of course, if you are open to using the ssreflect tactic language views are an essential feature and you can just do:
Variables (A B C : Prop).
Hypothesis U : A -> B.

Lemma L1 : A -> B.
by move=> /U.

Views in ssreflect prodive many more goodies, for instance, if you have a hypothesis B and a lemma U : A -> B -> C you can usually apply /U, etc... see the manual for more details.
Answer: One simple way to do that is to use apply L1 in H..
Variables A B : Prop.
Lemma L1 : A -> B. Admitted.

Theorem theorem : A -> 1 = 1.
  intros H.
  apply L1 in H.

The last line turns H : A into H : B.

Weakening hypothesis without a cut


getDayOfMonth throws NullPointerException

Question: I'm trying to get the selected date in a dialog but unfortunately I got NullPointerException.
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            LayoutInflater inflater = getLayoutInflater();
            builder.setView(inflater.inflate(R.layout.dialog_add, null));
            builder.setTitle("Add new event");
            builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DatePicker datepicker = (DatePicker) findViewById(R.id.ad_date_picker);
                    ContentValues values = new ContentValues();
                    values.put(DbHelper.COLUMN_NAME_DAY, datepicker.getDayOfMonth());
                    values.put(DbHelper.COLUMN_NAME_MONTH, datepicker.getMonth());
                    values.put(DbHelper.COLUMN_NAME_YEAR, datepicker.getYear());

                    DbHelper dbHelper = new DbHelper(getApplicationContext());
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    db.insert(DbHelper.TABLE_NAME, null, values);
                }
            });
            builder.show();

Stack trace:
03-02 17:34:31.890: E/AndroidRuntime(1619): FATAL EXCEPTION: main
03-02 17:34:31.890: E/AndroidRuntime(1619): java.lang.NullPointerException
03-02 17:34:31.890: E/AndroidRuntime(1619):     at com.dennis.countdown.MainActivity$1$1.onClick(MainActivity.java:38)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at android.os.Looper.loop(Looper.java:137)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at android.app.ActivityThread.main(ActivityThread.java:5193)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at java.lang.reflect.Method.invokeNative(Native Method)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at java.lang.reflect.Method.invoke(Method.java:511)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-02 17:34:31.890: E/AndroidRuntime(1619):     at dalvik.system.NativeStart.main(Native Method)

The DatePicker is in the XML file because I need a custom dialog with title field and a date picker. I didn't find any other way to do this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
    android:src="@drawable/ic_launcher"
    android:layout_width="match_parent"
    android:layout_height="64dp"
    android:scaleType="center"
    android:background="#FFFFBB33"
    android:contentDescription="@string/app_name" />
<EditText
    android:id="@+id/title"
    android:inputType="textEmailAddress"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginBottom="4dp"
    android:hint="Title" />
<DatePicker
    android:id="@+id/ad_date_picker"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_margin="5dp"/>
</LinearLayout>

Comment: One of `R`, `R.id`, or `datepicker` must be null. So which line is 38?
Comment: Have you set any values to the DatePicker on xml?
Comment: @Dennis I mean which line of code is line 38? The one from the stack trace. Otherwise we're just guessing at what is throwing the exception. The exception is clearly your from code, so it's going to be something with a `.` member accessor.
Comment: @lc. Line 38 is: ``values.put(DbHelper.COLUMN_NAME_DAY, datepicker.getDayOfMonth());`` @IronBlossom I posted the xml file above.
Comment: @Dennis Yeah, so probably `datepicker` is null (`DbHelper` is a static class, not an instance so it should never be null)...you can work backwards from there
Comment: It's an xml thing so clean project then run.. And check
Comment: Initialize your DatePicker outside the builder
Answer: Your DatePicker is null, When you try to access datepicker.getDayOfMonth(), it throws NPE
You need to initialize your DatePicker in onCreate
  DatePicker datepicker = (DatePicker) findViewById(R.id.ad_date_picker);

if your date picker is there in inflatted view than get it from the inflatted view
 DatePicker datepicker = (DatePicker) inflattedview.findViewById(R.id.ad_date_picker);

Answer: My problem was solved with help of Pragnani.
Instead of:
LayoutInflater inflater = getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null));
DatePicker datepicker = (DatePicker) findViewById(R.id.ad_date_picker);

I used:
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_add, null);
builder.setView(view);
DatePicker datepicker = (DatePicker) view.findViewById(R.id.ad_date_picker);


Node translation vs. Entity (field) translation

Question: I would like to know what you guys recommend for a multilanguage site. For example, consider the following case: A page and its content should be available in 3 languages (e.g. German, English, and Spanish); the site uses one profile type, several content types and views, taxonomy, taxonomy-references, node references, user and field references, field collections, menues and so on. All of this informations should be translatable.
As far as I know, there are two ways to obtain this: with Entity Translation and the "node-based" method, or the usual one with the Internationalization modules and l10n.
What way should I choose? In which case and why should I consider a method instead of the other?
Answer: Randy Fay recently created a post discussing the possibilities achieved with of Entity Translations, where Gabor Hojtsy commented on some of the considerations to weigh:

Some good things offered by [good old] node translation include support for separate node commenting (eg. your German and English comments will not be intermixed); support for per language revisions; publication workflows (eg. the German node can be in a pre-publication revision workflow while the English is already published, coordinated actions can publish multiple language versions when all reach a certain step in the workflow, etc); different permission handling (eg. certain people can only edit German translations not English originals), thanks to Drupal's excessive node access system, etc. Think about menus. Most sites do not plan to have 1-1 menu structures for all translated versions.

The major caveat as I see it for Content/Entity/field-level Translation right now boils down to that age old Drupalism special case: the node title... Its not really a field, so its not translatable without another module, and potentially some patch work.  As of right now, I think field translation is still very much "experimental" ground, but more power to you for pushing forward into new territory.
Comment: Thank you. Very interessting points and pro's for node translaion.
Answer: Suzanne Kennedy and Florian Loretan's presentation at DrupalCon Denver addressed this question.  It seems like entity translation is the way of the future and is at least partly slated for integration into core.
Their recommendation was to use entity translation unless you need support for revisioning.
Comment: Indeed, Entity Translation is now part of Drupal 8 Core. According to [its project page](https://www.drupal.org/project/entity_translation).
Answer: I used Node translation but now after I tried Entity Translation, it's definitely my favorite one!
I think the main problem is the import function with Entity Translation, because there is a long discussion in the Drupal community. Otherwise I read about a new module, but I haven't tried it yet. But I will give you my feedback afterwards!
If you combine Entity Translation with the Title module, you can translate everything. I also prefer the module "Localization update".
So you have to install and enable these contributed modules:

Entity Translation.
Title.
Localization update.

And you have to enable these core modules:

Locale.
Content Translation.

Good Luck!
Comment: Great summary about this topic, +1 !
Comment: could you explain why core "content translation" module should be enabled when using  entity_translation ?
Answer: I know I'm raising the dead here but:
From what I can tell, the 6-style node translation method (each translation is a new node) is still the only useful way to translate content, having the benefits of being what everyone is used to and being functionally complete. (Node titles are not fields in 7, and therefore cannot be field-translated, among other silly shortcomings.)
You're always going to use i18n/locale, the only choice (which isn't really a choice) is node level or field-level translation, of which only node translation is likely to be useful.
Edit: Since this was written, Entity Translation + Title module have made field-level translation very effective. If you can use them, you should.
Comment: It's a contrib module, but the Title module (http://drupal.org/project/title) allows node titles to be converted to function as fields.
Answer: Entity translation makes much more sense in most cases than node translation; but sadly it isn't really a viable option for D7 as many modules still do not support it. People that do presentations and show how great it is simply are only doing very simple work. For example, something as common/popular as field collections is still not supported by ET.
When we start a new multilingual site we always start with ET since it is a great idea. We stick with it until we find too many issues with things not being compatible.. and then eventually we switch back to the old D6 method.
Comment: Could you provide some more details on the difficulties you've experienced? We're in the same situation you described (creating a new site, need to decide model we're going to use for translation), and I'm wondering if our site is simple enough we won't encounter the problems you have. Knowing more details of your experiences would be extremely helpful.
Comment: There are over 6000 modules for D7; hard to say which ones will work and which won't. I know field collections does not translate properly with ET. I am sure there are others. Best bet is to try out each bundle as you create it and see if it can be translated using ET. You can mix ET and NT in the same site; but not within the same bundle. That makes ET more dangerous as if you end up adding a field type later that you hadn't previously verified and it isn't supported; or you add some functionality not supported; you might be in trouble.


Display price on Views for product variation

Question: I'm confused, how to display on Views just one price for product with variations? I have product with 2 variation, and both prices are displayed, like:
Price: 1-Price for 1-Variation-Product , Price: 2-Price for 2-Variation-Product
I mean the created from me some custom view-page, like "/all-products" (like some catalog page) where are displayed all of products or goods with their prices. And for the products with variations I see, that there will be displayed all of prices of this product.
In the Settings of View-Page ("/all-products") I have in Format section: "Show:Fields | Settings".
In RELATIONSHIPS:
Variations: Product variation
(Variations: Product variation) Product: Product
And in Fields I have:
(Variations: Product variation) Product variation relationship: Price
where in the Setting I have:
"Use entity field rendering"
There are no Setting to handle multiple values.
If I check out "Use entity field rendering" then will be shown some settings for handling of multiple values, but in this case it will be no price displayed on view-page (/all-products), because the prices are rendering from product entity, as I understand.
So, this is the problem
In addition: the product with variation has all the same price, not different prices for different variation.
What is teh best way to handle it?
I have Drupal 9, Commerce 2
Thanks
Comment: Very keep on achieving this this too. Did you work it out? My use case is a views page for a search api / facets-based product catalog. My add to cart is using the Variation Title widget.
Answer: I think I found a solution, in "Fields" just instead
"(Variations: Product variation) Product variation relationship: Price"
need to use:
"Product datasource: Variations", and there are some settings to handle multiple values.
In "Formatter" need to set "Rendered entry", instead default "Label"
Answer: It depends on how your view is configured, but here is a basic setup that will only show one price.
Create a view of Products with the Default view mode.
Then configure the Default view mode at <code>/admin/commerce/config/product-types/MY_PRODUCT_TYPE/edit/display</code>.
For Variations, you can change the Format to Add to cart form, which will show a dropdown for selecting the variations and the price of the current variation only.  You can check out the other options too; one of them may be better for your use case.
Comment: thanks for answering, but this settings I have already and on Product page I have dropdown for selecting the variations. With my question "Display price on Views " I mean the created from me some custom view-page, like "/all-products" (like some catalog page) where are displayed all of products  or goods with theyr prices. And for the products with variations I see, that there will be displayed all of prices of this product.
Comment: @lexx You need to describe exactly how you created your custom view page; what is displayed is controlled based on the settings, so without you sharing the exact settings, it is not possible to help you.
Comment: @lexx You should edit your question to include this information instead of posting it in a comment; that way, people who visit this question page will find all the information in the question.
Comment: Ok, thanks. I changed the question and delete my comments from above


HTML DOC --logoimage

Question: I am trying to put different header and footer images while creating a pdf doc. The problem is i can not insert two different images using --logoimage command. I have tried different ways but have failed. The document which gets created picks up the last image i set using --logoimage, in the example below it sets the footer fine but header is blank and vice versa.
htmldoc --webpage --quiet --no-compression -t pdf12 --size "/home/test/bbb557c4886b2f1c840130eeef93b395.txt"
htmldoc --webpage --quiet --logoimage http://test.com/images/pdf/header.gif --header l --no-compression -t pdf12 --size -f "/home/test/bbb557c4886b2f1c840130eeef93b395.txt"
htmldoc --webpage --quiet --logoimage http://test.com/images/pdf/footer.gif --footer l --no-compression -t pdf12 --size -f "/home/test/bbb557c4886b2f1c840130eeef93b395.txt"
Answer: It seems as if we can not use separate images for header and footer through proper way.
Anyways I found a work around finally which enables us to use different images.
i used a proper logoimage in the header, however for the footer to work i found a way around. I actually used a background image, which is actually a full page length white image with a footer at the bottom. So once i use --bodyimage image.gif it behaves as if i am using a footer.
htmldoc --webpage --quiet --logoimage http://test.com/images/pdf/header.gif --header l --footer --bodyimage http://test.com/images/pdf/footer.gif --no-compression -t pdf12 --size -f "/home/test/bbb557c4886b2f1c840130eeef93b395.txt"

HTML DOC --logoimage


Why do we use such complicated notation?

Question: I have just started learning about music from the internet. I have learned how to play the piano, but I don't have a real piano so I am playing a virtual piano. In my opinion, the notation which is used for music is very complicated. It has many disadvantages. For example, it is difficult to read. It needs special software to type it, etc. Why do we not use a simple notation like this:

    Key signature: F#
    Piano:
         FFGAAGFEDDEFFEE+  FFGAAGFEDDEFEDD+  EEF+  DEFGF  DEFGF  DEA+  FFGAAGFEDDEFEDD+
                                                     ---     ---

(Where + means long; and --- below notes means short notes.)
This will be much easier to read, it doesn't require special software, it takes less space, etc.
So why do we still use the old notation?
Comment: Might as well complain that there are too many symbols in Abstract Algebra:  music can get complicated, and we're fortunate that there really is a single world-wide set of symbols which everyone interprets identically!
Comment: On what basis do you assert that "this will be [much] easier to read"? Staff notation allows you to very quickly and easily see the relative pitches of notes (i.e. how much higher or lower subsequent notes are); your system, however, requires memorizing which arbitrary symbols go with which pitches. (The other weaknesses of your proposal have been fairly well characterized in some of the answers.)
Comment: You could say the same thing about English notation: it's complicated, it has many disadvantages and it's hard to learn. First off, a written word is *a series of letters that represent its sound* instead of something more obvious, like a picture of the thing. Why should "bird" be the word for bird instead of a picture of a bird? Even worse, there are 40 sounds in English but only 26 letters, and a bunch of those letters are redundant, like "c" sounds like both "s" and "k". But when you learn it, it becomes easy. Music notation is the same.
Comment: By the way, if you want to see what's required to turn something like Kartik's proposal into something that's actually practical -- though still limited -- websearch for the definition of _ABC Notation_. There are tools which will convert between ABC, MIDI, and sheet music. ABC has the additional features needed to handle a lot of the things folks have pointed out as missing from Kartik's sketch... and becomes a lot less readable when you actually want to use them. Its big advantage was that, as text, it could be pasted directly into e-mail. Some folk-music sites still use it.
Comment: Ironically, as you learn more and more about music you might find that your personal notes on music are more like your format. For example, in my music notebook I have written down `House of the Rising Sun: Am C D F Am C E7 Am C D F Am E Am E7`. That assumes that you already know the melody and rhythm, which I do; I just need to be reminded of the changes. But that's not going to work for a Beethoven piano concerto!
Comment: There have been attempts to create a piano 'tabs' syntax similar to the guitar tabs found all over the Internet. See http://tabnabber.com/
Comment: The one thing that immediately popped to my mind is that billions of people don't use or know the latin alphabet.
Comment: Music is an art. You get really good after 10000 hours of intense practice. The time needed to learn music notation is a very small fraction of that. Music notation is beautiful. And it is a precious legacy of the past. You read the scores as they were written by Beethoven. Just enjoy and practice. Music is not computers or texting. Take the time to learn.
Comment: @EricLippert You are right, I already have a small diary which contains music written like this, for example I have written `Ehma-Pizzicato: CDEbA#CBA#F , etc...`.
Comment: German organists in the seventeenth century used a system of notation (called tabulature) that was quite similar to what you describe. Most of Buxtehude's works were written down this way. It was a compact way to represent music, but it was difficult to read. Most organists, recent research suggests, did not actually play from notated music, but memorized examples and then improvised based on these models.
Comment: If you look up the article on Notation in the New Grove Dictionary of Music and Musicians, you will see there are many alternative approaches. My favorite is a 20th-century modernist piece where the score consists of drawings of teddy bears having a picnic and things like that, and the performers are supposed to play the images.
Comment: You've used your proposed new notation scheme to render "Ode to Joy", but isn't the rhythm wrong starting at EEF+  DEF  ?  Also the key should be D major, not F#
Comment: _"For example, it is difficult to read."_ Speak for yourself. I, among many professional musicians, can read musical score faster than English. You just need to learn it.
Answer: Your notation may work for a free form melody, but that's it.
How will you notate several notes played at once?
How will you notate exact rhythms if you don't split up a bar into beats and subbeats and give each note an exact duration?
Which octaves are those notes?
I agree that standard notation (common music notation) is complicated, but there are pretty good reasons for it being that way.
My personal project is to make easier notation, though.  Starting with pianoroll notation (and all it's deficiencies), I'm adding the things that make standard notation better than it, TO it...  See my website for some examples: http://pianocheetah.com/tutorial/screenshots.html  (oh dear, I'll have to take some new screen shots.  Those are out of date.)
Comment: Actually, from a melody point of view, I think the proposition weaker. The usual notation has a visual aspect (higher pitches are written higher on the score) which I find *very* important when following a score. His proposal has not.
Comment: I would even add that I barely look at the notes when playing some pieces. I almost only look at the "curve" made by the changes in the melody pitch.
Comment: I disagree that standard notation is complicated. Compared to natural languages it is almost ridiculously simple. What makes it complicated is what is _not_ there, i.e. interpretation stuff. What is written is unambiguous and sequential. You don't need to read ahead to understand what is written. (Though it is certainly necessary for 'interpretation stuff'.)
Comment: @Édouard me too. Triplets, ritard, dynamics, etc make it inexact and obscure, at least to me. Piano roll should remain confined to computers.
Comment: well, i wasn't saying that his notation was GOOD for melody, just that it could only possibly show melody.  Not chords, etc.
Comment: I think what bothers me is the Italian terms we still use `allegro`, `grave` `adante` etc. There is no good reason for that besides dumb old tradition, and it takes memorization before knowing what a lot of it means.
Answer: We most commonly use staff notation because it is a good compromise between expressiveness and readability for a wide range of music.  There are alternatives, however these alternatives are specialized in one dimension or another, and thus, in a sense, less expressive than standard staff notation.
The overall problems relate to the fundamental issues in trying to represent "produce this specific sound" via some glyphs, and having something that someone can read at speed.
Staff notation has evolved, in the context of western tonal music, as an effective means of representing almost all of the salient performance features of many types of music, in a compact, instrument independent, format that is reasonably easy to use for sight-reading.
There are other representations of music, usually referred to as "tablulature" (or tab); guitar tab is the most common, but other instruments, e.g. harmonicas also use a form of tabulature.  The main difference between tabs and staff music is that the tab notation is intimately tied to a specific instrument.
More recently, in order to support transmission of music via ASCII ABC notation was developed; this seems to have the features you deem desirable.
However, ABC is not able to express the full range of features, like appogiatura, trills, slurs etc., features that can be easily represented in standard notation.
It is my understanding that only a very small  proportion of people can sight-read from tabulature or ABC, while every professional classical musician is able to sight read for at least one instrument.
Comment: Not only are the tabs tied to some instruments, but they generally fail to tell the rythm. You have to already know the rythm of the melody or to complete the tablature with a standard notation.
Comment: @Morwenn ... Specific example of the problem: _Rise Up Singing_ gets 1200 songs into a convenient-sized book by giving only lyrics and rough chord changes. Fine if you already know how the song is supposed to go, non-starter if you don't.
Comment: "in the context of western tonal music..." one of the most amazing things about staff notation is actually that it readily generalises even quite a way beyond the western music it was invented for. You can easily apply it to alternative tuning systems where MIDI would fail horribly, incorporate a lot of microtonality without much hassle or danger of confusing the performer. There's even [a system for writing Bohlen-Pierce–scale music in staffs](http://www.youtube.com/watch?v=sd1b9Lh8iFA), which one could think would be totally uncompatible.
Answer: Everyone, when they first begin to learn to read music notation, is puzzled by all the complexities and nuances.
Music notation is the way that it is because it works well. You know so little about playing music at this point that you cannot fully appreciate all that is involved. The more you learn, the more sense it will make to you.
Answer: The notation you suggest is too simple for real scores, or on the contrary hand it would be nearly impossible to read.
Try to translate this into your notation:
Comment: It'd be notated with a picture of a dinosaur: http://www.youtube.com/watch?v=G3VqcTDf6l4
Answer: The short answer to this question is that musical notation evolved over centuries in a relatively haphazard way. Many aspects of it are optimized for situations that no longer exist, or assume limitations on musical conduct that we no longer respect. A lot of it is arbitrary (why five lines on a staff?).
To take a most obvious example:  the clefs that we all know (treble, bass, maybe alto and tenor if you play viola or cello) are simply a small subset of a much larger, complete set of clefs that used to be used. Soprano and baritone clefs were once pretty common, and, in fact, it is theoretically possible to put a "C," "F," or "G" clef on any staff line.
So, originally, the system was super logical and super flexible:  figure out which clef on which line would allow you to write the melody you wanted to write down on the five-line staff you had.
"Ledger lines"? Never heard of 'em. They were invented later.
And so on... :)
Comment: For some interesting background on the development of musical notation, see http://en.wikipedia.org/wiki/Musical_notation and http://en.wikipedia.org/wiki/Mensural_notation.
Comment: Also, from http://en.wikipedia.org/wiki/Ledger_line : Although ledger lines are found occasionally in manuscripts of plainchant and early polyphony, it was only in the early 16th century in keyboard music that their use became at all extensive (Anon. 2001). Even then printers had an aversion to ledger lines which caused difficulties in setting type, wasting space on the page and causing a messy appearance. Vocal music employed a variety of different clefs to keep the range of the part on the staff as much as possible... (Godwin 1974, 16–17)
Answer: In short, musical notation is complex because the music it notates is complex.
For example, your proposed notation has + and - symbols to denote long and short notes.  But what if you have a song that requires half, quarter, eighth, sixteenth, and "sixth" and "twelfth" (triplet) notes?  You'll have to distinguish all of those lengths somehow.  (The QBASIC PLAY command solved this problem with notations such as C8 C4 E16 E16 or L8 CBCC#).
Other issues to consider are:

What about harmony?  How do you denote multiple notes being played at one time?
How do you denote rests?
Which octave are your notes in?
How do you denote ties and slurs?
How do you indicate how loudly/softly the music should be played?

That being said, there have been many alternative notations proposed, including the ASCII-based ABC notation (similar to yours, but more developed), and various systems listed at The Music Notation Project based on the chromatic scale.
Traditional notation did evolve rather haphazardly, and so suffers from a few flaws, mostly in the non-isomorphic positioning of pitches.  However, it remains popular for the same reason that the QWERTY keyboard layout does: People use it because it's what everybody else already knows.
Answer: There are many reason we use the notation we do. Lets just look at a short piano piece as an example.
As you can see in this simple example there is a lot of information. The first is the clefs (the treble and the bass) that tell you exactly what notes to play and in what octave. It is very common for piano music to have a treble and a bass clef on the grand staff, but there are exceptions.
The next is the key signature which tells you what notes are in the key. In this case we are in the key of F where the only accidental is Bb.
Next comes the time signature where the "C" stands for common time (4/4) which tells us there are four quarter notes in a measure.
Now we get to the notes themselves which along with the clef and the key signature tell us exactly what note to play and how long. Then we have accidentals marked as necessary and also expressions marked as necessary (such as the fermata in measure 10 and the retardando starting in measure 7) that give a better understanding of how to play.
There is a lot of information compact into a language that musicians can easily understand. Sure it is not the easiest to a beginner, but it is rich with information that just can't be replicated with the notation you suggested.
Comment: "Love me tender" is copyrighted by Elvis Presley, so it's a bad idea to post a score under this name (similarly to how "Happy Birthday" is copyrighted in the U.S.A. because of its lyrics while "Good morning to all" or whatever it was isn't).  When stating "Trad. melody" as a defense, one should state _which_ melody.  It's "Nora Lee".  Under that name, the copyright hawks would have a hard time striking.  They'll still try, but at least one can then fight back with a good chance at success.
Comment: Well, if we now all agree that the title of that score must be some unfathomable mistake and since there are no printed lyrics and that the song really is "Nora Lee", we should be able to just wait and see whether anybody will complain before taking action.  At least that would be my guess.
Comment: Copyright in the U.S. lasts for whatever is needed to keep Mickey Mouse out of the Public Domain as the lawmakers receive a significant part of their income from large corporations (the laws are *retroactively* extended, with the only ones profiting from *that* being heirs and corporations since the respective authors are dead).  The current rules are https://en.wikipedia.org/wiki/Copyright_Term_Extension_Act#Opposition and the recent "trade" treaties supposed to be pressed onto Europe soon will extend even those and put them into national laws.
Comment: @Tim: I suspect that, say, a Beethoven Sonata would run to 100 pages instead of 20 or so, using that notation.  There is a whole lot of information packed into each note in musical notation.
Comment: @David that's "Aura Lea" actually.  See http://en.wikipedia.org/wiki/Aura_Lea
Comment: @David it was the one of the first pics in googling "easy piano sheet music". If I have to take it down I will.
Comment: Perhaps the OP can attempt to represent the above simple tune using his notation; it's likely to be instructive.  :)
Comment: @BobRodes - in its way it's the most succinct answer to the OP's question.Then we'll try to play it... Or even sing it 'orally'.
Comment: @David - copyright (in UK) lasts for 70 yrs after the death of the composer, as far as lyrics are concerned. Don't know about U.S.
Answer: After the language, notation, encoding or other similar communication standard becomes widespread, a popularity becomes its major positive side (net effect). It is good to know and use because everyone around knows and uses it. The standard can only slowly evolve, adding new possibilities to the existing base.
The new standard can only emerge and become more popular if significant problems have been discovered with the current one. I think, maybe the current notation is actually not so bad and this is the reason why it does not change.
Answer: Short answer: Yes you are right, but classic pianoforte notation is too common to be avoided, your best bet is to try to find either another notation that is also common like MIDI or Tablature, or either find a ressembling notation system that is easy to convert back and forth with the classical one like the Simplified Music Notation.
Long answer: You are totally right, one can use any notation one wants.
From Wikipedia:

In linguistics and semiotics, a notation is a system of graphic or
  symbols, characters and abbreviated expressions, used in artistic and
  scientific disciplines to represent technical facts and quantities by
  convention. Therefore, a notation is a collection of related symbols
  that are each given an arbitrary meaning, created to facilitate
  structured communication within a domain knowledge or field of study.

Thus there's no reason why you should not use your own notation system, as long as it can represent what you want to express. So why was the piano notation become so widespread?
As its name implies, it's because it's directly inspired by a piano rotated vertically (see the correspondances between the left and middle part):

(Courtesy of Ken Rushton aka MusicScienceGuy)
So as you can see, the primary reason for making this notation was not because of expressiveness or any other artistically elevated concept, but because of practicality: piano was the most used instrument historically in occident and this was a kinda straight way to represent a score to play on this instrument.
And this historical relationship directly influenced the notation a lot further: at first, pianos didn't have accidentals (the black keys) but only the white keys, and thus that's why they are not represented on the notation. Accidentals came later, and to accomodate this evolution, the notation was "tweaked" to be able to represent them. But it's hardly a perfect fit if you see what I mean...
Another historical anecdote: piano was initially made primarily to play in the C key (since C was and still is the most used key), hence why chords are so easy to play in C, but so weird and hard in other keys. Some attempts were made to fix that which are called isomorphic keyboards, with a common mapping being the Wicki-Hayden/Jammer used on concertinas, and an easy accessible mapping being the colored traditional keyboard.
About expressiveness, in fact, MIDI is the most expressive standardized notation, and is a superset of standard piano forte notation (and you can often find a "convert midi to notation" option in softwares, but the other way is much more hard because notation lacks informations that can be encoded in midi, so to do that softwares must rely on AI algorithms or just on the user to fix stuff).
But even with midi, after using it for a while, you will soon come to the conclusion that it's not nearly expressive enough to convey and reproduce all the expressions you may want. There are more expressive specifications in various softwares but these internal notations systems are not considered standard (since most are closed source anyway).
Other solutions exists, and a lot of alternative notations have been made over the centuries. You can find a good list with critical reviews at musicnotation.org and a historical review here.
On the simplicity side, one of the most common but simple notation is the tablature, which is quite widespread for guitar songs.
As you can see, you have a wide range of possibilities, and can easily imagine anything between tablature simplicity and midi expressiveness, or maybe even beyond or combining both.
Why then use such an old, deprecated musical notation system that can't even account elegantly for accidentals nor the latest findings in musical theory like microtonality?
Answer: because it's popular and culturally anchored.
Pianoforte notation is the defacto choice for teachers in musical schools. Furthermore, nearly all scores use this notation, thus if you want to use another notation, you will have the double burden to first learn the pianoforte notation and then learn how to convert it into your own notation of choice. But if you learn pianoforte, there's not much incentive to then convert to another notation...
In fact, that's not quite true. Since, as I demonstrated above, pianoforte is not the graal of expressiveness, a lot of experimental music composers and some contemporary classical composers use their own notation system, sometimes just twists on the classic pianoforte, others making a whole new notation system.
So in the end, it's up to you to choose the musical notation system you prefer, but you should not only choose it because you feel comfortable with it: it should also be expressive enough for your needs, and most important easily convertible back and forth with the classical piano notation, or sooner or later you will get tired of using your notation.
Comment: Staff notation evolved out of notations, primarily for vocal music, that preceded the use of piano-style keyboards; stating that keyboards are the driving force behind staff notation is inaccurate.
Comment: [Early vocal notation, neume](http://en.wikipedia.org/wiki/Neume) that influenced later staff notation.
Comment: @Dave I need to find the ref that made me write that (and the layout of the staff notation is so similar to one of a keyboard that it just seems logical), but you are welcome to provide one for your statement, I am greatly interested.
Comment: Also note that varieties of C clefs (instead of just G and F) were used for much early music; for example, they're referred to in Gradus ad Parnassum.
Answer: I agree.  Personally, I prefer MIDI notation.  Composing music in a MIDI editor, with rows representing pitches and columns representing notes/durations, makes much more sense to me.
MIDI editors will generally allow compositions to be exported in standard musical notation, too, so nothing is lost.  Plus, the MIDI editor will show up for band practice. ;-)
Comment: MIDI editors are sure able to generate sheet music for trivial e.g. chord sequences or melodies within a single key, but as soon as you have any modulations in there, want to express ornamentation or other expressive marks, or simply don't have a suitable raster (as soon as there's changes of tempo and / or time signature, that's rather infeasible), then you're in for a horrible jumble of awkward quantisation artifacts and mischosen accidentals. Also, MIDI editors give you way less of a useful overview about motif recurrence etc., fine intervals, and articulation (at least without zooming in).
Comment: Easier to compose in, I agree.  Hard to play, though!  :)
Comment: IMO, one should think about MIDI as a _intermediate form_ between performance instructions (such as sheet music) and audible result, not as an alternative form of the latter. Composer -Sheet-Music-> Performer -MIDI-> Instrument -Audio-> Listener. The backwards way is possible: you can transcribe a musical piece from hearing it, and you can (more easily) transcribe a MIDI file, but neither is trivial or desirable as a default.