text:
Approximating a special case of the Riemann Theta function
This challenge is to write fast code that can perform a computationally difficult infinite sum.
Input
An n by n matrix P with integer entries that are smaller than 100 in absolute value. When testing I am happy to provide input to your code in any sensible format your code wants. The default will be one line per row of the matrix, space separated and provided on standard input.
P will be positive definite which implies it will always be symmetric.  Other than that you don't really need to know what positive definite means to answer the challenge.  It does however mean that there will actually be an answer to the sum defined below.
You do however need to know what a matrix-vector product is.
Output
Your code should compute the infinite sum:

to within plus or minus 0.0001 of the correct answer.  Here Z is the set of integers and so Z^n is all possible vectors with n integer elements and e is the famous mathematical constant that approximately equals 2.71828.  Note that the value in the exponent is simply a number. See below for an explicit example.
How does this relate to the Riemann Theta function?
In the notation of this paper on approximating the Riemann Theta function we are trying to compute .  Our problem is a special case for at least two reasons.

We set the initial parameter called z in the linked paper to 0.
We create the matrix P in such a way that the minimum size of an eigenvalue is 1. (See below for how the matrix is created.)

Examples
P = [[ 5.,  2.,  0.,  0.],
     [ 2.,  5.,  2., -2.],
     [ 0.,  2.,  5.,  0.],
     [ 0., -2.,  0.,  5.]]

Output: 1.07551411208

In more detail, let us see just one term in the sum for this P.  Take for example just one term in the sum:

and  x^T P x = 30.  Notice thate^(-30) is about 10^(-14) and so is unlikely to be important for getting the correct answer up to the given tolerance. Recall that the infinite sum will actually use every possible vector of length 4 where the elements are integers.  I just picked one to give an explicit example.
P = [[ 5.,  2.,  2.,  2.],
     [ 2.,  5.,  4.,  4.],
     [ 2.,  4.,  5.,  4.],
     [ 2.,  4.,  4.,  5.]]

Output = 1.91841190706

P = [[ 6., -3.,  3., -3.,  3.],
     [-3.,  6., -5.,  5., -5.],
     [ 3., -5.,  6., -5.,  5.],
     [-3.,  5., -5.,  6., -5.],
     [ 3., -5.,  5., -5.,  6.]]

Output = 2.87091065342

P = [[6., -1., -3., 1., 3., -1., -3., 1., 3.],
     [-1., 6., -1., -5., 1., 5., -1., -5., 1.],
     [-3., -1., 6., 1., -5., -1., 5., 1., -5.],
     [1., -5., 1., 6., -1., -5., 1., 5., -1.],
     [3., 1., -5., -1., 6., 1., -5., -1., 5.],
     [-1., 5., -1., -5., 1., 6., -1., -5., 1.],
     [-3., -1., 5., 1., -5., -1., 6., 1., -5.],
     [1., -5., 1., 5., -1., -5., 1., 6., -1.],
     [3., 1., -5., -1., 5., 1., -5., -1., 6.]]

Output: 8.1443647932

P = [[ 7.,  2.,  0.,  0.,  6.,  2.,  0.,  0.,  6.],
     [ 2.,  7.,  0.,  0.,  2.,  6.,  0.,  0.,  2.],
     [ 0.,  0.,  7., -2.,  0.,  0.,  6., -2.,  0.],
     [ 0.,  0., -2.,  7.,  0.,  0., -2.,  6.,  0.],
     [ 6.,  2.,  0.,  0.,  7.,  2.,  0.,  0.,  6.],
     [ 2.,  6.,  0.,  0.,  2.,  7.,  0.,  0.,  2.],
     [ 0.,  0.,  6., -2.,  0.,  0.,  7., -2.,  0.],
     [ 0.,  0., -2.,  6.,  0.,  0., -2.,  7.,  0.],
     [ 6.,  2.,  0.,  0.,  6.,  2.,  0.,  0.,  7.]]

Output = 3.80639191181

Score
I will test your code on randomly chosen matrices P of increasing size.
Your score is simply the largest n for which I get a correct answer in less than 30 seconds when averaged over 5 runs with randomly chosen matrices P of that size.
What about a tie?
If there is a tie, the winner will be the one whose code runs fastest averaged over 5 runs. In the event that those times are also equal, the winner is the first answer.
How will the random input be created?

Let M be a random m by n matrix with m<=n and entries which are -1 or 1.  In Python/numpy M = np.random.choice([0,1], size = (m,n))*2-1 . In practice I will set m to be about n/2.
Let P be the identity matrix + M^T M. In Python/numpy P =np.identity(n)+np.dot(M.T,M). We are now guaranteed that P is positive definite and the entries are in a suitable range.

Note that this means that all eigenvalues of P are at least 1, making the problem potentially easier than the general problem of approximating the Riemann Theta function.
Languages and libraries
You can use any language or library you like. However, for the purposes of scoring I will run your code on my machine so please provide clear instructions for how to run it on Ubuntu.
My Machine The timings will be run on my machine. This is a standard Ubuntu install on an 8GB AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Leading answers

n = 47 in C++ by Ton Hospel
n = 8 in Python by Maltysen

It may be worth mentioning that a positive definite matrix is symmetric by definition.

@2012rcampion Thanks. Added.

Ok, maybe this is a dumb question, but I've stared at this for ages and I cannot figure out how you got an x of [-1,0,2,1].  Can you elaborate on this? (Hint: I am not a math guru)

@wnnmaw Sorry for being confusing. The sum has one term for every possible vector x of length 4 in this case. [-1,0,2,1] is just one I picked at random to show explicitly what the term would be in that case.

You're testing on randomly chosen matrices. A crucial thing to know: What distribution do they follow/how do you generate those?

Does the sum always converge?

@soktinpk Yes, because of the positive definite property.

@R.Kap  M^T means "M transpose". https://chortle.ccsu.edu/VectorLessons/vmch13/vmch13_14.html

@R.Kap Yes. Vector transpose just swaps a vector between being a row vector and a column vector (or vice versa)

@R.Kap You can definitely use numpy. In fact I just removed the rule as it was a little confusing and it isn't needed.

@R.Kap The e denotes the exponential function.

So the equation uses ALL possible vectors consisting of ALL the integers (whether positive or negative) with length n. Wow...

@Lembik The way you generate the SPD matrices implies that no singular value has ever an absolute value below 1. Can we use that knowledge?

@flawr Yes absolutely.

this one asks for matlab... gotta fire my instance up to set the arithmetic later

@masterX244 Please feel free to answer in matlab!  I can't run matlab myself but I will try to run it in octave for scoring and even convert it to python if I can.  That is not normally too hard these days.

So how do you actually know what the correct answer is? I mean, based on the equation given, from my perspective it seems as if their could be many different answers based on the bounds used. So how do you actually know what the correct answer (or range) should be?

@R.Kap Ton Hospel's code uses some provable bounds. Hopefully there will be more documentation soon.

C++
No more naive approach. Only evaluate inside the ellipsoid.
Uses the armadillo, ntl, gsl and pthread libraries. Install using
apt-get install libarmadillo-dev libntl-dev libgsl-dev

Compile the program using something like:
g++ -Wall -std=c++11 -O3 -fno-math-errno -funsafe-math-optimizations -ffast-math -fno-signed-zeros -fno-trapping-math -fomit-frame-pointer -march=native -s infinity.cpp -larmadillo -lntl -lgsl -lpthread -o infinity

On some systems you may need to add -lgslcblas after -lgsl.
Run with the size of the matrix followed by the elements on STDIN:
./infinity < matrix.txt

matrix.txt:
4
5  2  0  0
2  5  2 -2
0  2  5  0
0 -2  0  5

Or to try a precision of 1e-5:
./infinity -p 1e-5 < matrix.txt

infinity.cpp:
// Based on http://arxiv.org/abs/nlin/0206009

#include <iostream>
#include <vector>
#include <stdexcept>
#include <cstdlib>
#include <cmath>
#include <string>
#include <thread>
#include <future>
#include <chrono>

using namespace std;

#include <getopt.h>

#include <armadillo>

using namespace arma;

#include <NTL/mat_ZZ.h>
#include <NTL/LLL.h>

using namespace NTL;

#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>

double const EPSILON = 1e-4;       // default precision
double const GROW    = 2;          // By how much we grow the ellipsoid volume
double const UPSCALE = 1e9;        // lattice reduction, upscale real to integer
double const THREAD_SEC = 0.1;     // Use threads if need more time than this
double const RADIUS_MAX = 1e6;     // Maximum radius used in root finding
double const RADIUS_INTERVAL = 1e-6; // precision of target radius
int const ITER_MAX = 1000;         // Maximum iterations in root finding
unsigned long POINTS_MIN = 1000;   // Minimum points before getting fancy

struct Result {
    Result& operator+=(Result const& add) {
        sum     += add.sum;
        elapsed += add.elapsed;
        points  += add.points;
        return *this;
    }

    friend Result operator-(Result const& left, Result const& right) {
        return Result{left.sum - right.sum,
                left.elapsed - right.elapsed,
                left.points - right.points};
    }

    double sum, elapsed;
    unsigned long points;
};

struct Params {
    double half_rho, half_N, epsilon;
};

double fill_factor_error(double r, void *void_params) {
    auto params = static_cast<Params*>(void_params);
    r -= params->half_rho;
    return gsl_sf_gamma_inc(params->half_N, r*r) - params->epsilon;
}

// Calculate radius needed for target precision
double radius(int N, double rho, double lat_det, double epsilon) {
    Params params;

    params.half_rho = rho / 2.;
    params.half_N   = N   / 2.;
    params.epsilon = epsilon*lat_det*gsl_sf_gamma(params.half_N)/pow(M_PI, params.half_N);

    // Calculate minimum allowed radius
    auto r = sqrt(params.half_N)+params.half_rho;
    auto val = fill_factor_error(r, &params);
    cout << "Minimum R=" << r << " -> " << val << endl;

    if (val > 0) {
        // The minimum radius is not good enough. Work out a better one by
        // finding the root of a tricky function
        auto low  = r;
        auto high = RADIUS_MAX * 2 * params.half_rho;
        auto val = fill_factor_error(high, &params);
        if (val >= 0)
            throw(logic_error("huge RADIUS_MAX is still not big enough"));

        gsl_function F;
        F.function = fill_factor_error;
        F.params   = &params;

        auto T = gsl_root_fsolver_brent;
        auto s = gsl_root_fsolver_alloc (T);
        gsl_root_fsolver_set (s, &F, low, high);

        int status = GSL_CONTINUE;
        for (auto iter=1; status == GSL_CONTINUE && iter <= ITER_MAX; ++iter) {
            gsl_root_fsolver_iterate (s);
            low  = gsl_root_fsolver_x_lower (s);
            high = gsl_root_fsolver_x_upper (s);
            status = gsl_root_test_interval(low, high, 0, RADIUS_INTERVAL  * 2 * params.half_rho);
        }
        r = gsl_root_fsolver_root(s);
        gsl_root_fsolver_free(s);
        if (status == GSL_CONTINUE)
            throw(logic_error("Search for R did not converge"));
    }
    return r;
}

// Recursively walk down the ellipsoids in each dimension
void ellipsoid(int d, mat const& A, double const* InvD, mat& Accu,
               Result& result, double r2) {
    auto r = sqrt(r2);
    auto offset = Accu(d, d);
    // InvD[d] = 1/ A(d, d)
    auto from = ceil((-r-offset) * InvD[d]);
    auto to   = floor((r-offset) * InvD[d]);
    for (auto v = from; v <= to; ++v) {
        auto value  = v * A(d, d)+offset;
        auto residu = r2 - value*value;
        if (d == 0) {
            result.sum += exp(residu);
            ++result.points;
        } else {
            for (auto i=0; i<d; ++i) Accu(d-1, i) = Accu(d, i) + v * A(d, i);
            ellipsoid(d-1, A, InvD, Accu, result, residu);
        }
    }
}

// Specialised version of ellipsoid() that will only process points an octant
void ellipsoid(int d, mat const& A, double const* InvD, mat& Accu,
               Result& result, double r2, unsigned int octant) {
    auto r = sqrt(r2);
    auto offset = Accu(d, d);
    // InvD[d] = 1/ A(d, d)
    long from = ceil((-r-offset) * InvD[d]);
    long to   = floor((r-offset) * InvD[d]);
    auto points = to-from+1;
    auto base = from + points/2;
    if (points & 1) {
        auto value = base * A(d, d) + offset;
        auto residu = r2 - value * value;
        if (d == 0) {
            if ((octant & (octant - 1)) == 0) {
                result.sum += exp(residu);
                ++result.points;
            }
        } else {
            for (auto i=0; i<d; ++i) Accu(d-1, i) = Accu(d, i) + base * A(d, i);
            ellipsoid(d-1, A, InvD, Accu, result, residu, octant);
        }
        ++base;
    }
    if ((octant & 1) == 0) {
        to = from + points / 2 - 1;
        base = from;
    }
    octant /= 2;
    for (auto v = base; v <= to; ++v) {
        auto value = v * A(d,d)+offset;
        auto residu = r2 - value*value;
        if (d == 0) {
            if ((octant & (octant - 1)) == 0) {
                result.sum += exp(residu);
                ++result.points;
            }
        } else {
            for (auto i=0; i<d; ++i) Accu(d-1, i) = Accu(d, i) + v * A(d, i);
            if (octant == 1)
                ellipsoid(d-1, A, InvD, Accu, result, residu);
            else
                ellipsoid(d-1, A, InvD, Accu, result, residu, octant);
        }
    }
}

// Prepare call to ellipsoid()
Result sym_ellipsoid(int N, mat const& A, const vector<double>& InvD, double r,
                     unsigned int octant = 1) {
    auto start = chrono::steady_clock::now();
    auto r2 = r*r;

    mat Accu(N, N);
    Accu.row(N-1).zeros();

    Result result{0, 0, 0};
    // 2*octant+1 forces the points into the upper half plane, skipping 0
    // This way we use the lattice symmetry and calculate only half the points
    ellipsoid(N-1, A, &InvD[0], Accu, result, r2, 2*octant+1);
    // Compensate for the extra factor exp(r*r) we always add in ellipsoid()
    result.sum /= exp(r2);
    auto end = chrono::steady_clock::now();
    result.elapsed = chrono::duration<double>{end-start}.count();

    return result;
}

// Prepare multithreaded use of sym_ellipsoid(). Each thread gets 1 octant
Result sym_ellipsoid_t(int N, mat const& A, const vector<double>& InvD, double r, unsigned int nr_threads) {
    nr_threads = pow(2, ceil(log2(nr_threads)));

    vector<future<Result>> results;
    for (auto i=nr_threads+1; i<2*nr_threads; ++i)
        results.emplace_back(async(launch::async, sym_ellipsoid, N, ref(A), ref(InvD), r, i));
    auto result = sym_ellipsoid(N, A, InvD, r, nr_threads);
    for (auto i=0U; i<nr_threads-1; ++i) result += results[i].get();
    return result;
}

int main(int argc, char* const* argv) {
    cin.exceptions(ios::failbit | ios::badbit);
    cout.precision(12);

    double epsilon    = EPSILON; // Target absolute error
    bool inv_modular  = true;    // Use modular transform to get the best matrix
    bool lat_reduce   = true;    // Use lattice reduction to align the ellipsoid
    bool conservative = false;   // Use provable error bound instead of a guess
    bool eigen_values = false;   // Show eigenvalues
    int  threads_max  = thread::hardware_concurrency();

    int option_char;
    while ((option_char = getopt(argc, argv, "p:n:MRce")) != EOF)
        switch (option_char) {
            case 'p': epsilon      = atof(optarg); break;
            case 'n': threads_max  = atoi(optarg); break;
            case 'M': inv_modular  = false;        break;
            case 'R': lat_reduce   = false;        break;
            case 'c': conservative = true;         break;
            case 'e': eigen_values = true;         break;
            default:
              cerr << "usage: " << argv[0] << " [-p epsilon] [-n threads] [-M] [-R] [-e] [-c]" << endl;
              exit(EXIT_FAILURE);
        }
    if (optind < argc) {
        cerr << "Unexpected argument" << endl;
        exit(EXIT_FAILURE);
    }
    if (threads_max < 1) threads_max = 1;
    threads_max = pow(2, ceil(log2(threads_max)));
    cout << "Using up to " << threads_max << " threads" << endl;

    int N;
    cin >> N;

    mat P(N, N);
    for (auto& v: P) cin >> v;

    if (eigen_values) {
        vec eigval = eig_sym(P);
        cout << "Eigenvalues:\n" << eigval << endl;
    }

    // Decompose P = A * A.t()
    mat A = chol(P, "lower");

    // Calculate lattice determinant
    double lat_det = 1;
    for (auto i=0; i<N; ++i) {
        if (A(i,i) <= 0) throw(logic_error("Diagonal not Positive"));
        lat_det *= A(i,i);
    }
    cout << "Lattice determinant=" << lat_det << endl;

    auto factor = lat_det / pow(M_PI, N/2.0);
    if (inv_modular && factor < 1) {
        epsilon *= factor;
        cout << "Lattice determinant is small. Using inverse instead. Factor=" << factor << endl;
        P = M_PI * M_PI * inv(P);
        A = chol(P, "lower");
        // We could simple calculate the new lat_det as pow(M_PI,N)/lat_det
        lat_det = 1;
        for (auto i=0; i<N; ++i) {
            if (A(i,i) <= 0) throw(logic_error("Diagonal not Positive"));
            lat_det *= A(i,i);
        }
        cout << "New lattice determinant=" << lat_det << endl;
    } else
        factor = 1;

    // Prepare for lattice reduction.
    // Since the library works on integer lattices we will scale up our matrix
    double min = INFINITY;
    for (auto i=0; i<N; ++i) {
        for (auto j=0; j<N;++j)
            if (A(i,j) != 0 && abs(A(i,j) < min)) min = abs(A(i,j));
    }

    auto upscale = UPSCALE/min;
    mat_ZZ a;
    a.SetDims(N,N);
    for (auto i=0; i<N; ++i)
        for (auto j=0; j<N;++j) a[i][j] = to_ZZ(A(i,j)*upscale);

    // Finally do the actual lattice reduction
    mat_ZZ u;
    auto rank = G_BKZ_FP(a, u);
    if (rank != N) throw(logic_error("Matrix is singular"));
    mat U(N,N);
    for (auto i=0; i<N;++i)
        for (auto j=0; j<N;++j) U(i,j) = to_double(u[i][j]);

    // There should now be a short lattice vector at row 0
    ZZ sum = to_ZZ(0);
    for (auto j=0; j<N;++j) sum += a[0][j]*a[0][j];
    auto rho = sqrt(to_double(sum))/upscale;
    cout << "Rho=" << rho << " (integer square " <<
        rho*rho << " ~ " <<
        static_cast<int>(rho*rho+0.5) << ")" << endl;

    // Lattice reduction doesn't gain us anything conceptually.
    // The same number of points is evaluated for the same exponential values
    // However working through the ellipsoid dimensions from large lattice
    // base vectors to small makes ellipsoid() a *lot* faster
    if (lat_reduce) {
        mat B = U * A;
        P = B * B.t();
        A = chol(P, "lower");
        if (eigen_values) {
            vec eigval = eig_sym(P);
            cout << "New eigenvalues:\n" << eigval << endl;
        }
    }

    vector<double> InvD(N);;
    for (auto i=0; i<N; ++i) InvD[i] = 1 / A(i, i);

    // Calculate radius needed for target precision
    auto r = radius(N, rho, lat_det, epsilon);
    cout << "Safe R=" << r << endl;

    auto nr_threads = threads_max;
    Result result;
    if (conservative) {
        // Walk all points inside the ellipsoid with transformed radius r
        result = sym_ellipsoid_t(N, A, InvD, r, nr_threads);
    } else {
        // First grow the radius until we saw POINTS_MIN points or reach the
        // target radius
        double i = floor(N * log2(r/rho) / log2(GROW));
        if (i < 0) i = 0;
        auto R = r * pow(GROW, -i/N);
        cout << "Initial R=" << R << endl;
        result = sym_ellipsoid_t(N, A, InvD, R, nr_threads);
        nr_threads = result.elapsed < THREAD_SEC ? 1 : threads_max;
        auto max_new_points = result.points;
        while (--i >= 0 && result.points < POINTS_MIN) {
            R = r * pow(GROW, -i/N);
            auto change = result;
            result = sym_ellipsoid_t(N, A, InvD, R, nr_threads);
            nr_threads = result.elapsed < THREAD_SEC ? 1 : threads_max;
            change = result - change;

            if (change.points > max_new_points) max_new_points = change.points;
        }

        // Now we have enough points that it's worth bothering to use threads
        while (--i >= 0) {
            R = r * pow(GROW, -i/N);
            auto change = result;
            result = sym_ellipsoid_t(N, A, InvD, R, nr_threads);
            nr_threads = result.elapsed < THREAD_SEC ? 1 : threads_max;
            change = result - change;
            // This is probably too crude and might misestimate the error
            // I've never seen it fail though
            if (change.points > max_new_points) {
                max_new_points = change.points;
                if (change.sum < epsilon/2) break;
            }
        }
        cout << "Final R=" << R << endl;
    }

    // We calculated half the points and skipped 0.
    result.sum = 2*result.sum+1;

    // Modular transform factor
    result.sum /= factor;

    // Report result
    cout <<
        "Evaluated " << result.points << " points\n" <<
        "Sum = " << result.sum << endl;
}

This is very impressive and much better than the naive approach in my view. I look forward to the documentation :)

@TonHospel Can you tell us a bit more about how you come up with the bounds?

I am using Arch Linux and needed the -lgslcblas flag to compile. Amazing answer by the way!

Python 3
12 secs n=8 on my computer, ubuntu 4 core.
Really naive, have no clue what I'm doing.
from itertools import product
from math import e

P = [[ 6., -3.,  3., -3.,  3.],
     [-3.,  6., -5.,  5., -5.],
     [ 3., -5.,  6., -5.,  5.],
     [-3.,  5., -5.,  6., -5.],
     [ 3., -5.,  5., -5.,  6.]]

N = 2

n = [1]

while e** -n[-1] > 0.0001:
    n = []
    for x in product(list(range(-N, N+1)), repeat = len(P)):
        n.append(sum(k[0] * k[1] for k in zip([sum(j[0] * j[1] for j in zip(i, x)) for i in P], x)))
    N += 1

print(sum(e** -i for i in n))

This will keep on increasing the range of Z that it uses until it gets a good enough answer. I wrote my own matrix multiplication, prolly should use numpy.

Thanks ! Can you show some outputs and timings on your computer?

Your code runs in pypy which is great and is fast. Unfortunately, [[6.0, -1.0, -3.0, 1.0, 3.0, -1.0, -3.0, 1.0, 3.0], [-1.0, 6.0, -1.0, -5.0, 1.0, 5.0, -1.0, -5.0, 1.0], [-3.0, -1.0, 6.0, 1.0, -5.0, -1.0, 5.0, 1.0, -5.0], [1.0, -5.0, 1.0, 6.0, -1.0, -5.0, 1.0, 5.0, -1.0], [3.0, 1.0, -5.0, -1.0, 6.0, 1.0, -5.0, -1.0, 5.0], [-1.0, 5.0, -1.0, -5.0, 1.0, 6.0, -1.0, -5.0, 1.0], [-3.0, -1.0, 5.0, 1.0, -5.0, -1.0, 6.0, 1.0, -5.0], [1.0, -5.0, 1.0, 5.0, -1.0, -5.0, 1.0, 6.0, -1.0], [3.0, 1.0, -5.0, -1.0, 5.0, 1.0, -5.0, -1.0, 6.0]]  gives just the wrong answer.

8.1443647932-8.14381938863 = 0.00054540457 > 0.0001.

@Maltysen Your program does only check whether the last term is smaller than the given accuracy. But the error you make is by far bigger, as you'd have to consider the sum of all the other terms for the error too!

Python, numpy
one example program using numpy is as follows.
Really naive, have no clue what I'm doing.
import numpy as np
from itertools import product
from math import e
from time import time

n=9
is_randomized=False

if is_randomized:
    m = n // 2
    M = np.random.choice([0, 1], size=(m, n)) * 2 - 1
    P = np.identity(n) + np.dot(M.T, M)
    print(P)
else:
    if n==4:
        P = [[5., 2., 2., 2.],
             [2., 5., 4., 4.],
             [2., 4., 5., 4.],
             [2., 4., 4., 5.]]
        P = np.array(P)
        print(P)
    elif n==5:
        P = np.array([[6., -3., 3., -3., 3.],
                      [-3., 6., -5., 5., -5.],
                      [3., -5., 6., -5., 5.],
                      [-3., 5., -5., 6., -5.],
                      [3., -5., 5., -5., 6.]])
        P = np.array(P)
        print(P)
    elif n==9:
        P = [[7., 2., 0., 0., 6., 2., 0., 0., 6.],
             [2., 7., 0., 0., 2., 6., 0., 0., 2.],
             [0., 0., 7., -2., 0., 0., 6., -2., 0.],
             [0., 0., -2., 7., 0., 0., -2., 6., 0.],
             [6., 2., 0., 0., 7., 2., 0., 0., 6.],
             [2., 6., 0., 0., 2., 7., 0., 0., 2.],
             [0., 0., 6., -2., 0., 0., 7., -2., 0.],
             [0., 0., -2., 6., 0., 0., -2., 7., 0.],
             [6., 2., 0., 0., 6., 2., 0., 0., 7.]]
        P = np.array(P)
        print(P)

# estimate how much N should be chosen?  based on matrix P or size n ?
if n==9:
    N = 2
elif n==5:
    N = 4
elif n==4:
    N = 5
else:
    N = 3

n_list = []
start_time=time()
for x in product(range(-N, N+1), repeat=len(P)):
    x = np.array(x)
    summand = np.dot(np.dot(x, P), x.T)
    n_list.append(summand)
result = sum(e**-i for i in n_list)
print(result)
print(f"duration: {time()-start_time}")

8 secs, n=9 on my computer.


text:
Palindromizing the strings
Introduction
For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is:
abcdcba

If you reverse this, you will end up with:
abcdcba

Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string:
adbcb

This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string at the right of the initial string, leaving both versions intact. The shorter, the better.
The first thing we can try is the following:
adbcb
bcbda
^^ ^^

Not all characters match, so this is not the right position for the reversed string. We go one step to the right:
adbcb
 bcbda
 ^^^^

This also doesn't match all characters. We go another step to the right:
adbcb
  bcbda

This time, all characters match. We can merge both string leaving the intact. The final result is:
adbcbda

This is the palindromized string.

The Task
Given a string (with at least one character) containing only lowercase letters (or uppercase, if that fits better), output the palindromized string.

Test cases
Input     Output

abcb      abcba
hello     hellolleh
bonobo    bonobonob
radar     radar
hex       hexeh

This is code-golf, so the submission with the least amount of bytes wins!

Related.

You should specify that the reversed string has to be merged into the original string with the reversed one at the right. If it can go at left, obonobo would be a better solution to the test case.

Related 2

@LevelRiverSt +1 just because "obonobo" is such an amazing word

@Nathaniel Thanks  but bono b o nob is an entire sentence. What's the difference between God and Bono? God doesn't wander round Dublin pretending to be Bono ;-)

Related 3: revenge of the relations

Why is this question so ridiculously long-winded? The whole task can literally be summarised in a sentence, there's no need for such a thorough (and weird) explanation.

Jelly, 11 10 bytes
ṫỤfU$Ḣœ^;U

Try it online!
How it works
ṫỤfU$Ḣœ^;U  Main link. Argument: s (string)

 Ụ          Yield all indices of s, sorted by their corr. character values.
ṫ           Tail; for each index n, remove all characters before thr nth.
            This yields the list of suffixes of s, sorted by their first character,
            then (in descending order) by length.
    $       Combine the two links to the left into a chain:
   U        Upend; reverse all suffixes.
  f         Filter; only keep suffixes that are also reversed suffixes.
            This gives the list of all palindromic suffixes. Since all of them
            start with the same letter, they are sorted by length.
     Ḣ      Head; select the first, longest palindromic suffix.
      œ^    Multiset symmetric difference; chop the selected suffix from s.
         U  Upend; yield s, reversed.
        ;   Concatenate the results to the left and to the right.

Pyth (commit b93a874), 11 bytes
.VkI_IJ+zbB

Test suite
This code exploits a bug in the current version of Pyth, commit b93a874. The bug is that _IJ+zb is parsed as if it was q_J+zbJ+zb, which is equivalent to _I+zb+zb, when it should (by the design intention of Pyth) be parsed as q_J+zbJ, which is equivalent to _I+zb. This allows me to save a byte - after the bug is fixed, the correct code will be .VkI_IJ+zbJB. I'll explain that code instead.
Basically, the code brute forces over all possible strings until it finds the shortest string that can be appended to the input to form a palindrome, and outputs the combined string.
.VkI_IJ+zbJB
                z = input()
.Vk             For b in possible strings ordered by length,
       +zb      Add z and b,
      J         Store it in J,
    _I          Check if the result is a palindrome,
   I            If so,
          J     Print J (This line doesn't actually exist, gets added by the bug.
          B     Break.

How do you come up with such code? It is barely readable and absolutely not understandable by someone who is not acquainted with Pyth. What is the purpose of such a language.

@momo The purpose of the language is to write short code in, for fun. It's a recreational activity. I can write it because I have a lot of practice, and because I invented the language. I know it's not understandable to someone who doesn't know the language, which is why I included the explanation.

Ah, that explains how you knew of a bug in the language!

Python, 46 bytes
f=lambda s:s*(s==s[::-1])or s[0]+f(s[1:])+s[0]

If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the remainder of the string.
Example breakdown:
f(bonobo)
b  f(onobo) b
b o f(nobo) o b
b o n f(obo) n o b
b o n obo n o b

I think you can save a byte if you use the opposite condition (s!=s[::-1])

@aditsu That works but using a multiply is yet shorter.

Haskell, 36 bytes
f s|s==reverse s=s|h:t<-s=h:f t++[h]

More readably:
f s
 |s==reverse s = s
 |(h:t)<-s     = h:(f t)++[h]

If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the tail of the string.
The string s is split into h:t in the second guard, obviating a filler 1>0 for this case. This is shorter than doing s@(h:t) for the input.

Pyth - 16 12 bytes
4 bytes saved thanks to @FryAmTheEggman.
FGITW, much golfing possible.
h_I#+R_Q+k._

Test Suite.

Brachylog, 16 6 5 bytes (Non-competing)
:Ac.r

Try it online!
When I posted my initial answer, it was still on the old implementation in Java. Since I have reprogrammed everything in Prolog, it now works as it should have in the first place.
Explanation
(?):Ac.        Output is the concatenation of Input with another unknown string A
      .r(.)    The reverse of the Output is the Output

Backpropagation makes it so that the first valid value for A it will find will be the shortest that you can concatenate to Input to make it a palindrome.
Alternate solution, 5 bytes
~@[.r

This is roughly the same as the above answer, except that instead of stating "Output is the concatenation of the Input with a string A", we state that "Output is a string for which the Input is a prefix of the Output".

Retina, 29 25
$
¶$_
O^#r`.\G
(.+)¶\1
$1

Try it online!
Big thanks to Martin for 11 bytes saved!
This just creates a reversed copy of the string and smooshes them together. The only really fancy part of this is the reversing method: O^#r`.\G, which is done by using sort mode. We sort the letters of the second string (the ones that aren't newlines and are consecutive from the end of the string, thanks to the \G) by their numeric value, which, since there are no numbers, is 0. Then we reverse the order of the results of this stable sort with the ^ option. All credit for the fancy use of \G belongs to Martin :)

JavaScript (ES6), 92 bytes
(s,a=[...s],r=a.reverse().join``)=>s.slice(0,a.findIndex((_,i)=>r.startsWith(s.slice(i))))+r

Computes and slices away the overlap between the original string and its reversal.

CJam, 18
q__,,{1$>_W%=}#<W%

Try it online
Explanation:
q         read the input
__        make 2 copies
,,        convert the last one to a range [0 … length-1]
{…}#      find the first index that satisfies the condition:
  1$>     copy the input string and take the suffix from that position
  _W%=    duplicate, reverse and compare (palindrome check)
<         take the prefix before the found index
W%        reverse that prefix
          at the end, the stack contains the input string and that reversed prefix

Octave, 78 75 bytes
Saved 3 bytes thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ!
function p=L(s)d=0;while~all(diag(s==rot90(s),d++))p=[s fliplr(s(1:d))];end

ideone still fails for named functions, but here is a test run of the code as a program.

Lua, 89 88 Bytes
I beat the Javascript! \o/
Saved 1 byte thanks to @LeakyNun ^^
It's a full program, takes its input as command-line argument.
i=1s=...r=s:reverse()while s:sub(i)~=r:sub(0,#r-i+1)do i=i+1 end print(s..r:sub(#r-i+2))

ungolfed
i=1                             -- initialise i at 1 as string are 1-indexed in lua
s=...                           -- use s as a shorthand for the first argument
r=s:reverse()                   -- reverse the string s and save it into r
while(s:sub(i)~=r:sub(0,#r-i+1))-- iterate while the last i characters of s
do                              -- aren't equals to the first i characters of r
  i=i+1                         -- increment the number of character to skip
end
print(s..r:sub(#r-i+2))         -- output the merged string

I believe the parentheses near while can be removed?

@LeakyNun sure they can ^^

Can't do i=i+1end?

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Sadly, I can't. It would try to evaluate 1end as an hexadecimal number. Generally, you can't use [abcdef] directly after a number without it being considered an hexadecimal. There's one more exception being 0x.

Prolog, 43 bytes
a(S):-append(S,_,U),reverse(U,U),writef(U).

This expects a codes string as input, e.g. on SWI-Prolog 7: a(`hello`).
Explanation
This is basically a port of my Brachylog answer.
a(S) :-               % S is the input string as a list of codes
    append(S,_,U),    % U is a list of codes resulting in appending an unknown list to S
    reverse(U,U),     % The reverse of U is U
    writef(U).        % Write U to STDOUT as a list of codes

Perl, 37 bytes
Based on xnor's answer.
Includes +2 for -lp
Run with input on STDIN, e.g.
palindromize.pl <<< bonobo

palindromize.pl:
#!/usr/bin/perl -lp
s/.//,do$0,$_=$&.$_.$&if$_!~reverse

Vyxal, 2 bytes
Ṙ⋎

Try it Online!
 ⋎ # Merge on longest prefix/suffix with...
Ṙ  # Input reversed

05AB1E, 18 bytes
Code:
Â©gF¹ðN×®«ðñD®åi,q

Uses CP-1252 encoding. Try it online!

Pyke, 15 bytes
D_Dlhm>m+#D_q)e

Try it here!

J, 20 bytes
,[|.@{.~(-:|.)\.i.1:

This is a monadic verb. Try it here. Usage:
   f =: ,[|.@{.~(-:|.)\.i.1:
   f 'race'
'racecar'

Explanation
I'm using the fact that the palindromization of S is S + reverse(P), where P is the shortest prefix of S whose removal results in a palindrome.
In J, it's a little clunky to do a search for the first element of an array that satisfies a predicate; hence the indexing.
,[|.@{.~(-:|.)\.i.1:  Input is S.
        (    )\.      Map over suffixes of S:
         -:             Does it match
           |.           its reversal? This gives 1 for palindromic suffixes and 0 for others.
                i.1:  Take the first (0-based) index of 1 in that array.
 [   {.~              Take a prefix of S of that length: this is P.
  |.@                 Reverse of P.
,                     Concatenate it to S.

MATL, 17 16 bytes
Loosely inspired in @aditsu's CJam answer.
`xGt@q:)PhttP=A~

Try it online!
Explanation
`        % Do...while loop
  x      %   Delete top of stack, which contains a not useful result from the
         %   iteration. Takes input implicitly on first iteration, and deletes it
  G      %   Push input
  t      %   Duplicate
  @q:    %   Generate range [1,...,n-1], where n is iteration index. On the  first
         %   iteration this is an empty array
  )      %   Use that as index into copy of input string: get its first n elements
  Ph     %   Flip and concatenate to input string
  t      %   Duplicate. This will be the final result, or will be deleted at the
         %   beginning of next iteration
  tP     %   Duplicate and flip
  =A~    %   Compare element-wise. Is there some element different? If so, the
         %   result is true. This is the loop condition, so go there will be a
         %   new iteration. Else the loop is exited with the stack containing
         %   the contatenated string
         % End loop implicitly
         % Display stack contents implicitly

Haskell, 68 bytes
import Data.List
f i=[i++r x|x<-inits i,i++r x==x++r i]!!0
r=reverse

Usage example: f "abcb" -> "abcba".
Search through the inits of the input i (e.g. inits "abcb" -> ["", "a", "ab", "abc", "abcb"]) until you find one where it's reverse appended to i builds a palindrome.

Doesn't r=reverse have to go before f i=...?

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ: No, you can use any order.

I managed in 46 bytes. I bet it can be done even better.

@theonlygusti: see xnor's answer.

Ruby, 44 bytes
This answer is based on xnor's Python and Haskell solutions.
f=->s{s.reverse==s ?s:s[0]+f[s[1..-1]]+s[0]}

Can't do ==s?s:?

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ irb throws a fit if I try it. Must be something to do with how it parses ? between ?: for ternary and the ?x == 'x' substitution used since Ruby 1.9

Oracle SQL 11.2, 195 bytes
SELECT MIN(p)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(p))FROM(SELECT:1||SUBSTR(REVERSE(:1),LEVEL+1)p FROM DUAL WHERE SUBSTR(:1,-LEVEL,LEVEL)=SUBSTR(REVERSE(:1),1,LEVEL)CONNECT BY LEVEL<=LENGTH(:1));

Un-golfed
SELECT MIN(p)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(p))
FROM (
       SELECT :1||SUBSTR(REVERSE(:1),LEVEL+1)p
       FROM   DUAL
       WHERE  SUBSTR(:1,-LEVEL,LEVEL)=SUBSTR(REVERSE(:1),1,LEVEL)
       CONNECT BY LEVEL<=LENGTH(:1)
     );

Seriously, 34 bytes
╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I.

The last character is a non-breaking space (ASCII 127 or 0x7F).
Try it online!
Explanation:
╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I.<NBSP>
╩                                        push inputs to registers (call the value in register 0 "s" for this explanation)
 ╜lur                                    push range(0, len(s)+1)
     `              `M                   map (for i in a):
      ╜╨                                   push all i-length permutations of s
        "        "£M                       map (for k in perms):
         Σ╜+                                 push s+''.join(k) (call it p)
            ;;R=                             palindrome test
                *                            multiply (push p if palindrome else '')
                      Σ                  summation (flatten lists into list of strings)
                       ;░                filter truthy values
                         p               pop first element (guaranteed to be shortest, call it x)
                          ╜;;R=I         pop x, push s if s is palindromic else x
                                .<NBSP>  print and quit

C#, 202 bytes
I tried.
class P{static void Main(string[]a){string s=Console.ReadLine(),o=new string(s.Reverse().ToArray()),w=s;for(int i=0;w!=new string(w.Reverse().ToArray());){w=s.Substring(0,i++)+o;}Console.WriteLine(w);}}

Ungolfed:
class P
{
    static void Main(string[] a)
    {
        string s = Console.ReadLine(), o = new string(s.Reverse().ToArray()), w = s;
        for(int i = 0; w!=new string(w.Reverse().ToArray());)
        {
            w = s.Substring(0, i++) + o;
        }
        Console.WriteLine(w);
        Console.ReadKey();
    }

}

Can anyone provide me with any ideas to group the two calls to .Reverse().ToArray() ? A separate method is more bytes.

Jelly, 9 bytes
Ṗ;¥ƤUŒḂƇḢ

Try it online!
How it works
Ṗ;¥ƤUŒḂƇḢ - Main link. Takes a string S on the left
    U     - Reverse s
  ¥       - Group the previous 2 links into a dyad f(p, r):
Ṗ         -   Remove the last element of p
 ;        -   Concatenate the truncated p to r
   Ƥ      - Over each prefix p of s, yield f(p, rev(s))
       Ƈ  - Keep those for which the following is true:
     ŒḂ   -   Is a palindrome?
        Ḣ - Take the first

K (ngn/k), 24 bytes
{t@*&{x~|x}'t:x,/:|',\x}

Try it online!
Feels like it could be golfed more...

,\x make list of prefixes of input
t:x,/:\' append the reverse of each prefix to the original input, storing in t
*&{x~|x}' identify the index of the first item in the list that is a palindrome
t@ retrieve that list item and return it from the function

Haskell, 46 bytes
f l|l==reverse l=l|(h:t)<-l=l!!0:(f$tail l)++[l!!0]

I'm wondering if there's a way to remove the parenthesis in (f$tail l)++[l!!0]...

Why not use the variables h and t you've extracted? https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN9XSFHJqcmxti1LLUouKUxVybHNqNDKsSjRtdHNsM6zSFEq0taMzYqGqXXMTM_MUbBVKihIhyjUKijLzSvTSNBWilRKTkpOUdBSUMoDm54MYSfl5-UlgVlFiSmIRRK5CCWoYzAkA

QBIC, 41 bytes
;_FA|C=A{a=a+1~C=_fC||_XC\C=A+right$(B,a)

Explanation:
;_FA|    Read A$ from the cmd line, then flip it to create B$
C=A      Set C$ to be A$
{        Start an infinite DO-loop
a=a+1    Increment a (not to be confused with A$...)
~C=_fC|  If C$ is equal to its own reversed version
|_XC     THEN end, printing C$
\C=A+    ELSE, C$ is reset to the base A$, with
right$(B the right part of its own reversal
,a)      for length a (remember, we increment this each iteration
         DO and IF implicitly closed at EOF

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Where will the cat go? (orbital mechanics)
A nearly massless cat is dropped in space (don't worry, with a space suit and everything) at the point (x, y, z) with velocity (vx, vy, vz). There is an fixed, infinitely dense planet (with volume of 0) at the point (0, 0, 0) and it attracts objects at distance r with acceleration 1/r^2. According to Newtonian gravity, where does the object go after time t?
Nearly massless in this case means you are outputting the value of lim (mass --> 0) <position of cat>. The mass is affected by the planet's gravity, but the planet is not affected by the cat's gravity. In other words, the central body is fixed.
This is somewhat similar to Code Golf: What is the spaceship's fate? [floating point version], but this is different because it is measuring accuracy.
You may implement a solution based on a simulation, which must run in less than 3 seconds, OR you may implement a program that gives an exact value (must also run in less than 3 seconds). See scoring details below. If you implement a simulation, it does not have to be exact, but your score will be lower because of the inaccuracy.
Input: x y z vx vy vz t, not necessarily integers representing x, y, z coordinates, velocity in the x, y, and z directions and time respectively. It is guaranteed that the speed of the cat is strictly less than the escape velocity at that altitude. Input may be taken from anywhere, including parameters to a function. The program must run in less than three seconds on my laptop for t < 2^30, which means, if you are running a simulation, you must adjust your timestep accordingly. If you are planning on hitting the 3 second limit for every test case, make sure there is a tuneable parameter that can make it more accurate/less accurate for speed gains, so that I can make it run in three seconds on my computer.
Output: x y z, the position after time t.
Since the two-body problem can be solved perfectly, it is in theory possible to get a perfect, correct answer.
Scoring: For any test case, the error is defined to be the distance between your output and the "true" output. The true output is defined to be the one that the test case snippet generates. If the error is less than 10^(-8), the error is rounded down to zero. Your score is the average error on 100 (or more) random test cases. If you write a perfectly accurate answer, you should get a score of 0; lowest score wins, and ties will be broken by code length.
Test cases:
1 0 0 0 -1 0 1000000000 --> 0.83789 -0.54584 0

In this case , the orbit is perfectly circular with period 2*pi, so after circling 159154943 times, the cat ends up at approximately (0.83789, -0.54584). This isn't a test case your code will be tested on; if you submit a perfectly accurate answer, however, you may want to test it on this.
The snippet below generates random additional test cases and will be used to judge submissions; let me know if there is a bug with this:

var generateTestCase = function() {
  var periapsis = Math.random() * 10 + 0.5;
  var circularVelocity = Math.sqrt(1 / periapsis);
  var escapeVelocity = Math.sqrt(2) * circularVelocity;
  var v = Math.random() * (escapeVelocity - circularVelocity) + circularVelocity;
  var a = 1 / (2 / periapsis - v * v);
  var ecc = (a - periapsis) * (2 / periapsis - v * v);
  var semiLatus = a * (1 - ecc * ecc);
  var angM = Math.sqrt(semiLatus);
  var period = 2 * Math.PI * a * Math.sqrt(a);
  var getCoordAfterTime = function(t) {
    var meanAnomaly = t / (a * Math.sqrt(a));

    function E(e, M, n) {
      var result = M;
      for (var k = 1; k <= n; ++k) result = M + e * Math.sin(result);
      return result;
    }
    var eAnomaly = E(ecc, meanAnomaly, 10000);
    var radius = a * (1 - ecc * Math.cos(eAnomaly));
    var theta = Math.acos((semiLatus / radius - 1) / ecc);
    if (t > period / 2) theta = -theta;
    return {
      r: radius,
      t: theta,
      x: radius * Math.cos(theta),
      y: radius * Math.sin(theta)
    };
  }
  var t1 = Math.random() * period;
  var p1 = getCoordAfterTime(t1);
  var v1 = Math.sqrt(2 / p1.r - 1 / a);
  var velocityAngle1 = Math.acos(angM / p1.r / v1);
  var horizontal = Math.atan(-p1.x / p1.y);
  if (t1 < period / 2) {
    velocityAngle1 *= -1;
    horizontal += Math.PI;
  }
  var vx = v1 * Math.cos(horizontal + velocityAngle1);
  var vy = v1 * Math.sin(horizontal + velocityAngle1);
  var t2 = Math.random() * period;
  var p2 = getCoordAfterTime(t2);
  var v2 = Math.sqrt(2 / p2.r - 1 / a);
  var dummyPeriods = Math.floor(Math.random() * 100) * period + period;
  var rotate = function(x, y, z, th1, th2, th3) {
    var x1 = x * Math.cos(th1) - y * Math.sin(th1);
    var y1 = x * Math.sin(th1) + y * Math.cos(th1);
    var z1 = z;
    var x2 = x1 * Math.cos(th2) + z1 * Math.sin(th2);
    var y2 = y1;
    var z2 = -x1 * Math.sin(th2) + z1 * Math.cos(th2);
    var x3 = x2;
    var y3 = y2 * Math.cos(th3) - z2 * Math.sin(th3);
    var z3 = y2 * Math.sin(th3) + z2 * Math.cos(th3);
    return [x3, y3, z3];
  }
  var th1 = Math.random() * Math.PI * 2,
    th2 = Math.random() * 2 * Math.PI,
    th3 = Math.random() * 2 * Math.PI;
  var input = rotate(p1.x, p1.y, 0, th1, th2, th3)
    .concat(rotate(vx, vy, 0, th1, th2, th3))
    .concat([t2 - t1 + dummyPeriods]);
  var output = rotate(p2.x, p2.y, 0, th1, th2, th3);
  return input.join(" ") + " --> " + output.join(" ");
}
var $ = function(x) {
  return document.querySelector(x);
}
$("#onetestcase").onclick = function() {
  $("#result1").innerHTML = generateTestCase();
}
$("#huntestcases").onclick = function() {
  var result = [];
  for (var i = 0; i < 100; ++i) result.push(generateTestCase());
  $("#result100").innerHTML = result.join("\n");
}

  <button id="onetestcase">Generate</button>

  <button id="huntestcases">Generate 100 test cases</button>

Is time t given in seconds? If so, would the velocity be given in units per second, or something smaller?

@R. Kap It doesn't matter. t is given in unit time, whatever that is, and velocity will use the same unit. Whether it is in seconds or hours, the answer will be the same.

nearly massless cat Well, what would the exact mass of the cat be? Should we just use 0 as a value for the mass of this cat?

@R. Kap Yes. But it is still affected by gravity (usually, Newton didn't consider objects with no mass to be affected by gravity). So we should consider it to have arbitrarily small mass, and your answer is actually the position as the mass of the cat goes to zero. The main point is that the planet itself is not affected at all by the cat.

Maybe I'm missing something, but a massless cat isn't affected by gravety, so it's location at time t = [x,y,z]+t*[vx,vy,vz]...

@agtoever Read my previous comment. Yes it is "massless" in the sense that you are outputting the value of lim (mass --> 0) <position of cat>. The mass is never 0, but is arbitrarily small.

@soktinpk it might be easier to just explicitly say that the central body is fixed.

Mew? I love cats. :3 :P

What precision is required?

@isaacg Updated. 4 decimal digits

@AlexL. me and tac thank you.

10^-8 accuracy for times out to 2^30 in less than 3 seconds is a little unrealistic for simulation no? What is the exact solution?

@David your score is your accuracy. So you don't have to get 10^-8 accuracy for a simulation; better accuracy = lower score = better chance of winning. You don't have to post an exact solution.

No calculation necessary. The answer to "Where will the cat go?" is always land on their feet.

Python 3.5 + NumPy, exact, 186 bytes
from math import*
def o(r,v,t):
 d=(r@r)**.5;W=2/d-v@v;U=W**1.5;b=[0,t*U+9]
 while 1:
  a=sum(b)/2;x=1-cos(a);y=sin(a)/U;k=r@v*x/W+d*y*W
  if a in b:return k*v-r*x/W/d+r
  b[k+a/U-y>t]=a

This is an exact solution, using a formula I engineered based on Jesper Göranssonhis, “Symmetries of the Kepler problem”, 2015.  It uses a binary search to solve the transcendental equation Ax + B cos x + C sin x = D, which has no closed-form solution.
The function expects the position and velocity to be passed in as NumPy arrays:
>>> from numpy import array
>>> o(array([1,0,0]),array([0,-1,0]),1000000000)
array([ 0.83788718, -0.54584345,  0.        ])
>>> o(array([-1.1740058273269156,8.413493259550673,0.41996042044140003]),array([0.150014367067652,-0.09438816345868332,0.37294941703455975]),7999.348650387233)
array([-4.45269544,  6.93224929, -9.27292488])

What does the @ do?

It’s a new operator in Python 3.5 that NumPy overloads for numpy.dot (dot product/matrix multiplication). See PEP 465.

It's great that it's golfed, but this is code-challenge, could you make it a bit clearer, I had some scratchwork in Python done, and can calculate the anomaly, theta, eccentricity, period, etc, but I'm stuck on determining the sign of theta and determining the rotation from x-y reference plane to 3d space. Still, this is really great stuff

@miles Since ties are broken by code length, it makes sense for this to be golfed.

That's true, as I was working on an exact solution too, since the test case generator only creates elliptical orbits

Javascript
This is just to get the ball rolling, since no one seems to be posting answers. Here is a very naive, simple way that can be improved a lot:
function simulate(x, y, z, vx, vy, vz, t) {
  var loops = 1884955; // tune this parameter
  var timestep = t / loops;
  for (var i = 0; i < t; i += timestep) {
    var distanceSq = x*x + y*y + z*z; // distance squared from origin
    var distance = Math.sqrt(distanceSq);
    var forceMag = 1/distanceSq; // get the force of gravity
    var forceX = -x / distance * forceMag;
    var forceY = -y / distance * forceMag;
    var forceZ = -z / distance * forceMag;
    vx += forceX * timestep;
    vy += forceY * timestep;
    vz += forceZ * timestep;
    x += vx * timestep;
    y += vy * timestep;
    z += vz * timestep;
  }
  return [x, y, z];
}

Testing:
simulate(1, 0, 0, 0, -1, 0, Math.PI*2) --> [0.9999999999889703, -0.0000033332840909716455, 0]

Hey, that's pretty good. It has an error of about 3.333*10^(-6) which isn't enough for it to be rounded down... it's close.
Just for fun:
console.log(simulate(1, 0, 0, 0, -1, 0, 1000000000))
--> [-530516643639.4616, -1000000000.0066016, 0]

Oh well; so it's not the best.
And on a random test case from the generator:
simulate(-1.1740058273269156,8.413493259550673,0.41996042044140003,0.150014367067652,-0.09438816345868332,0.37294941703455975,7999.348650387233)
-->    [-4.528366392498373, 6.780385554803544, -9.547824236472668]
Actual:[-4.452695438880813, 6.932249293597744, -9.272924876103785]

With an error of only approximately 0.32305!
This can be improved a lot by using something like Verlet integration or some fancy algorithm. In fact, those algorithms may even get perfect scores, despite being simulations.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Tips for King of the Hill bots
What general tips do you have for creating a bot to participate in a King of the Hill challenge? What strategies do you use to go from considering the challenge to creating your bot? What data structures do you find most useful?
Please post one tip per answer.

I feel like this depends way too much on the specific problem.

@QPaysTaxes I modeled this directly after many of the other tips questions. Is there a way to fix this question to be better? Also, do those older tips questions also need to be fixed?

The older tips questions are based on languages as far as I can tell, which means that the tips are universal but you might not use them. This question is more analogous to "Tips for Code Golf challenges" – where it depends entirely on the challenge. However, as the answers below prove, there are a few universal things. I'm conflicted.

I think this depends as much on the specific questions as "tips for golfing in (lang)", because you use a lot of different language features in different challenges anyway

Finding Nash Equilibria
This is a very important concept when the KOTH involves a relatively simple set of decisions, involves only a few players (typically 2), and is deterministic.  A Nash equilibrium describes a "gridlock" position: if the two players have decided upon their two strategies, then the two players are effectively locked in those positions: either player changing their strategy simply creates additional vulnerabilities.
Examples of games where Nash equilibria are important are:

Rock-Paper-Scissors(-Lizard-Spock), in which an "unbeatable" strategy is random play
Morra, which has a "spectrum" of equilibria. Peter Taylor wrote a good example in his answer here.
Prisoner's Dilemma, a cooperative game notable for having an "everybody loses" gridlock

How to find an equilibrium
Finding an equilibrium actually is actually pretty simple for most simple games, and is often pretty intuitive.  A ton of detail about the various methods can be found on the internet.  The basic concept, which is normally applicable, is to create a list of possible strategies that the two players can use (the options provided by the game).  If one strategy is "dominated" by another, then that strategy can be removed from the list, and the process is repeated. By "domination," I mean that if strategy A always gives an equal-or-better result than strategy B, against all of the remaining opponent strategies, then strategy B can be removed from the list.
Example: Rock-Paper-Scissors
RPS has something called a "mixed" equilibrium, meaning that a distribution is involved.  Rather than playing the same move repeatedly (which will lead to quick defeat), the equilibrium is to play 1/3 rock, 1/3 paper, and 1/3 scissors in a random distribution.  If I play randomly, there is nothing my opponent can do to get an edge on me, period.  If my opponent chooses not to play randomly, then that only creates a vulnerability on his part.
Games with mixed equilibrium are probably the most common on PPCG, since they can take many forms (the only interesting game I can think of with a pure equilibrium is prisoner's dilemma).  I should note that the mixed equilibrium doesn't have to be uniformly random, simply something other than playing the same move every time.
Using this information
The Nash equilibrium of a game often represents the "baseline" from which you should try to operate.  In RPS, playing randomly guarantees a finishing spot around the middle of the pack.  In order to move to the top, you have to start identifying other player's weaknesses.
To do this, you should stick to the equilibrium when unsure of the opponent's weaknesses.  Once those weaknesses have been identified (you have detected that your opponent is not in equilibrium), then you need to gently shift out of equilibrium to take advantage of your opponent.  This action, in turn, creates weaknesses on your own part.  You must then detect when your opponent is changing his strategy, so that you can then stop the attack and resume random play.
Detecting variation from equilibrium
This is pretty difficult, and I am not an expert.  Variations can come in many forms:

Favoring some options above/below others for no reason, like an RPS player that plays rock twice as often as scissors, or one that avoids playing paper.  Some relatively simple statistics can detect this.
Basing a current move off past moves, in some predictable pattern.  This includes copy-cats, "beats what beats your last move" bots, or "cycling" bots.  This takes additional logic to detect, since the overall move distribution can be evenly-distributed, even though the moves aren't random.  You should attempt to take the record of moves and find correlations like "the move I made 2 turns ago and the move my opponent made now" and "the move he made 1 turn ago, and the move he made now", etc.
Bots whose move distribution is based off of yours.  The vulnerability in these bots is often not created (in a measurable quantity) until after you have yourself varied from a random distribution.  Generally, your own bot falls into this category.

Use a meta strategy
For almost every clever strategy there's another strategy that beats it: For example, your opponent might use exactly the same reasoning as you to anticipate your next move and then counteract it. Now you might try to second-guess your opponent again, but it's hard to know when to stop.
Another problem is that a strategy that is good at second-guessing a clever opponent might be far from optimal against more simple opponents.
How can you solve this? You let your bot decide on the fly which strategy to use!
For this, you start off with giving your bot a repertoire of different strategies. Then, before each move, your bot looks at the recorded history of the game so far and evaluates how these different strategies would have fared. It then pics the one that would have been most successful.
Including strategies that are strong in the first place will help to give your bot good options to choose from. But you should also include really simple ones, because they often work better against dumb opponents.
You might consider to put a bias on some strategies, either to avoid overfitting (e.g. trying to beat a pattern where the opponent just acts randomly) or to favor certain strategies in the beginning when there isn't yet much information.
Of course, this approach will only work for certain kinds of king-of-the-hill challenges. It did really well for me in a Rock-Paper-Scissors-Lizard-Spock match. In other games it can be almost impossible to evaluate how a certain strategy would have fared if it was not actually played.
An extreme form of this meta approach (that borders on cheating) would be to include the known behavior of all other bots into your own bot, such that it can perfectly anticipate their moves.

including the known behavior of all other bots into your own bot doesn't just border on cheating, it is cheating. I'm fairly certain it's a disallowed loophole.

Be specific about the requirements to run your bot
Bots can be written in a variety of languages (and versions of those languages), so it helps everyone out when you:

Test it in the environment the OP specifies (or as close to it as you can).
Test it in a variety of other environments if possible (to help others who want to run it).
Be specific about the language and version you use, and explain how to run your bot.

As a bonus: if you are using a lesser known language, make a link to where people can download the binary/source to run it.

If team based, work together with your team
While you can usually write a bot that works solo to complete tasks to help your team, there's a much greater advantage when you coordinate both in and out of the game. A prime example of this can be seen in Red vs. Blue - Pixel Team Battlebots.
During development, teams were able to chat and discuss how to coordinate their bots to function better than alone. While technically the same bot, SphiNotPi3000 was written to work in tandem with another of itself, and was able to move in ways that accounted for the weaknesses it would have faced if it were on its own. The end result was that they were able to almost completely dominate the battlefield, even when it was just the two of them against the entire other team.
So outside the game, plan and coordinate with your teammates on what strategies to cover. Maybe someone has a bot that scans the map diagonally? Have yours scan horizontally (just an example). Inside the game, if the challenge allows for team communication, take advantage of it. In the battlebots game for example, you could send a message to your teammates on the position of bots outside their field of vision, and then encourage them to write their bots in a compatible way to make use of those signals.

Add Randomness (if allowed)
Making your bot move somewhat randomly, especially if there are multiple options that seem to be equally good, makes it far harder to predict the behavior of the bots. In some challenges, it's even worth having a probability of making a suboptimal move if other bots are designed to take the optimal move, as it makes it less likely you end up doing the same thing, which is a disadvantage in many challenges.
As a bonus, if hardcoding behavior to go after a specific bot or calculating what moves they will make is allowed, randomness makes it significantly more likely you can put up a fight against them.


text:
Write a narcissist program!
A narcissist program is simple.  It is related to a quine.
If the input is equal to it's source code, it prints a truthy value, if not it prints a falsy one.  That is it.
Rules:

It can't read it's own file.
This is code-golf, so the shortest answer wins.
Hash functions are not allowed.  This trivializes it into just string matching.
The submission may be a function.

An example would be:
Code:
someprogramhere

Input:
someprogramhere

Output:
1

Or input:
a

Output:
0

Your code most certainly won't be someprogramhere, but you get the idea.
Go code.

JavaScript ES6, 14 bytes
$=_=>_==`$=`+$

Simple modification of the traditional "bling quine".


text:
Tips for golfing in Racket / Scheme
What general tips do you have for golfing in Racket / Scheme? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Racket / Scheme (e.g. "remove comments" is not an answer).

I'm aware Scheme and Racket (formerly PLT Scheme) are technically different languages but are quite similar in many ways and much code (I suspect) will run mostly as intended in either. If your tip only applies to one of the aforementioned languages, note as such.

The expressions 'x, `x, ,x, an ,@x automatically expand to (quote x), (quasiquote x), (unquote x), and (unquote-splicing x), respectively.  This is purely a syntactic transformation, and can be applied anywhere. This gives a convenient notation for one-variable functions:
; Defining a function:
(define ,x (+ x x))
; Calling a function:
(display ,2)

which expands to
; Defining a function:
(define (unquote x) (+ x x))
; Calling a function:
(display (unquote 2))

I'm not sure what the semantics for shadowing a syntactic keyword such as quote or quasiquote with a bound variable, although code like the above worked in the interpreters I tested it on, and unquote-splicing is less than ideal since it has a two-character abbreviation, but unquote is an auxillary syntax with a one-character abbreviation and so is ideal for this hack.

In Racket, λ and lambda are synonymous keywords for constructing anonymous functions, but λ is 2 bytes where lambda is 6.
In Scheme, there's no such keyword λ and you're stuck with lambda.

Use ~a to convert numbers and symbols to strings.

could u give an example?

Examples: https://docs.racket-lang.org/reference/strings.html?q=~a#%28def._%28%28lib.racket%2Fformat..rkt%29.~7ea%29%29

thanks! Does this work for scheme as well?

No. The funtion ~a belongs to racket/format which is automatically included in #lang racket.

Use shorter synonyms
There's a number of procedures in Racket that have mostly-equivalent shorter versions. (They are usually not equivalent: for example, (car (cons 1 2)) works where (first (cons 1 2)) fails. But you can make the substitution if you know they are synonyms in your case.)
This list is probably incomplete: I probably don't know about most of the things that could go in this list yet.

(= a b) instead of (equal? a b) when comparing numbers.
'(1 2) instead of (list 1 2).
car, cadr, cdr for first, second, and rest.
null? instead of empty?
modulo instead of remainder when the modulus is positive.
floor instead of truncate when its argument is positive.

When using Racket, bind variables using λ to shave off a few bytes. In Scheme, lambda makes this trick not applicable, unless one is binding four or more variables.
Example: One variable saves 2 bytes over let/define
(define n 55)(* n n) ; 20 bytes

(let([n 55])(* n n)) ; 20 bytes

((λ(n)(* n n))55) ; 18 bytes

I wouldn't call that binding. You are using different functions. In some cases, using an anonymous function is shorter than binding a variable.

I'm not sure what your opinion has to do with the typical terminology used in scheme circles. I can assure you both ways are binding variables to a lexical scope, and let is often implemented in terms of lambda.

In Racket, require forms can have multiple arguments.
(require net/url net/uri-codec)

Is way shorter than
(require net/url)(require net/uri-codec)

I don't know much about Scheme, but it doesn't seem to have a require builtin.

Omit needless spaces
This can be considered a "trivial" tip, but it has to be pointed out somewhere.
Any time you read Racket code written by normal people (e.g. in the Racket documentation) it will have all the spaces put in: for example,
(append (list 1 2) (list 3 4) (list 5 6) (list 7 8))

In fact, since ( and ) can't be part of variable names, we can delete all the spaces around them and not lose any ambiguity (and, more importantly, still get valid code). So the above expression can instead be:
(append(list 1 2)(list 3 4)(list 5 6)(list 7 8))

The following tips are for Racket:
Default arguments
Especially useful for creating aliases for long function names that are used often.
Assume the golf allows you to write a function that consumes the argument, and assume you need to use reverse a lot.
You'll start with something like:
(λ(x) ... reverse ... reverse ... reverse ...

You can instead take in an additional argument, with a shorter name than reverse, and set its default value to reverse:
(λ(x[r reverse]) ... r ... r ... r ...

Furthermore, it's useful if you have a helper function that you use in many places with some of the same arguments. Remember to reorder the arguments to the function as needed, so you can use as many default arguments as possible, and remove the arguments from multiple callsites.
match
This one is a little harder to summarize in a small post, so read up on the Racket Docs for this one.
In a nutshell, match allows you extract elements and sequences of elements in a certain order from a list, and the quasiquote syntax lets you stitch the mutilated list back together:
(match (range 10)
 [`(,xs ... 3 ,ys ... 6 ,zs ...)
  `(,@(map f xs) 3 ,@(map f ys) 6 ,@(map f sz))]
 ...

It also gives you an easy way to work with regular expressions and do additional computation on the resulting groups afterwards,
Named let
See the named let proc-id ... syntax here.
This allows you to write recursive functions that are called immediately without define or actually calling the function after you've defined it.
Something like:
(define (fib i)
  (if (< i 2) i
      (+ (fib (- i 1)) (fib (- i 2)))))
(fib 10)

can be shortened to:
(let fib {[i 10]}
  (if (< i 2) i
      (+ (fib (- i 1)) (fib (- i 2)))))

This last one is silly, but I haven't been able to use this little trick anywhere so far:
(apply map list matrix) takes a transpose of matrix, where matrix is some rectangular list of lists, like '((1 2 3) (a b c)).
Let me know if this does prove to be useful.

As Winny pointed out, #! can usually be used instead of #lang, saving four bytes.
#lang racket ;12 bytes
#!racket ;8 bytes

I know this is an old answer, but in most cases you can exclude it entirely from the byte count


text:
Rectangle Detection
Write a program or function that takes in a multiline string of 0's and 1's. No other characters will be in the string and the string will always be rectangular (all lines will have same number of characters), with dimensions as small as 1×1, but otherwise the 0's and 1's may be arranged arbitrarily.
You may assume the string has an optional trailing newline, and if desired you may use any two distinct printable ASCII characters in place of 0 and 1.
Print or return a truthy value if all of the path connected regions of both 0's and 1's in the string are solid rectangles, else output a falsy value.
A path connected region of 0's means that from any one 0 in the region, all the other 0's can be reached by only moving up, down, left and right to other 0's (and not moving diagonally, not moving to any 1, and not moving outside the string bounds). The same idea applies to 1 path connected regions.
A solid rectangle of 0's means the entire area of the rectangle is filled with 0's and no 1's. The same idea applies to 1 solid rectangles.
The shortest code in bytes wins. Tiebreaker is earlier answer.
(Note that the string does not wrap around with toroidal boundary conditions.)
Examples
1) This input string has 3 path connected regions (2 for 0 and 1 for 1). Only the bottom right 00 region is a solid rectangle though, so the output would be falsy.
0011
0111
0100

2) This input string has 4 path connected regions (2 for both 0 and 1). All of them are solid rectangles so the output would be truthy.
0011
0011
1100

3) This input has 2 path connected regions, but only one of them is a solid rectangle, so the output would be falsy.
00000000
01111110
00000000

4) This input has only 1 path connected region and is trivially a solid rectangle, so the output is truthy.
11111111
11111111
11111111

Test Cases
A T just below the input string means truthy, F means falsy.
0
T

1
T

00
T

01
T

10
T

11
T

0000000
T

1111111
T

011100100100101100110100100100101010100011100101
T

00
11
T

01
10
T

01
11
F

00
01
F

11
11
T

110
100
F

111
000
T

111
101
111
F

101
010
101
T

1101
0010
1101
0010
T

1101
0010
1111
0010
F

0011
0111
0100
F

0011
0011
1100
T

00000000
01111110
00000000
F

11111111
11111111
11111111
T

0000001111
0000001111
T

0000001111
0000011111
F

0000001111
1000001111
F

1000001111
1000001111
T

1110100110101010110100010111011101000101111
1010100100101010100100010101010101100101000
1110100110010010110101010111010101010101011
1010100100101010010101010110010101001101001
1010110110101010110111110101011101000101111
F

Jelly, 7 bytes
ṣ⁷µ=ḢZE

This uses the same algorithm as @LevelRiverSt's Ruby answer. The actual algorithm fits in the last 4 bytes; the first 3 bytes are required to parse the input format.
Try it online!
How it works
ṣ⁷µ=ḢZE  Main link. Argument: t (string)

ṣ⁷       Split t at linefeeds..
  µ      Begin a new, monadic link. Argument: A (list of strings)
    Ḣ    Pop the first string of A.
   =     Compare all other strings in A with the first.
         = compares characters, so this yields a list of Booleans for each string.
         For a truthy input, all pairs of lines now have been transformed in lists
         of only 1's or only 0's. That means all columns must be equal.
     Z   Zip; transpose rows with columns.
      E  Check if all rows (former columns) are equal to each other.

Jelly, 11 10 bytes
ṣ⁷^2\⁺€FS¬

Massive thanks to @Dennis for golfing this one down to half its original size (via undocumented features).
Try it online! Note that the triple quotes are for a multiline string.
Explanation
The basic algorithm is: return true iff every 2x2 subgrid has an even number of 1s (or, equivalently, 0s).
It's clear why an odd number of 1s can't work, since we would have one of the following:
10  01  00  00  01  10  11  11
00  00  01  10  11  11  10  01

Note that the first 4 are rotations of the same thing, and ditto for the last 4. The reflex angle can't be part of a rectangle, hence why it would be invalid.
In other words, all 2x2 subgrids must be one of the following:
00  00  11  01  10  01  10  11
00  11  00  01  10  10  01  11

which, if we look at the boundaries, can be imagined as the following "puzzle pieces":
 ___    ___    ___    ___
|   |  | | |  |   |  | | |
|   |  | | |  |---|  |-|-|
|___|  |_|_|  |___|  |_|_|

And try forming a non-rectangle with those puzzle pieces :) (whilst having the ends match up)
The actual implementation is thus:
ṣ⁷               Split input by newlines to give rows
  ^2\            Taking overlapping sets of 2 rows at a time: accumulate rows by XOR
                 Note that strings cast to integers automatically for bitwise operators
     ⁺€          Repeat the previous link (⁺), on each (€) element in the resulting array
       F         Flatten the array
        S        Sum (effectively reducing by OR)
         ¬       Logical negation of the result

For example, for the input
100
010
000
101

we have:
  ṣ⁷: ["100", "010", "000", "101"]
 ^2\: [[1, 1, 0], [0, 1, 0], [1, 0, 1]]    (e.g. first entry is "100" ^ "010")
^2\€: [[0, 1], [1, 1], [1, 1]]             (e.g. the first entry is [1^1, 1^0] - this
                                            gives the counts of 1s in each subgrid, mod 2)
   F: [0, 1, 1, 1, 1, 1]
   S: 5                                    (this gives the number of invalid 2x2 subgrids,
                                            which is indeed all but the top left)
   ¬: 0

Can you please go document the features you used? If people do that then documentation will happen!

Do you need to flatten?

@CatsAreFluffy If you don't flatten, Jelly tries to sum a list of vectors and you get a vector as a result

Just sum and sum-it's better!

"Undocumented features" -- aha! So that's how Dennis outgolfs everyone! :D

Ruby, 76
->s{j=!r=1
s.lines{|t|i=t.to_i(2)
j&&r&&=(j^i)%t.tr(?0,?1).to_i(2)<1
j=i}
r}

In any grid composed entirely of rectangles, each line must be identical to the line before, or have all bits flipped from 0 to 1 and vice versa.
This is easy to prove. Take a piece of paper and draw arbitrary vertical and horizontal lines all the way across it. Now colour the rectangles using only 2 colours. You will end up with a distorted checkerboard, where all the colours flip at each line.
Want to draw rectangles with lines only part way across? try deleting a segment of any of your lines. You will now need more than 2 colours to colour your design, because you will have points where 3 rectangles meet (2 corners and an edge.) Such designs are therefore irrelevant to this question.
I'm surprised answers so far haven't noticed this.
I think this algorithm should be a lot shorter in some other language.
Ungolfed in test program
f=->s{
  j=!r=1                              #r = truthy, j=falsy
  s.lines{|t|                         #for each line
    i=t.to_i(2)                       #i = value of current line, converted to a number in base 2 (binary)
    j&&                               #if j is truthy (i.e this is not the first line)
      r&&=(j^i)%t.tr(?0,?1).to_i(2)<1 #XOR i with the previous line. Take the result modulo (current line with all 0 replaced by 1)
                                      #if the result of the XOR was all 0 or all 1, the modulo == zero (<1). Otherwise, it will be a positive number.
j=i}                                  #j = value of current line (always truthy in ruby, even if zero)
r}                                    #return 1 or true if all the modulo calculations were zero, else false.

#text to print after test case to check answer is as desired
T='T

'
F='F

'

#test cases
puts f['0'],T

puts f['1'],T

puts f['00
'],T

puts f['01'],T

puts f['10'],T

puts f['11
'],T

puts f['0000000'],T

puts f['1111111'],T

puts f['011100100100101100110100100100101010100011100101'],T

puts f['00
11'],T

puts f['01
10'],T

puts f['01
11'],F

puts f['00
01'],F

puts f['11
11
'],T

puts f['110
100'],F

puts f['111
000'],T

puts f['111
101
111'],F

puts f['101
010
101
'],T

puts f['1101
0010
1101
0010'],T

puts f['1101
0010
1111
0010'],F

puts f['0011
0111
0100
'],F

puts f['0011
0011
1100'],T

puts f['00000000
01111110
00000000'],F

puts f['11111111
11111111
11111111'],T

puts f['0000001111
0000001111'],T

puts f['0000001111
0000011111'],F

puts f['0000001111
1000001111'],F

puts f['1000001111
1000001111'],T

puts f['1110100110101010110100010111011101000101111
1010100100101010100100010101010101100101000
1110100110010010110101010111010101010101011
1010100100101010010101010110010101001101001
1010110110101010110111110101011101000101111'],F

I bet using s.scan(/^?.*\n/) would help save bytes.

Snails, 20 bytes
!{to{\0w`3\1|\1w`3\0

Prints the area of the grid if there isn't a 2x2 square with 3 zeroes and a one or 3 ones and a zero, or 0 if such a 2x2 square exists.

MATL, 12 bytes
Ybc2thYCs2\~

Same algorithm as @sp3000's great answer.
To allow multiline input, MATL needs the row char array (string) to be explicitly built using character 10 for newline. So the input of the four examples are (note that [] is concatenation, so each of these is a row array of chars):
['0011' 10 '0111' 10 '0100']
['0011' 10 '0011' 10 '1100']
['00000000' 10 '01111110' 10 '00000000']
['11111111' 10 '11111111' 10 '11111111']

and the last three test cases are
['0000001111' 10 '1000001111']
['1000001111' 10 '1000001111']
['1110100110101010110100010111011101000101111' 10 '1010100100101010100100010101010101100101000' 10 '1110100110010010110101010111010101010101011' 10 '1010100100101010010101010110010101001101001' 10 '1010110110101010110111110101011101000101111']

Truthy output is an array containing only ones.
Try it online!
Explanation
This uses the fact that the parity of chars '0' and '1' is the same as that of numbers 0 and 1, so there's not need to convert from char to the digit it represents,
Yb     % split implicit input by whitespace. Gives a cell array
c      % concatenate cell contents into 2D char array
2th    % push array [2 2]
YC     % get 2×2 sliding blocks and arrange as columns
s      % sum of each column
2\     % modulo 2 of each sum
~      % negate. Implicit display

Input needs to be a string

@HelkaHomba MATL doesn't allow multiline string input... The input would have to be a row array of the form ['first line' 10 'second llne'], where 10 is ASCII for newline. Is that acceptable?

@HelkaHomba I've used that in the updated answer. Alternatively, can space be used instead of newline? First example would be string '0011 0111 0100'

@LuisMendo I appreciate the thought, but I think the Ruby answer might actually be golfier in general here :)

@Sp3000 Oh, I hadn't seen that one. Very clever too

JavaScript (ES6), 79
Same algorithm of Jelly answer from @Sp3000 (and happy not having to prove it works). Just 8 times longer
s=>[...s].every((x,i)=>[++i,i+=s.search`
`,i+1].some(p=>!(x^=p=s[p],p>`
`))|!x)

Less golfed
s=>[...s].every((x,i)=> // repeat check for every sub square
     [++i,                  // array of position for next char in row
      i+=s.search`\n`, i+1] // and 2 chars at same column in next row
       .some(p=> // for each position
          !(
            x^=s[p],  // xor current value with value at position p
            s[p]>`\n` // true if value at position p is valid
           ) // the condition is negated
       ) // if any value scanned is not valid, .some return true
         // else, we must consider the check for current square
       | !x // x can be 0 or 1, to be valid must be 0
   )

Test suite

f=s=>[...s].every((x,i)=>[++i,i+=s.search`
`,i+1].some(p=>!(x^=p=s[p],p>`
`))|!x)

testData=`
0
T

1
T

00
T

01
T

10
T

11
T

0000000
T

1111111
T

011100100100101100110100100100101010100011100101
T

00
11
T

01
10
T

01
11
F

00
01
F

11
11
T

110
100
F

111
000
T

111
101
111
F

101
010
101
T

1101
0010
1101
0010
T

1101
0010
1111
0010
F

0011
0111
0100
F

0011
0011
1100
T

00000000
01111110
00000000
F

11111111
11111111
11111111
T

0000001111
0000001111
T

0000001111
0000011111
F

0000001111
1000001111
F

1000001111
1000001111
T

1110100110101010110100010111011101000101111
1010100100101010100100010101010101100101000
1110100110010010110101010111010101010101011
1010100100101010010101010110010101001101001
1010110110101010110111110101011101000101111
F`

console.log=x=>O.textContent+=x+'\n'

testData.split('\n\n').forEach(t=>{
  var k=t.slice(-1)=='T',
      r=f(t.slice(0,-1))
  console.log(t+' '+r+ (k==r?' OK\n':' KO\n'))
})

Now 8 times longer!

JavaScript (ES6), 69 bytes
s=>!s.split`
`.some((t,i,u)=>[...t].some((v,j)=>v^t[0]^u[0][j]^s[0]))

I believe that the path connectedness rectangle criterion is equivalent to requiring that given any four points that form the corners of an arbitrary rectangle that there is an even number of 1s. Note that the parity of the rectangle (0, b), (x, y) is the same as (0, b), (a, y) ^ (a, b), (x, y) so I only have to check those rectangles whose top left corner is at (0, 0). Also by De Morgan's laws, !.some() is the same as .every(!) which saves me a couple of bytes.
Edit: I notice that the Jelly solution checks the parity of the corners of all 2×2 rectangles, which can be shown to be equivalent.

almost 7 times, but +1

Grime v0.1, 31 bytes
E=\0+|\1+
N=.+&E!
e`(E/N|N/E)#!

Prints 1 for match and 0 for no match. Try it online!
Explanation
Grime is my 2D pattern matching language.
I did modify it today, but only to change the character of a syntax element (` instead of ,), so it doesn't affect my score.
I'm using a similar approach to that of Sp3000: an input is falsy if it contains a 2×N rectangle whose one row contains both 0 and 1, and the other row does not.
E=             Define a nonterminal E, which matches
  \0+|           a horizontal run of one or more 0s, OR
      \1+        a horizontal run of one or more 1s.
N=             Define a nonterminal N, which matches
  .+             a horizontal run of one or more characters,
    &E!          which is NOT matched by E (so contains both 0 and 1).
e`             Match entire input to this pattern:
            !    not
           #     contains
  (E/N|N/E)      E on top of N, or N on top of E

JavaScript (ES6), 64 bytes
s=>(a=s.split`
`).every(l=>l==a[0]|l==a[0].replace(/./g,n=>n^1))

Based on @LevelRiverSt's observation that each line must either be the same or the opposite of the first.