APL+WIN
Works by starting in the centre and converges on the location by setting the upper or lower limit to the last value and adding or subtracting half the difference to the appropriate limit to the last guess on each iteration.
API
id←¯20↑¯2↓GetUrl 'http://easter_egg_hunt.andrewfaraday.com/new_game'
xh←yh←100 ⋄ xl←yl←0 ⋄ x←50 ⋄ y←50 ⋄ c←0
:repeat
    xy←GetUrl 'http://easter_egg_hunt.andrewfaraday.com/guess/',id,'/',(⍕x),'/',⍕y
    xy←(('higher'⍷xy)+(¯1×'lower'⍷xy)+2×'right'⍷xy)~0
    :if xy[1]=1 ⋄ xl←x ⋄ x←x+⌈(xh-x)÷2 ⋄ :endif
    :if xy[1]=¯1 ⋄ xh←x ⋄ x←x-⌈(x-xl)÷2 ⋄ :endif
    :if xy[2]=1 ⋄ yl←y ⋄ y←y+⌈(yh-y)÷2 ⋄ :endif
    :if xy[2]=¯1 ⋄ yh←y ⋄ y←y-⌈(y-yl)÷2 ⋄ :endif
    c←c+1
:until 4=+/2↑xy
'id:',id,' x:',(⍕x),' y:',(⍕y),' count:',⍕c

This function uses the following function to do the API calls:
r←GetUrl url
⎕wself←'HTTP' ⎕wi 'Create' 'MSXML2.ServerXMLHTTP'
⎕wi 'XOpen' 'GET' url 0
⎕wi 'XSend'
r←⎕wi 'xresponseText'

The results for 10 trys were:
id:rbgprkxrqzzhwdfsbszn x:36 y:52 count:7
id:nmpcxdqsdzhgrbtlcpbp x:35 y:49 count:6
id:qqnsbpwnlbptxxblywnz x:99 y:22 count:6
id:nsytnvcgnsyrgzvjcysc x:45 y:28 count:6
id:yfkpfhphjpqxtqnwpmhv x:95 y:40 count:7
id:kxhszzrhxqlnvwvwjgnm x:49 y:6 count:6
id:rwnwfgdpzcjpzzfmgcfn x:93 y:34 count:7
id:tcvhtpqlfrwngybsyzqh x:95 y:94 count:6
id:pmlmqnprwcjggjfhttmy x:20 y:41 count:6
id:kpsmmhfhxxrrlvbbgzkv x:9 y:28 count:5


JavaScript (ES6), 64 bytes

Takes input as a string.

f=(n,i=0,[d,t]=n.split(/(...)$/))=>t?f(d,i+1)+['kMGT'[d&&i]]+t:d

Try it online!

How?

The regular expression /(...)/$ matches the last three digits of the integer, or nothing at all if there are less than 3 digits remaining.

Because there's a capturing group, these digits -- if present -- are included in the output of the .split() method.

Examples:

'123456789'.split(/(...)$/) // --> [ '123456', '789' '' ]
'123'.split(/(...)$/))      // --> [ '', '123' ]
'12'.split(/(...)$/))       // --> [ '12' ]
''.split(/(...)$/))         // --> [ '' ]

Commented

f = (                 // f is a recursive function taking:
  n,                  //   n = input
  i = 0,              //   i = index of next prefix
  [d, t] =            //   d = either the leading digits without the last 3 ones,
                      //       or all remaining digits if there are less than 3
    n.split(/(...)$/) //   t = last three digits (or undefined)
) =>                  //
  t ?                 // if t is defined:
    f(d, i + 1) +     //   append the result of a recursive call with d and i + 1
    ['kMGT'[d && i]]  //   append the prefix if d is defined, or an empty string otherwise
    + t               //   append the last 3 digits
  :                   // else:
    d                 //   stop recursion and return the remaining digits


Unary, 1
The program is a string of 47297560408284 zeroes
i.e.
000000000000000000000000000000000000000000.... 47297560408284 times

A brainfuck quivalent code would be
+[>+<+++++]>--.

which just prints 1
as in unary, the whole program is made up of just 0 which are all a single token.


J, 66 bytes

1#.2|@-/\1e3&((-:@[%:_1:)^[:i.1+[*0{])((*{:)+[*(1{])*1e3%~i.@#@[)]

Try it online!

This could be golfed more, but I'm putting it away for now.

Instead of taking an analytic approach I am using complex number arithmetic to break the spiral down into 1000 straight line segments per rotation, and then summing those segments.

I find the 500th root of -1, and keep multiplying it by itself to rotate it and get an approximation to the next spiral point.

Because the spiral also moves outward, we need to take the new vector, normalize it, multiply the normal vector by 1/1000 of the thickness, and then add that little correction to the new vector.

Conceptually, we're doing something similar to approximating a circle's circumference with the short sides of many triangles.

The idea is simple, but the golf part of it boils down to boring bookkeeping and argument parsing which isn't worth going into.  In theory the realization of this method could be a lot shorter.


Jelly, 35 bytes

L€ṀR,Ṛ$ċƲȧ3
L€,;¥LE€S+Ç
ỴµZL«L>1ȧÇ

Try it online!

0 = Mess
1 = Rectangle
2 = Square
3 = Triangle


Create a simple math calculator +-/* accepting only Chinese characters

Java

It parses the equation as a context-free language, using these productions for that:

U1 = [一-九]                 (i.e. [1-9])
D1 = U1 十 U1?
DO = U1? 十 U1?
CDN = 〇 U1 | D1
C1 = U1 百 CDN?
F = C1 | DO | U1 | 〇
F2 = 負? F
OP = 加 | 减 | 乘以 | 除以    (i.e., + | - | * | / )
EQ = F2 (OP F2)*

The DO and D1 productions are handled in the same method, diferentiated by a parameter. The other productions take one method each. The EQ is the grammar main symbol. Before starting the parse, it replaces 零 for 〇, so it need to handle just 〇 after that.

The 負 is for negative numbers. It can handle numbers from -999 to 999 (or 負九百九十九 to 九百九十九).

Further, to make it much more chinese, all the identifiers are in chinese. The only exception is the class name (using international characters there may cause problems) that is a chinese name transliterated to latin characters.

For the input I had to use a JOptionPane. Sorry for that, but I had trouble about encodings using other input methods. If you don't like this method of input, you can use the 解方程 method directly, it takes the input formula and produce the output equation (or error message).

import javax.swing.JOptionPane;

public class ZhongguoJisuanQi {

    private final String 文字输入;
    private int 源指数;

    public ZhongguoJisuanQi(String 文字输入) {
        this.文字输入 = 文字输入.replace("零", "〇");
        this.源指数 = 0;
    }

    public static void main(String... 参数) {
        String 方程 = 解方程(读取文本行());
        System.out.println(方程);
        JOptionPane.showMessageDialog(null, 方程, "答案是", JOptionPane.INFORMATION_MESSAGE);
    }

    private static String 读取文本行() {
        return JOptionPane.showInputDialog(null, "输入数学公式", "输入数学公式", JOptionPane.QUESTION_MESSAGE);
    }

    public static String 解方程(String 数学公式) {
        if (数学公式 == null) return "错误：给定的数学公式的格式不正确。";
        ZhongguoJisuanQi 计算器 = new ZhongguoJisuanQi(数学公式);
        Integer 结果 = 计算器.解析并解决了式();
        if (结果 == null) return "错误：给定的数学公式的格式不正确。";
        return 数学公式 + "等于" + 整数转换为文本(结果);
    }

    private boolean 找到字符(char 字符, int 指数) {
        return 指数 < 文字输入.length() && 文字输入.charAt(指数) == 字符;
    }

    private Integer 解析生产一() {
        int 数 = "一二三四五六七八九".indexOf(文字输入.charAt(源指数));
        if (数 == -1) return null;
        源指数++;
        return 数 + 1;
    }

    private Integer 解析生产十(boolean 必须带有前缀) {
        int 原始来源索引 = 源指数;
        Integer 第一个数字 = 解析生产一();
        if (第一个数字 == null && 必须带有前缀) return null;
        if (!找到字符('十', 源指数)) {
            源指数 = 原始来源索引;
            return null;
        }
        源指数++;
        Integer 第二个数字 = 解析生产一();
        return (第一个数字 == null ? 1 : 第一个数字) * 10 + (第二个数字 == null ? 0 : 第二个数字);
    }

    private Integer 解析生产或零十() {
        int 原始来源索引 = 源指数;
        if (找到字符('〇', 源指数)) {
            源指数++;
            Integer 数 = 解析生产一();
            if (数 == null) {
                源指数 = 原始来源索引;
                return null;
            }
            return 数;
        }
        return 解析生产十(true);
    }

    private Integer 解析生产百() {
        int 原始来源索引 = 源指数;
        Integer 第一个数字 = 解析生产一();
        if (第一个数字 == null) return null;
        if (!找到字符('百', 源指数)) {
            源指数 = 原始来源索引;
            return null;
        }
        源指数++;
        Integer 第二个数字 = 解析生产或零十();
        return 第一个数字 * 100 + (第二个数字 == null ? 0 : 第二个数字);
    }

    private Integer 解析生产数无符号() {
        Integer 数 = 解析生产百();
        if (数 != null) return 数;
        数 = 解析生产十(false);
        if (数 != null) return 数;
        数 = 解析生产一();
        if (数 != null) return 数;
        if (找到字符('〇', 源指数)) {
            源指数++;
            return 0;
        }
        return null;
    }

    private Integer 解析该生产号() {
        boolean 负 = false;
        if (找到字符('負', 源指数)) {
            源指数++;
            负 = true;
        }
        Integer 数 = 解析生产数无符号();
        return 数 == null ? null : 负 ? -数 : 数;
    }

    private String 解析算术运算符() {
        if (找到字符('加', 源指数)) { 源指数++; return "加"; }
        if (找到字符('减', 源指数)) { 源指数++; return "减"; }
        if (找到字符('乘', 源指数) && 找到字符('以', 源指数 + 1)) { 源指数 += 2; return "乘以"; }
        if (找到字符('除', 源指数) && 找到字符('以', 源指数 + 1)) { 源指数 += 2; return "除以"; }
        return null;
    }

    public Integer 解析并解决了式() {
        Integer 第一个数字 = 解析该生产号();
        while (true) {
            String 算术运算符 = 解析算术运算符();
            if (算术运算符 == null) return 源指数 == 文字输入.length() ? 第一个数字 : null;
            Integer 第二个数字 = 解析该生产号();
            if (第二个数字 == null) return null;
            switch (算术运算符) {
                case "加": 第一个数字 += 第二个数字; break;
                case "减": 第一个数字 -= 第二个数字; break;
                case "乘以": 第一个数字 *= 第二个数字; break;
                case "除以": 第一个数字 /= 第二个数字; break;
                default: throw new AssertionError();
            }
        }
    }

    private static String 整数转换为文本(int 参数) {
        if (参数 == 0) return "〇";
        StringBuilder 字符串生成器 = new StringBuilder(7);
        int 数 = 参数;
        if (数 < 0) {
            字符串生成器.append("負");
            数 = -数;
        }
        if (数 >= 1000) return null;
        if (数 >= 100) {
            字符串生成器.append("〇一二三四五六七八九".charAt(数 / 100)).append("百");
            数 %= 100;
            if (数 >= 1 && 数 <= 9) 字符串生成器.append("〇");
            if (数 >= 10 && 数 <= 19) 字符串生成器.append("一");
        }
        if (数 >= 20) 字符串生成器.append("〇一二三四五六七八九".charAt(数 / 10));
        if (数 >= 10) 字符串生成器.append("十");
        数 %= 10;
        字符串生成器.append("〇一二三四五六七八九".charAt(数));
        return 字符串生成器.toString();
    }
}

Compile with:

javac -encoding UTF8 ZhongguoJisuanQi.java

Run with:

java ZhongguoJisuanQi

Cheat sheet for identifiers names, accordingly to google translator:

(english original text) -> (chinese text) -> (english text back from chinese)
chinese calculator -> 中国计算器 (Zhōngguó jìsuàn qì) -> china calculator
text input -> 文字输入 -> text input
source index -> 源指数 -> source index
original source index -> 原始来源索引 -> original source index
Enter the mathematical formula -> 输入数学公式 -> Enter mathematical formulas
mathematical formula -> 数学公式 -> mathematical formulas
Error: The given mathematical formula is malformed. -> 错误：给定的数学公式的格式不正确。 -> Error: The given mathematical formula is not correct.
character -> 字符 -> character
read a text line -> 读取文本行 -> read a line of text
arguments -> 参数 -> parameter
equation -> 方程 -> equation
index -> 指数 -> index
find character at -> 找到字符 -> find characters
parse the production -> 解析生产 -> resolve the production
parse the production or zero -> 解析生产或零 -> resolve the production or zero
parse the production number -> 解析该生产号 -> resolve the production number
parse the production number without sign -> 解析生产数无符号 -> resolve production unsigned
parse and solve the formula -> 解析并解决了式 -> parse and resolve the formula
parse an arithmetic operator -> 解析算术运算符 -> parsing arithmetic operators
arithmetic operator -> 算术运算符 -> arithmetic operators
must be prefixed -> 必须带有前缀 -> must be prefixed with
calculator -> 计算器 -> calculators
solve the equation -> 解方程 -> solving equations
result -> 结果 -> result
number -> 数 -> number
minus -> 负 -> minus
first number -> 第一个数字 -> the first number
second number -> 第二个数字 -> second number
string builder -> 字符串生成器 -> string builder
convert integer to text -> 整数转换为文本 -> integer is converted to text
the answer is -> 答案是 -> the answer is


Find a number which generates all the integers mod q

Pyth, 16 15 bytes

f-1m.^T/tQdQPtQ

Test suite

If p is the input, we know that g^(p-1) = 1 mod p, so we just need to check that g^a != 1 mod p for any smaller a. But a must be a factor of p-1 for that to be possible, and any multiple of an a with that property will also have that property, so we only need to check that g^((p-1)/q) != 1 mod p for all prime factors q of p-1. So, we check all integers g in increasing order until we find one that works.

Explanation:

f-1m.^T/tQdQPtQ
f                  Return the first value T such that the following is truthy:
            PtQ    Take the prime factorization of the input - 1.
   m               Map those prime factors to
       /tQd        Take the input - 1 divided by the factor
    .^T    Q       Raise T to that exponent mod input,
                   performed as modular exponentiation, for performance.
 -1                Check that 1 is not found among the results.


vim, 38 bytes

:s/"/<C-d>/g
qqysW"Ypds"W@qq@qdk:%s/<C-d>/"/g

Try it online!

Requires the vim-surround plugin.

If the input does not contain " characters, this can be done in 19 bytes:

qqysW"Ypds"W@qq@qdk

Here, we record a recursive macro (qq ... @qq@q) that surrounds a word with quotation marks (ysW"), duplicates the line (Yp), deletes the quotation marks (ds"), and moves to the next word (W) before calling itself recursively. After it terminates, there are two extraneous lines, which are deleted with dk.

The full solution simply wraps this with :s/"/<C-d>/g at the beginning, which replaces existing " characters with an unprintable character, and :%s/<C-d>/"/g at the end, which undoes the replacement.


Count the number of Hamming distance sequences

Haskell, score 9

import Data.Bits
import Data.List
import qualified Data.IntSet as S

main = mapM_ (print . S.size . S.fromList . hd) [1..9]

hd :: Int -> [Int]
hd n = [foldl' (\s e->s*m+e) 0 [popCount $ xor p (shiftR t i .&. m)|i<-[(0::Int)..n-1]] | let m=2^n-1,p<-[(0::Int)..2^n-1],t<-[(0::Int)..2^(2*n-1)-1]]

Compile with -O3. It takes 6min35s on my 6 year old laptop hardware to run up to n=9, so maybe it's under 5min on the reference hardware.

> time ./113785
2
9
48
297
2040
15425
125232
1070553
9530752

real  6m35.763s
user  6m27.690s
sys   0m5.025s


Jelly, 3 bytes

R¡F

Try it online

Explanation

R¡F    Argument n

R      Yield range [1..n]
 ¡     Repeat n times
  F    Flatten the result


MATL, 7 bytes
UsGXzU=

Input is a string. Output is 1 for truthy, 0 for falsey.
Try it online! Or verify all test cases.
Explanation
U     % Implicit input. Convert to number(s): gives a vector of two numbers
s     % Sum of that vector
G     % Push input again
Xz    % Remove spaces
U     % Convert to number
=     % Equal? Implicit display


Charcoal, 17 16 bytes:

↶⁴-Ｆ⊖Ｎ«↶²/ι↶²\-ι

Try it online! Link is to verbose version of code.

↷²-¶Ｆ⊖Ｎ«/ι↶²\-ι↶

Try it online! Link is to verbose version of code.

Edit: Saved 1 byte thanks to @icrieverytim.


Pyth, 8 bytes

_J^Q3+QJ

Demonstration. Equivalent to the Python 2 code:

Q=input()
J=Q**3
print -J
print Q+J

So, the output has form (-n**3, n+n**3)

Some outputs:

-5 (125, -130)
-4 (64, -68)
-3 (27, -30)
-2 (8, -10)
-1 (1, -2)
 0 (0, 0)
 1 (-1, 2)
 2 (-8, 10)
 3 (-27, 30)
 4 (-64, 68)
 5 (-125, 130)

These are distinct because cubes are far enough spaced that adding n to n**3 is not enough to cross the gap to the next cube :n**3 < n+n**3 < (n+1)**3 for positive n, and symmetrically for negative n.


Shortest program to split a string at non-digits without RegExps

APL, 13 chars

(or 28 / 30 bytes, read below)

{⍵⊂⍨⍵∊∊⍕¨⍳10}

I see you've banned GolfScript from your question. I understand your sentiment, but I hope this community won't eventually ban APL, because it's a truly remarkable programming language with a long history, not to mention a lot of fun to code in. Maybe it could just be scored differently, if people feel it's competing unfairly. I'll post my thoughts on this matter to that thread you've linked.

On that same token, I've always added a footnote to my APL posts, claiming that APL could be scored as 1 char = 1 byte. My claim rests on the fact that a few (mostly commercial) APL implementations still support their own legacy single-byte encoding, with the APL symbols mapped to the upper 128 byte values. But maybe this is too much of a stretch, in which case you may want to score this entry as 28 bytes in UTF-16 or 30 bytes in UTF-8.

Explanation

{        ⍳10}  make an array of naturals from 1 to 10
       ⍕¨      convert each number into a string
      ∊        concatenate the strings into one (it doesn't matter that there are two 1s)
    ⍵∊         test which chars from the argument are contained in the digit string
 ⍵⊂⍨           use it to perform a partitioned enclose, which splits the string as needed

Examples

      {⍵⊂⍨⍵∊∊⍕¨⍳10} 'ab5c0x'
 5  0
      {⍵⊂⍨⍵∊∊⍕¨⍳10}  'z526ks4f.;8]\p'
 526  4  8

The default output format for an array of strings does not make it clear how many strings are there in the array, nor how many blanks. But a quick manipulation to add quotes should make it clear enough:

      {q,⍵,q←'"'}¨ {⍵⊂⍨⍵∊∊⍕¨⍳10} 'ab5c0x'
 "5"  "0"
      {q,⍵,q←'"'}¨ {⍵⊂⍨⍵∊∊⍕¨⍳10}  'z526ks4f.;8]\p'
 "526"  "4"  "8"


Find the last position in a matrix walking like a spiral

MATL, 24 bytes
This works in release 16.0.0 of the language, which predates the challenge.
2^Q6Y3GYLG2\?!P!}P]-=2#f

Output is 1-based, as in the examples.
A^2 and N are limited to 2^53 as per the language's default data type (double). In addition, since the whole matrix is being generated, memory will limit A to significantly lower values.
Try it online! (In the online version I have changed the order of G and 6Y3 so it works in the new 16.1.0 release)
Explanation
This uses MATL's builtin for generating an outward spiral. To make it inward, a subtraction and a reversal are needed. The direction of reversal depends on whether A is odd or even.
2^Q     % take input A implicitly. Compute A^2+1
6Y3GYL  % outward spiral of side length A
G2\     % is A odd?
?       % if so
  !P!   %   flip matrix horizontally
}       % else
  P     %   flip matrix vertically
]       % end if
-       % compute A^2+1 minus the matrix element-wise, so (1,1) contains 1
=       % take input N implicitly. Set matrix entry that contains that value to true
2#f     % row and column index of that true value


Ruby, 140 116 bytes

Takes code point as an array, and encodings are JIS, Shift_JIS, and EUC-JP, respectively.

Ruby supports converting between EUC-JP and SHIFT_JIS, so we math JIS encoding into EUC, perform the appropriate conversion, then math back the JIS encoding if that's the destination encoding.

-34 bytes by getting permission to take EUC input as EUC-JP.

->c,s,d{(c.map!{|e|e+=128};s="EUCJP")if s=~r=/^J/
c.pack('c*').encode(d[r]?"EUCJP":d,s).bytes.map{|e|e-=d[r]?128:0}}

Try it online!

Explanation

->c,s,d{                                            # Function that takes 3 parameters
        (                           )if s=~r=/^J/   # If s is JIS: (starts with J)
                                                    #  (also store this regex for later)
         c.map!{|e|e+=128};                         # Add 128 to each codepoint
                           s="EUCJP"                # Change s to EUC-JP locale
  c.pack('c*')                                      # Pack codepoints into bytestring
    .encode(                                        # Encode the bytestring as follows:
                                                    #  Destination encoding is:
      d[r]?"EUCJP":d,                               #   If d is JIS, use EUC-JP instead
      s                                             #  Source encoding
    )
    .bytes                                          # Convert to bytes
    .map{|e|e-=d[r]?128:0}                          # If d is JIS, subtract 128
}

Pure Math Version, 164 162 bytes

Takes code points separately, and the encodings are integers: 0=JIS, 1=SHIFT_JIS, 2=EUC.

-2 bytes from Jonathan Allen.

->a,b,s,d,e=160{k,t=[[a-32,b-32],[a*2-1+b/158-(2+a/222)*128,b-63-b/128-b/158*94],[a-e,b-e]][s]
[[k+32,t+32],[128+k/2+k%2+k/63*64,158+t+t/64-k%2*95],[k+e,t+e]][d]}

Try it online!


Python3, 293 242 bytes
This is my first CodeGolf. I am curious to see how others do this.
def f(s):
 for j in 4,3,2,1:
  try:return ''.join(['-^--^-^--^-^'[('A BC D EF G'.index(s[0])-('b'==s[1])+('#'in s)+i)%12]for i in(0,)+{'7':(4,7,10),'M7':(4,7,11),'m7':(3,7,10),'dim7':(3,6,9),'m7b5':(3,6,10),'-M7':(3,7,11)}[s[-j:]]])
  except:pass

Edit on 01.06.15
Thanks to the commenters, we found some tricks to shorten the code. I also discovered that changing to a function is slightly shorter. Old code: http://ideone.com/j5gmV2. P.S. I am just copying the code into triple quotes in Python and calling len to get the number of bytes.
Note:
I am assuming that Bb-M7 is Bb Major/Minor, i.e. that there is no delimiter between the note and the chord type, as described in the OP's second paragraph. Thus Bb-M7 gives ^^--. If Bb-M7 means Major, then what is Bb Major/Minor? Should it be Bb--M7?


05AB1E, 8 7 bytes
λ₂D(‚Ω+

-1 byte thanks to @ovs.
Prints the infinite sequence.
Try it online.
Explanation:

λ        # Create a recursive environment to output the infinite sequence,
         # implicitly starting at a(0)=1
         #  (push a(n-1) implicitly)
 ₂       #  Push a(n-2) (NOTE: all negative a(n) are 0, so a(-1)=0)
  D      #  Duplicate a(n-2)
   (     #  Negate the copy: -a(n-2)
    ‚    #  Pair them together: [a(n-2), -a(n-2)]
     Ω   #  Pop and push a random item
      +  #  And add it to the a(n-1)
         # (after which the infinite list is output implicitly)


JavaScript (ES6), 179 bytes

a=>a.map((r,y)=>r.map((v,x)=>t+=x*y/r[x+1]&&a[y+1]?[...(S='12221000')+S].map((n,i)=>p-(p=d=Math.sign(v-a[y+~-n][x+~-S[i+2&7]]))&&d?s&s!=-(s=d)?T=a:T++:0,T=s=p=0)|T>>1==4:0),t=0)|t

Try it online!

How?

We iterate on each cell \$v_{y,x}\$ of each row \$r_y\$ of the input matrix.

We first make sure that we're not located over an edge of the matrix with:

x * y / r[x + 1] && a[y + 1]

(neither \$x\$ or \$y\$ is \$0\$ and both \$v_{y,x+1}\$ and \$r_{y+1}\$ are defined)

We iterate twice on each neighbor cell and keep track of the number of valid segments in \$T\$. By doing this, each segment is guaranteed to be counted twice, except the first one which may be counted either twice or three times, depending on its starting point in relation to the starting point of the cycle. Either way, we have \$\lfloor{T/2}\rfloor=4\$ for order-2 saddle points, in which case we increment the counter \$t\$.

Example:

If the first segment is aligned with the starting point:

neighbor cells: AAAABCCD --> AAAABCCDAAAABCCD
                             ^   ^^ ^^   ^^ ^  --> T = 8

If it is not aligned:

neighbor cells: AABCCDAA --> AABCCDAAAABCCDAA
                             ^ ^^ ^^   ^^ ^^   --> T = 9

We iterate on neighbor cells by starting with the rightmost one and moving clockwise with:

[...(S = '12221000') + S].map((n, i) => a[x + ~-n][y + ~-S[i + 2 & 7]])

Try it online!

We store the sign of the difference between the current cell and its current neighbor in \$d\$. We keep track of the previous value of \$d\$ in \$p\$ and the previous sign (for non-zero values) in \$s\$.

The logic to update \$p\$, \$s\$ and \$T\$ reads as follows:

p - (p = d) && d ? s & s != -(s = d) ? T = a : T++ : 0

In plain English:

Ignore identical consecutive values.
Ignore segments with \$d=0\$.
Increment \$T\$ on valid sign transitions.
Whenever an invalid sign transition is detected, do T = a to force all upcoming operations on \$T\$ to either NaN or \$0\$, thus invalidating the final test.


Produce different behaviour in all versions of your language

Python

if 2 + 2 is 4:
    # Lies must be abolished

    try:
        fact = '2 + 2 = %r' % 5
        exec('True = False')
        exec('assert (2 + 2 == 5) is True')
    except ValueError:
        print('War is peace.')
    except NameError:
        print('Freedom is slavery.')
    except SyntaxError:
        print('Ignorance is strength.')

else:
    # All is good
    print('Big Brother is watching you.')

(Edit: Had to make a change because string formatting was actually introduced in... 0.9.9)

Tested on the following versions:

0.9.1: Prints Big Brother is watching you. because 2 + 2 is 5.*
1.5: Prints War is peace. since %r string formatting is unavailable, raising a ValueError,
2.1: Prints Freedom is slavery. since True is not defined, raising a NameError,
3.4: Prints Ignorance is strength. since True cannot be assigned to, raising a SyntaxError.

As a bonus, Python 2.3 to 2.7 gives no output, since the assertion passes.

Note that there are four spaces on both "blank" lines, and the file also needs to have a trailing newline.

* is checks object equality, and only from 1.0.0 onwards were small integers shared. You can still see the effect today by trying larger numbers, e.g. 999 + 1 is 1000 gives False.


Pyth, 30 29 26 24 23 bytes
sm.Asmmq1ssbCkds./MC./M

Try it online.
I'm sure this will get shorter. This is O(2mn), where m and n are the width and height of the array, but completes the last two test cases in 45 seconds on my laptop on battery (i5-5200U with limited performance).
Outputs the number of solutions.
Explanation
Five-dimensional arrays are really fun to work with.</sarcasm> You are not supposed to understand how this works even with the explanation.
                    ./M    Find all partitions of each row. Now we have a list of rows,
                           each containing the ways to split the row, each containing
                           the parts of the split (3D).
                   C       Transpose. Now we have a list of ways to split the columns,
                           each containing the rows, each containing the parts of the
                           row (3D).
                ./M        Find all partitions of each row list. Now we have a list of
                           ways to split the columns, each containing the ways to split
                           the rows, each containing the bunch of rows, each containing
                           the rows in the bunch, each containing the parts of the row
                           (6D).
               s           Combine the ways to split rows & columns into one array (5D).
 m            d            Do the following for each way to split rows & columns (4D):
     m       k                 Do the following for each bunch of rows (3D):
            C                      Transpose the array. We now have a list of column
                                   groups, each containing the row parts (3D).
      m    b                       Do the following for each column group (2D):
          s                            Combine the row parts in the column group. We now
                                       have the list of cells in this row/column group
                                       (1D).
         s                             Sum the cells.
       q1                              Check if the sum is one.
                                   We now have the list of booleans that tell if each
                                   row/column group is valid (1D).
                               We now have the 2D list of booleans that tell if each
                               row/column group in each bunch of rows is valid. (2D)
    s                          Combine the 2D list of booleans to 1D.
  .A                           Check if all values are truthy; if the split is valid.
                           We now have the validity of each split.
s                          Sum the list to get the number of valid solutions.


Mathematica, 5 bytes

Split

... there's a built-in for that.


JavaScript (ES6), 34 bytes

a=>a.reduce((l,[r,o])=>o>>l+l+r&1)

Accepts true/false but prefers 1/0 format.


Python 3 + scikit-image

Simply sets the color of the missing channel to the average of the other two.

import sys
from skimage import io, color

im = io.imread(sys.argv[1])
h, w, c = im.shape

removed_channel_options = {0, 1, 2}
for y in range(h):
    for x in range(w):
        if len(removed_channel_options) == 1: break
        removed_channel_options -= {i for i, c in enumerate(im[y][x]) if c > 0}
removed_channel = removed_channel_options.pop()

for y in range(h):
    for x in range(w):
        p = [float(c) / 255 for c in im[y][x][:3]]
        p = [sum(p)/2 if i == removed_channel else p[i]
             for i in range(3)]
        im[y][x] = [int(c*255) for c in p] + [255]*(c == 4)

io.imsave(sys.argv[2], im)

And the restored images:


J, 30 26 23 22 bytes
0{0{[:+/|.^:(<@%&{.~$)

Try it online!
Note: This solution works for any grid
J supports multi-dimensional rotation, which reduces the problem almost to a single summation.  To clarify what's happening, assume the board looks like this:
 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
25 26 27 28 29
30 31 32 33 34
35 36 37 38 39

Now we rotate the columns left and the rows up |. by 1 3, iteratively, 3 times:
┌──────────────┬──────────────┬──────────────┐
│ 0  1  2  3  4│ 8  9  5  6  7│11 12 13 14 10│
│ 5  6  7  8  9│13 14 10 11 12│16 17 18 19 15│
│10 11 12 13 14│18 19 15 16 17│21 22 23 24 20│
│15 16 17 18 19│23 24 20 21 22│26 27 28 29 25│
│20 21 22 23 24│28 29 25 26 27│31 32 33 34 30│
│25 26 27 28 29│33 34 30 31 32│36 37 38 39 35│
│30 31 32 33 34│38 39 35 36 37│ 1  2  3  4  0│
│35 36 37 38 39│ 3  4  0  1  2│ 6  7  8  9  5│
└──────────────┴──────────────┴──────────────┘

We are bringing the sled's "new position" to the top-left corner every time, rather than moving a pointer within a fixed grid and adjusting indexes with modular arithmetic.
Once we have every iteration like this, we need only "sum the planes" element-wise [:+/, and then our answer will the number in the top left corner of the resulting matrix 0{0{.
The only piece left is to determine how many times we need to iterate.  This amounts to dividing the first element of our "step" vector (the down part) into the height of the input matrix: %&{.~$.
old approach, 26 bytes
1#.]{~[:;/$@]|"1#\@]*($~#)

Try it online!


The negative order integer challenge, but it's Prime Time!

Processing, 161 bytes
int p(int n){for(int k=1;++k<=sqrt(n);)if(n%k<1)return 0;return 1;}void t(int n){for(int i=1,j;i<=n;i++){if(p(i)<1)continue;for(j=i;j>0;j--)print(p(j)<1?"":j);}}

One function does the primality checking, the other does the printing. Call it by t(7)
Ungolfed
The first function does the primality checking. It returns an int instead of a boolean since this way more bytes are saved. (int instead of boolean, 0 instead of false, 1 instead of true)
int Q103891p(int n){
  for(int k=1;++k<=sqrt(n);)
    if(n%k<1)return 0;
  return 1;
}

The second function prints out the string. It iterates through every number, if it is not a prime, skip to the next iteration. If it is a prime, it continues down to the printing inside another for-loop. Again, if the number is prime, then we print it, otherwise not.
void Q103891(int n){
  for(int i=1,j;i<=n;i++){
    if(p(i)<1)continue;
    for(j=i;j>0;j--)
      print(p(j)<1?"":j);
  }
}


Haskell, 35 33 bytes

a n|n<3=1|b<-a.(-)n=b(b 1)+b(b 2)

Defines a function a.


The program that will find the next prime number


Brainfuck, 48 bytes, Adnan
++++[>++++[>++++<-]<-]+++[>++++++++<-]>++[>+.<-]

Pretty straightforward, generating 64 and then 26. It might be a little red herring that
++++[>++++[>++++<-]<-]>>+

is a way to get 65, so you might try to do something like
++++[>++++[>++++<-]<-]>>+[>+++++>++<<-----]>>[<.+>-]

before noticing that it's a dead end.


Triangularity, 127 bytes

.......).......
......2)1......
...../)IL^.....
....f)rMD@_....
...)2)1/)IL^...
..f+`"'.'*"+E..
.DWReD)2s^)Its.
D+@sh+s+})10cJ.

Try it online!

Explanation

Removing the characters that make up for the padding, we get the following program:

)2)1/)IL^f)rMD@_)2)1/)IL^f+`"'.'*"+EDWReD)2s^)ItsD+@sh+s+})10cJ

... Which is quite length-ish, right? Let's break it down into pieces.

Generating the integers [0 … √len(input))

)2)1/)IL^f)r – Subprogram #1.
)            – Creates a new stack entry, equal to 0. This must precede any integer
               literal, because each character in '0123456789' isn't parsed on its
               own as a literal, but rather they are commands which multiply the ToS
               by 10 and add the value of their digit equivalent.
 2           – ToS * 10 + 2 = 2.           || STACK: [2]
  )1         – The literal 1.              || STACK: [2, 1]
    /        – Division.                   || STACK: [1 / 2] = [0.5]
     )I      – Get the input at index 0.   || STACK: [0.5, input]
       L     – Length.                     || STACK: [0.5, len(input)]
        ^    – Exponentiation.             || STACK: [len(input) ** 0.5]
         f   – Trim decimals.              || STACK: [int(len(input) ** 0.5)]
          )r – Create the list [0 .. ToS). || STACK: [[0 ... int(len(input) ** 0.5))]

Generating the dots

MD@_)2)1/)IL^f+`"'.'*"+E – Subprogram #2.
MD                       – For each integer in the range, run some code on a separate
                           stack, preinitialised to two copies of the argument.
  @_                     – Increment and negate the ToS.
    )2)1/)IL^f           – The square root of the length of the input, again.
              +          – Add the two.
               `         – And cast the integer given to a string.
                "'.'*"+  – Prepends the literal "'.'*" to the string representation.
                       E – Evaluate as a Python expression (basically string repetition).

Trimming the characters at the front

DWReD)2s^)It – Subprogram #3.
D            – Duplicate the result of the expression above.
 W           – Wrap the whole intermediate stack to an array.
  Re         – Reverse the stack and dump the contents separately onto the stack.
    D        – Duplicate the result.
     )2      – Push the literal 2.
       s^    – Swap and perform exponentiation.
         )It – Push the input and trim the characters before that index.

Trimming the characters at the end

sD+@sh+s+ – Subprogram #4.
s         – Swap the top two elements on the stack.
 D+       – Double. Push twice and add.
   @      – Increment.
    sh    – Swap the top two elements and trim the characters after that index.
      +   – Append the first set of dots.
       s+ – And prepend the second set of dots.

Ending the loop and pretty-printing

})10cJ – Subprogram #5.
}      – End the loop.
 )10   – Push the literal 10.
    c  – Convert from code-point to character (yields '\n').
     J – And join the result by newlines.


05AB1E, 22 bytes
v¯R¬yQiõˆ}2£yåiˆ}yˆ}¯g

Try it online or verify all test cases.
Explanation:

v           # Loop over the integers `y` of the (implicit) input-list:
 ¯R         #  Push the global_array, and reverse it
   ¬        #  Get the first item (without popping the reversed global_array itself)
    yQi  }  #  If it's equal to the integer `y`:
       õˆ   #   Add an empty string to the global_array
   2£       #  Then only leave the first 2 items of the reversed global_array
     yåi }  #  If the integer `y` is in these first 2 items:
        ˆ   #   Add the (implicit) input-list to the global_array
 yˆ         #  And push the integer `y` itself to the global_array
}¯g         # After the loop: push the global array, and then pop and push its length
            # (which is output implicitly as result)


JavaScript (ES6), 228 212 200 194 bytes

a=>w=>(B=1/0,(F=(r,p,s,b=a[p])=>p-a.length+1?1/b&&([...a[p]='RDUL'].map((c,d)=>d|p%w<w-1&&d-3|p%w&&F(r+c,P=p+[1,w,-w,-1][d],s+1+Math.abs(b-a[P]))),a[p]=b):R=s>B?R:s<B?(B=s,r):R+' '+r)('',0,0),R)

Input

One-dimensional array a and width w in currying syntax (a)(w)

Output

A space-separated list of solutions such as "DRDRRDR DRDRDRR"

Formatted and commented

a => w => (                            // given an array 'a' and a width 'w'
  B = 1 / 0,                           // B = best score so far, initialized as +Infinity
  (                                    //
    F = (                              // F = recursive function with:
      r,                               //   - r = current path (string)
      p,                               //   - p = current position in grid
      s,                               //   - s = current score
      b = a[p]                         //   - b = backup of current cell
    ) =>                               //
    p - a.length + 1 ?                 // if we haven't reached our destination:
      1 / b && (                       //   if the current cell is valid:
        [...a[p] = 'RDUL']             //     invalidate the current cell
        .map((c, d) =>                 //     for each possible direction:
          d | p % w < w - 1 &&         //       check right boundary
          d - 3 | p % w &&             //       check left boundary
          F(                           //       do a recursive call with:
            r + c,                     //         - new direction appended to the path
            P = p + [1, w, -w, -1][d], //         - updated position
            s + 1 + Math.abs(b - a[P]) //         - updated score
          )                            //
        ),                             //
        a[p] = b                       //     restore current cell value
      )                                //
    :                                  // else:
      R = s > B ?                      //   if the current score is worse than B:
        R                              //     keep the previous solution
      : s < B ?                        //   if the current score is better than B:
        (B = s, r)                     //     update best score / store path as new solution
      : R + ' ' + r                    //   if it's just as good: append path to solution
  )('', 0, 0),                         // initial call to F with r = '', p = 0, s = 0
  R                                    // return solution
)                                      //

Test cases

let f =

a=>w=>(B=1/0,(F=(r,p,s,b=a[p])=>p-a.length+1?1/b&&([...a[p]='RDUL'].map((c,d)=>d|p%w<w-1&&d-3|p%w&&F(r+c,P=p+[1,w,-w,-1][d],s+1+Math.abs(b-a[P]))),a[p]=b):R=s>B?R:s<B?(B=s,r):R+' '+r)('',0,0),R)

console.log(f([
  0, 3, 0, 0, 0,
  0, 2, 0, 2, 0,
  0, 0, 0, 3, 0
])(5));

console.log(f([
  3
])(1));

console.log(f([
  11, 11, 11,
  11, 11, 11,
  11, 11, 11
])(3));

console.log(f([
  7, 8, 1, -1, 0,
  4, 4, 6, -1, 7,
  3, 4, 4,  2, 8,
  2, 5, 2, -1, 2
])(5));


Mathematica 126 119 109 bytes
Mathematica can measure the elongation of a component in an image.  A full moon, being perfectly symmetric, has an elongation of 0, on a scale of 0 to 1.
A diminishing moon becomes increasingly elongated, to a maximum of roughly 0.8.
0.998 -0.788 x-0.578 x^2 was the empirically determined model (based on the large photos) for `predicting the fullness of the moon (by area), given its elongation.
I adjusted the model to 1- 0.788 x -0.578 x^2 so that with exactly zero elongation (full moon) the model will return 1 for the pixel scale factor.  It saves 4 bytes and still stays within the accuracy limits.
This model is used for any size images.  The moon image does not need to be centered. It also does not need to cover a fixed proportion of the photo.
Here are the data points (elongation, displayedMoonPixels/fullMoonPixels) for the large images and the parabolic model that was generated to fit the data. Linear models fit ok, but the quadratic model is dead on, within limits (see below).
Here the data are from the large pictures.  So is the model

Below, the data (the red points) are from the small pictures.  The model (the blue curve) is the one generated by the large pictures, the same one as displayed above.
The smallest crescent has 7.5% the area of a full moon.  (The smallest crescent among the large photos is 19% of a full moon.)  If the quadratic model had been based on the small photos the fit below would be better, only because it accommodated the small crescent.  A robust model, that would stand up under a wide range of conditions, including very small crescents, would be better made from a larger variety of pictures.
The closeness of fit shows that the model was not hard-coded for the given pictures. We can be fairly certain that the elongation of a moon is independent of the size of the photo, as one would expect.

f takes the image, i, as input and outputs the predicted size of the full moon, in pixels.  It works for off-center shots.
As the data below show, it all of the test cases except one.
The moons were arranged from full to most diminished.
i_~c~t_ := Max@ComponentMeasurements[i, t][[All, 2]];
f@i_ := i~c~"Count"/(1 - 0.788 x - 0.578 x^2 /. x -> i~c~"Elongation")

More than one image component may turn up in a photo.  Even a single pixel separated from the others will be considered a distinct component.  For this reason, it is necessary to search "all" components, to find the one that has the greater number of pixels.  (One of the small photos has more than one image component.)
Large pictures
Predictions of moon size made from the large photos were uniformly accurate.
{"predicted size of full moon", f[#] & /@ large}
{"accuracy", %[[2]]/16416}

{"predicted sizes of full moon", {16422., 16270.9, 16420.6, 16585.5, 16126.5, 16151.6}}
{"accuracy", {1.00037, 0.991161, 1.00028, 1.01033, 0.982367, 0.983891}}

Small pictures
Predictions of moon size made from the small photos were uniformly, with one great exception, the final picture.  I suspect the issue stems from the fact that the crescent is very narrow.
{"predicted sizes of full moon", f[#] & /@ small}
{"accuracy", %[[2]]/10241}

{"predicted sizes of full moon",{10247.3, 10161., 10265.6, 10391., 10058.9, 7045.91}}
{"accuracy", {1.00061, 0.992192, 1.0024, 1.01465, 0.982221, 0.68801}}


Use closures instead of functions

A closure:

|n|n+1

is shorter than a function:

fn f(n:i32)->i32{n+1}

Closures longer than one statement need braces but are still far shorter than a function.


Emotion, 17 bytes

Explanation
 Push literal 280
 Enter an iteration block over the first stack value and push the iteration element register at the begining of each loop.
 Push literal 1
 Push the sum of the second and first stack values.
 Push literal 1114112
 Swap the top two stack values.
 Push the first stack value to the power of the second stack value.
 Push the sum of the second and first stack values.
 Ends a control flow structure.

Try it online!


Python -> Perl -> Ruby, 48 characters
Adaption of my previous answer. Running
s='print q<puts %%q{s=%r;print s%%s}>';print s%s

with Python generates this Perl snippet
print q<puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}>

which generates the following Ruby code
puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}

which then prints the original Python snippet:
diff -s <(ruby <(perl <(python thirdorderquine.py))) thirdorderquine.py
Files /dev/fd/63 and thirdorderquine.py are identical


R, 102, 98

(kinda cheating: literal interpretation of the question)

cat(if(x<-as.Date(readline())-Sys.Date())c(abs(x),"days",c("from now","ago")[(x<0)+1])else"today")

Examples:

2013-12-08
today

2010-01-13
1425 days ago

2015-12-2
724 days from now


JavaScript (ES6),  116 112  107 bytes
Expects an array of entries in the following format: [[a,b,c,d], "XY"], where a to d are integers in [0..7], X is the number of correct digits and Y is the number of near-misses.
Returns 0 or 1.

f=(a,n)=>n>>12?0:!a.some(([a,x])=>!a.every(o=(d,i)=>o[x-=d^(v=n>>i*3&7)?a.includes(v):10,v]^=1)|x)|f(a,-~n)

Try it online!
Commented
f = (                     // f is a recursive function taking:
  a,                      //   a[] = input
  n                       //   n = 12-bit counter, initially undefined, to
) =>                      //       describe all possible codes
n >> 12 ?                 // if n = 4096:
  0                       //   stop the recursion
:                         // else:
  !a.some(([a, x]) =>     //   for each entry [a, x, y] in a[], with a[] =
                          //   guess, x = correct digits and near-misses:
    !a.every(o =          //     we use the object o to keep track of the
                          //     digits that were already extracted from n,
                          //     in order to discard invalid codes
      (d, i) =>           //     for each value d at position i in a[]:
      o[                  //
        x -=              //       update x:
          d ^ (           //         compare d with ...
            v =           //         ... v which is defined as ...
              n >> i * 3  //         ... the next 3-bit digit extracted from n
              & 7         //
          ) ?             //         if d is not equal to v, decrement x if ...
            a.includes(v) //           ... v appears elsewhere in a[]
          :               //         else:
            10,           //           subtract 10 from x
        v                 //       actual index in o to ...
      ] ^= 1              //       ... mark this digit as used; or yield 0
                          //       and exit every() if it was already used
    )                     //     end of every(); the iteration fails if it's
    | x                   //     falsy or x is not equal to 0
  )                       //   end of some()
  | f(a, -~n)             //   do a recursive call with n + 1


CJam, 32 bytes

l~1md@:X*mo'|*XSe]1$)NW$s,S*'-X*

Takes the precision first and the decimal second, separated by a space.

Run all test cases.

Explanation

l~   e# Read input and evaluate, pushing precision and decimal on the stack.
1md  e# Divmod 1, separating the decimal into integer and fractional part.
@:X  e# Pull up precision, store in X.
*mo  e# Multiply precision by fractional part and round.
'|*  e# Push that many vertical bars.
XSe] e# Pad with length X with spaces.
1$)  e# Copy integer part and increment.
N    e# Push linefeed.
W$   e# Copy integer part.
s,   e# Get number of digits as length of string representation.
S*   e# Push that many spaces, to indent the hyphens correctly.
'-X* e# Push X hyphens.


JavaScript (ES10),  250 ... 228  227 bytes
n=>(e=g=(a,[x]=a)=>+e?e=0:(x&=-x)?a.map((_,s)=>[b=1<<s,...s?[1,b+=~-b,b]:[]].map((m,d)=>d|x>>s&&g(a.flatMap(S=(v,y)=>(S|=y>s?v:(e|=(v^=M=x*m>>!d*s)&M,m^=1<<[s+~y,y+1,s-y,y][d],v))?v:[])))):n++)([...Array(n)].map(_=>2**n---1))|n

Try it online!
How?
The size-\$n\$ staircase is described with an array \$a[\:]\$ of \$n\$ bit masks, going from the longest to the shortest row.
For \$n=4\$, this gives:
# # # #  0b1111 = 15
. # # #  0b0111 = 7
. . # #  0b0011 = 3
. . . #  0b0001 = 1  --> a = [ 15, 7, 3, 1 ]

At each iteration, we remove all the leading empty rows in \$a[\:]\$ and look for the least significant non-zero bit \$x\$ in the first non-empty row. Note that \$x\$ is not set to the index of this bit, but to the corresponding power of \$2\$.
For each \$s\in[0\:..\:n-1]\$ we try to cover the main staircase with another staircase of size \$s+1\$ anchored to the non-zero bit, and whose rows are described with the bit mask \$m\$. If \$s=0\$, we only try the orientation \$d=0\$. Otherwise, we try \$d=0\$ to \$d=3\$.
The table below describes for each value of \$d\$:

the initial value of \$m\$
the index of the bit that must be inverted in \$m\$ to generate the next row
the shift applied to \$m\$

The non-zero bit to which the staircase is anchored is marked with an A. In all cases, \$m\$ is first multiplied by \$x\$ before being shifted. All examples are given with \$x=16\$ and \$s=2\$.
             x           d = 0
       . . . . . . . .
y = 0        A           init.  : 2 ** s
y = 1        # #         bit    : s + ~y  (i.e. s - y - 1)
y = 2        # # #       shift  : >> s

             x           d = 1
       . . . . . . . .
y = 0        A           init.  : 1
y = 1      # #           bit    : y + 1
y = 2    # # #           shift  : none

             x           d = 2
       . . . . . . . .
y = 0    # # A           init.  : 2 * (2 ** s) - 1
y = 1      # #           bit    : s - y
y = 2        #           shift  : none

             x           d = 3
       . . . . . . . .
y = 0    # # A           init.  : 2 * (2 ** s) - 1
y = 1    # #             bit    : y
y = 2    #               shift  : none

Note: Given that the bits to the right of the non-zero bit are all cleared by definition and given that we go from top to bottom, the anchor point of the covering staircase is unambiguously defined for each orientation.


Dyalog APL, 17 13 10 bytes

Prompts for an enclosed array containing (row, column) and then for a character. Gives INDEX ERROR on faulty input.
⊖⍞@⎕⊢5 5⍴0

Try it online!
⊖ flip upside-down the result of
⍞ inputted-character
@ replacing the content at position
⎕ evaluated-input (enclosed row, column)
⊢ of
5 5⍴ 5×5 array of
0 zeros


Python 3.9, 350 bytes
import sys
[s,p,x]=sys.stdin.read().split("\n\n")
p,x=[[l.split(',')for l in d.split("\n")]for d in[p,x]]
s={k:20 for k in s.split("\n")}
p={k:int(v)for k,v in p}
for t,i in x:b=s|p;b={k:b[k]for k in b if k[:4]==t[:4]};b=sorted(b,key=b.get);p[i]=p.get(i,0)+1;print((f"MATCH:{t[:4]},"if i in b[:5]else f"FULLWORD:{t},"if t==i else f"MISMATCH:{t},")+i)

Try it online! (Uses {**a,**b} instead of a|b to merge dictionaries)
The I/O formats are restrictive, but this still makes for a simple and fun challenge.
import sys
#s is the standard dictionary, p is the personal dictionary, and x is the input
#They are separated by a blank line
[s,p,x]=sys.stdin.read().split("\n\n")
#Turn both p and x into lists (separated by \n) of 2-element lists (separated by commas)
p,x=[[l.split(',')for l in d.split("\n")]for d in[p,x]]
#Split s on \n to get list of words, then map to 20, the default no. of occurrences
s={k:20 for k in s.split("\n")}
#Turn p into a dictionary, and make the values ints
p={k:int(v)for k,v in p}
#Iterate over each typed word t and intended word i in the input
for t,i in x:
  #Merge the personal and standard dictionaries and store in b
  b=s|p
  #Filter the words who start with the first 4 characters of t (typed word)
  b={k:b[k]for k in b if k[:4]==t[:4]}
  #b now contains words from the dictionary, sorted by number of occurrences
  b=sorted(b,key=b.get)
  #Increment number of occurrences of i in personal dictionary, or set to 1 if it doesn't exist yet
  p[i]=p.get(i,0)+1
  #Print the corresponding message
  print((f"MATCH:{t[:4]},"if i in b[:5]else f"FULLWORD:{t},"if t==i else f"MISMATCH:{t},")+i)


sh + coreutils, 58 bytes

tr '$%&)+0389:>CDGLMQVW]`bjpqu' 1u.#:BFO%+M/L2Aa,795d0@H=C

Try it online!

The modular square root is typically not unique; we have 2 or 4 choices for each character except .  We don’t need to translate , !, 4, l since each is already a square root of itself.  For the remaining characters, we choose images that don’t need to be escaped for the shell or tr.


Tri-interquine - Three programs that output each other in a loop

Python 3, 50 bytes

s='s=%r;print(s%%(s,%i*2%%7))';print(s%(s,1*2%7))

Try it online!

The last expression goes from 1*2%7 to 2*2%7 to 4*2%7 then back to 1*2%7.


How much time will I need to unlock my Android phone?

Rebmu: 197 175 168 167 characters

Generates combinations as a series of numbers (ex. 12369 is top-left to top-right to bottom-right), checks if combination is valid, and increments a counter if it is. This might take a while* to run. Returns the number of seconds needed to unlock the phone.

B[[2 13][4 17][6 39][8 79][5 19][5 28][5 37][5 46][a 0]]Fdz[Q1feCb[st[a]paStsC/1 Qa^Qa^e?NNfiAtsC/2 e?NNfiArvTSc/2]]rpJ987653088[StsADj1233iA^e?SuqSf[++K]]adKmp30dvK 5

Unmushed and commented:

; for each subarray c:
; the sequences c/2 and c/3 are invalid before the point c/1 is pressed
; a 0 - a is never in the sequence, therefore 0 is always invalid
b: [[2 13] [4 17] [6 39] [8 79] [5 19] [5 28] [5 37] [5 46] [a 0]]
; checks (most) conditions of validity
f: dz[
    ; set q to 1
    q: 1
    ; foreach array in b as c
    fe c b [
        ; set a to be portion of s before c/1
        st [a] pa s ts c/1
        ; q = q and (a does not contain c/2) and (a does not contain reverse of c/2)
        q: a^ q
           a^ e? nn fi a ts c/2
              e? nn fi a ts rv c/2
    ]
]
; repeat 98765308 times, with j = 1 to 98765308
; 987653088 = 987654321 (largest valid combination) - 1234 (smallest valid combination) + 1
rp j 987653088 [
    ; set s to j+1233 (smallest valid combination - 1) as a string
    s: ts ad j 1233
    ; if f returns trues and s does not contain duplicates, increment k
    i a^ e? s uq s
          f
     [++ k]
]
; print k (number of combinations) + 30 * (k/5) -> number of seconds needed
ad k mp 30 dv k 5

The program loops from 1 to (987654321-1233), checking 1233+loop counter (therefore checking 1234 to 987654321).

If the number 987653088 is replaced with, 9876-1233 or 8643, then the program will find the time taken for all 4-point combinations.

Output for 9876-1233=8643 (4-point combinations):

>> rebmu %combinations.rebmu
== 11344

Output for 98765-1233=97532 (4 and 5-point combinations):

>> rebmu %combinations.rebmu
== 61426

Output for 987654-1233=986421 (4,5,6-point combinations):

>> rebmu %combinations.rebmu
== 243532

*4/5-point took me about 8 seconds to run; 4-6 took about 77 seconds. It might take ~24 hours or longer depending on who runs this to calculate number of combinations for 4-9 point combinations.


Bash / Unix shell, 29

tr 0-9a-zA-Z+/ w-zA-Z+/0-9a-v

Input from STDIN, output on STDOUT.


Python 3, 118 \$\cdots\$ 85 80 bytes

Saved a whopping 29 bytes thanks to Surculose Sputum!!!
Saved 4 bytes thanks to Arnauld!!!
Saved 5 bytes thanks to xnor!!!

lambda a,b,c,d,e:399674e26**e/174539e29**a/162874e3**b/523253e37**c/189007e13**d

Try it online!


Be aware of the uppercase variants of common commands. This can trivially save one keystroke in a lot of contexts. For example:

A = $a
C = c$
D = d$
I = ^i
S = cc
X = dh
Y = yy

Another one is to use G instead of gg, but only if you use a count! For example, without a count, gg moves to the beginning, and G moves to the end. However, with a count, they both move to the line you specify, so 5G is shorter than but equivalent to 5gg
    .

Another one, is to use H in place of gg, but it's important to note that this only works if you can guarantee that any input will not take up more than the default number of rows (I believe this is 24, but it may vary).


JavaScript (ES7), 159 158 bytes

Edit: new version to comply with the updated rules regarding --
Saved 1 byte thanks to @Shaggy

Takes input in currying syntax (e)(r) where e is the array of equations and r is the array of expected results. Returns an array of characters.

e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))

Test cases

let f =

e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))

console.log(JSON.stringify(f
  ([ '123', '8423', '4+4', '4*7-10', '9/3', '42-9' ])
  ([ 3, 252, 8, 417, 3, -36 ])
));

console.log(JSON.stringify(f
  ([ '4/2', '3/0', '0/8+2', '95-5', '4+2' ])
  ([ 6, 3, 4, 90, 2 ])
));

console.log(JSON.stringify(f
  ([ '7+4', '5-15', '212-23' ])
  ([ 11, 46, -2121 ])
));

console.log(JSON.stringify(f
  ([ '4+8/2-9*1', '99/3-13', '1+2+3+4', '4-3-2-1' ])
  ([ -5, 20, 10, -6 ])
));

console.log(JSON.stringify(f
  ([ '18/18', '98-8', '55*88', '-5--15' ])
  ([ 1, 90, 4840, 10 ])
));

console.log(JSON.stringify(f
  ([ '9119', '5-3', '8*-9', '13116/3' ])
  ([ 18, 513, 152, -1 ])
));

Formatted and commented

e => r =>                                  // given e and r
  (l = [...2 ** 29 + '4+-*/'])             // generate l = [...'5368709124+-*/']
  .filter(x =>                             // for each character x of l
    l.some(y =>                            // for each character y of l
      eval("try {                          // we need to 'try', because we don't know
        eval(                              // whether the following expression is valid
          (S = (s = `[${e}]`).             // s = list of equations coerced to a string
            replace(/./g, c =>             // S =
              c == x ? y : c == y ? x : c  //   s with x and y exchanged
            )                              // end of replace()
          ).split`--`.join`+`              // replace '--' with '+'
        ) + '' == r                        // does the resulting list match r?
        & S != s                           // and was at least one character modified?
      } catch(e){}")                       // if we try, we oughta catch
    )                                      // end of some()
  )                                        // end of filter()


RUBY (449 436 chars)

I=*(0..8)
b=$*[0].split('').map{|v|v<'1'?I.map{|d|d+1}:[v.to_i]};f=b.map{|c|!c[1]}
[[z=I.map{|v|v%3+v/3*9},z.map{|v|v*3}],[x=I.map{|v|v*9},I],[I,x]
].map{|s,t|t.map{|i|d=[a=0]*10;s.map{|j|c=b[i+j];c.map{|v|d[v]+=1if !f[i+j]}
v,r=*c;s.map{|k|b[i+k].delete(v)if j!=k}if !r
s[(a+=1)..8].map{|k|s.map{|l|b[i+l]-=c if l!=k&&l!=j}if c.size==2&&c==b[i+k]}}
v=d.index 1;f[i+k=s.find{|j|b[i+j].index v}]=b[i+k]=[v]if v}}while f.index(!1)
p b*''

Example:

C:\golf>soduku2.rb 030001000006000050500000983080006302000050000903800060714000009020000800000400030
"832591674496387251571264983185746392267953418943812765714638529329175846658429137"

quick explanation:
Board b is an array of 81 arrays holding all the possible values for each cell.
The array on line three holds [offset,start_index] for each group (boxes,rows,columns).
Three tasks are performed while iterating through the groups.

The value of any cell of size 1 is removed from the rest of the group.
If any pair of cells contain the same 2 values, these values are removed from the rest of the group.
The count of each value is stored in d - if there is only 1 instance of a value, we set the containing cell to that value, and mark the cell fixed in f

Repeat until all cells are fixed.


GolfScript

Straightforward bubble sort implementation. Can probably be golfed down further. Try it online.

~x {{ document.write man [
putc( 'c', stdout ) ;
\b {{ return 1 echo ${10}
return
true;
Convert.ToDouble(o)
datagrid1.ItemsSource = dataTable1.DefaultView;
echo $a:u
cat > file {{ \b }} ~x
int* arr1[8];
}}
source ~/.bashrc
return
true;
] document.write
@echo off
IP=`curl ifconfig.me`
return
true;
~x return !0
return
true;
}} ~x
for {0..10..2}; do
  ..
done
set -x
\b
basename `pwd`
~x

Sources

https://stackoverflow.com/a/2513659 (https://stackoverflow.com/u/276101):

~x

https://stackoverflow.com/a/3773868  (https://stackoverflow.com/u/394167):

{{

https://stackoverflow.com/a/802894   (https://stackoverflow.com/u/8815):

document.write

https://stackoverflow.com/a/2188223 (https://stackoverflow.com/u/116908):

man [

https://stackoverflow.com/q/4563825 (https://stackoverflow.com/u/111307):

putc( 'c', stdout ) ;

https://stackoverflow.com/a/16876671 (https://stackoverflow.com/u/980550):

\b

https://stackoverflow.com/a/22604291 (https://stackoverflow.com/u/1622022):

return 1

https://stackoverflow.com/a/6146038 (https://stackoverflow.com/u/116908):

echo ${10}

https://stackoverflow.com/a/4054267 (https://stackoverflow.com/u/69083):

return
true;

https://stackoverflow.com/q/23657401 (https://stackoverflow.com/u/1171811):

Convert.ToDouble(o)

https://stackoverflow.com/q/6097907 (https://stackoverflow.com/u/517871):

datagrid1.ItemsSource = dataTable1.DefaultView;

https://stackoverflow.com/a/4813101 (https://stackoverflow.com/u/591720):

echo $a:u

https://stackoverflow.com/q/19114714 (https://stackoverflow.com/u/72436):

cat > file

https://stackoverflow.com/a/3773868 (https://stackoverflow.com/u/394167):

}}

https://stackoverflow.com/a/859676 (https://stackoverflow.com/u/87234):

int* arr1[8];

https://stackoverflow.com/a/2518150 (https://stackoverflow.com/u/245602):

source ~/.bashrc

https://stackoverflow.com/a/5750751 (https://stackoverflow.com/u/187690):

]

https://stackoverflow.com/q/8823643 (https://stackoverflow.com/u/1059446):

@echo off

https://stackoverflow.com/a/9764597 (https://stackoverflow.com/u/167925):

IP=`curl ifconfig.me`

https://stackoverflow.com/a/8255667 (https://stackoverflow.com/u/179669):

return !0

https://stackoverflow.com/a/966110 (https://stackoverflow.com/u/104162):

for {0..10..2}; do
  ..
done

https://stackoverflow.com/a/6930980 (https://stackoverflow.com/u/705676):

set -x

https://stackoverflow.com/a/4641636 (https://stackoverflow.com/u/333698):

basename `pwd`


Generate the python dictionary of phone keypresses for any letter

perl, 49 48 bytes

Using a different algorithm than my previous answer, we can lose another 12 bytes. The basic idea is that you usually just add the digit from the last letter's solution over again. We handle the other cases (detected by a short regex) by starting with a single instance of the last digit + 1.

{map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d||=2}a..z}

With output:

ski@anito:~/src$ perl -MData::Dumper  -e '$Data::Dumper::Sortkeys=1; $d=2;print Dumper {map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d}a..z}'
$VAR1 = {
      'a' => '2',
      'b' => '22',
      'c' => '222',
      'd' => '3',
      'e' => '33',
      'f' => '333',
      'g' => '4',
      'h' => '44',
      'i' => '444',
      'j' => '5',
      'k' => '55',
      'l' => '555',
      'm' => '6',
      'n' => '66',
      'o' => '666',
      'p' => '7',
      'q' => '77',
      'r' => '777',
      's' => '7777',
      't' => '8',
      'u' => '88',
      'v' => '888',
      'w' => '9',
      'x' => '99',
      'y' => '999',
      'z' => '9999'
};


Retina, 51 48 bytes

 Thanks to Martin Ender for saving 3 bytes

M`X((.{6}X){3}|(.{8}X){3}|(.{7}X){3}|XXX)
T`d`YX

Try it Online!

Takes input as a comma-separated list of rows


Python 3, 289 286 bytes

l,u=eval(input())
*_,w,h=map(max,zip(*l))
r=[*map(list,[' '*-~w]*-~h)]
R=range
for x,y,X,Y in l:
 for i in R(x,X+1):
  for j in R(y,Y+1):Q=i<X,y<j,x<i,j<Y;r[j][i]=u[sum(3**o*max(Q[o]*[j in(y,Y),i in(x,X)][o%2]*2,u.index(r[j][i])//3**o%3-Q[o])for o in R(4))]
for l in r:print(''.join(l))

Try it online!

Takes input as a list of 4-tuples: (x0, y0, x1, y1), along with the pipedrawing characters as follows: " ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"

Supports boxes of zero width or height (uses all box drawing chars).

Based on my answer to this question, but modified to alter existing boxes when drawing.

'Ungolfed':

u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"

#Create array of spaces:
l=eval(input())
w,h=list(map(max,zip(*l)))[2:]
r=[[' ']*w for _ in' '*h]

for x,y,X,Y in l:
 n,m=X-1,Y-1
 for i in range(x,X):
  for j in range(y,Y):
   A,B=j in(y,m),i in(x,n)
   P=(i<n*A,y<j*B,x<i*A,j<m*B)   # Pipe sides of the new box
   Q=(i<n,y<j,x<i,j<m)           # Pipe sides that are inside the new box, and should be thinned.
   # Get new pipe (sides of new box, on top of thinned pipes of existing boxes. (u.index... is existing pipe))
   l=sum(3**o*max(P[o]*2,(u.index(r[j][i])//3**o%3)-Q[o])for o in range(4))
   #Add to 'canvas'
   r[j][i]=u[l]

print('\n'.join(''.join(l)for l in r))


Python 3, 424 420 369 363 bytes
import time as t
r=range
x=len
d=list(t.strftime('%m%d%y'))
o=([[x,x+'(',x+')']for x in ['']+"+ - == * / **".split()])
n=[]
for l in o:
    n=l+n
o=n
for p in r(x(o)**(x(d)-1)):
    e=''
    for i in r(x(d)-1):
        e+=str(d[i])+o[(p//(x(o)**i))%x(o)]
    e+=str(d[-1])
    try:
        if eval(e)and e.find('=')!=-1:
            print(e.replace('==','=').replace('**','^'))
            break
    except:pass

Brute-forces all possible combinations of operations in the numbers and stops when it finds one.
EDIT: Saved 4 bytes thanks to @NoOneIsHere
EDIT 2: Saved 51(!) bytes thanks to @ValueInk


I'll give it a shot.   Here's some ugly Ruby that bases its ranking on how well each team scored compared to the opponent's average points against.  It weights scores based on the opponent's rank in the list, and iterates until it is stable.

class Team
  attr_accessor :wins,:loss,:for,:agn,:rank,:old_rank
  attr_reader :beat,:fell, :name
  def initialize nm
    @name = nm
    @wins=0
    @loss=0
    @for = 0
    @agn = 0
    @beat = []
    @fell  = []
  end
  def win pts,opp,opts
    @wins+=1
    @for+=pts
    @agn+=opts
    @beat << [opp,pts,opts]
  end
  def lose pts,opp,opts
    @loss+=1
    @for+=pts
    @agn+=opts
    @fell << [opp,pts,opts]
  end
  def avgPtsFor
    @for.to_f/(@wins+@loss)
  end
  def avgPtsAgn
    @agn.to_f/(@wins+@loss)
  end
  def score teams
    #most points for scoring above opponents average, scaled by opponent's rank.
    x = @beat.inject(0){|sum,game|opp = teams[game[0]]
      sum+(game[1]/opp.avgPtsAgn*(1-(opp.rank/teams.size)))/@beat.size
      }
    y = @fell.inject(0){|sum,game|opp = teams[game[0]];
      sum+(game[1]/opp.avgPtsAgn*(opp.rank/teams.size))/@fell.size
      }
    (x+y)*(@wins/@loss.to_f)++(@rank/teams.size)/8
  end

end

#read the file
teams = Hash.new
ARGF.each_line{|l|
  result = l.split(',')
  team = teams[result[0]]||Team.new(result[0])
  team.win(result[1].to_i,result[2],result[3].to_i)
  teams[result[0]]=team
  team = teams[result[2]]||Team.new(result[2])
  team.lose(result[3].to_i,result[0],result[1].to_i)
  teams[result[2]]=team
}
#initial ranking by w/l,pts for, pts against
rankings = teams.map{|n,t|t}.sort_by{|t|[t.wins.to_f/t.loss,t.for,t.agn]}
rankings.each_with_index{|a,i|a.rank = (i+1.0)}

#loop
stable = false
loops = 0
while !stable and loops < 1000 do
  stable = true
  n = rankings.size.to_f
  rankings = rankings.sort_by{|t|
  t.score(teams)
  }
  rankings = rankings.each_with_index{|t,i|
    t.old_rank = t.rank
    t.rank = (i+1.0)
    stable = false if (t.rank != t.old_rank)
  }
  loops+=1
end

i=0
puts rankings.reverse.map{|t|"#{i+=1}: "+t.name}

Here's the output:

1: Oklahoma St.
2: LSU
3: Boise St.
4: Houston
5: Stanford
6: Oregon
7: Alabama
8: Arkansas
9: Wisconsin
10: TCU
11: Michigan
12: Georgia
13: South Carolina
14: Arkansas St.
15: Southern Miss
16: Michigan St.
17: West Virginia
18: Baylor
19: USC
20: Georgia Tech
21: Clemson
22: Tulsa
23: BYU
24: Oklahoma
25: Kansas St.
26: Nebraska
27: Virginia Tech
28: Penn St.
29: Notre Dame
30: Cincinnati
31: Northern Illinois
32: LA Lafayette
33: San Diego St.
34: Toledo
35: Florida Intl.
36: Texas A&M
37: Louisiana Tech
38: Ohio
39: Florida St.
40: North Carolina
41: Nevada
42: Iowa
43: Temple
44: Washington
45: West. Kentucky
46: Rutgers
47: Air Force
48: Auburn
49: Wyoming
50: California
51: Texas
52: Ohio St.
53: W. Michigan
54: Virginia
55: Utah St.
56: Florida
57: Missouri
58: Northwestern
59: SMU
60: Vanderbilt
61: Mississippi St.
62: Pittsburgh
63: Ball St.
64: Louisville
65: Purdue
66: East Carolina
67: UCLA
68: Wake Forest
69: Marshall
70: North Texas
71: N.C. State
72: Arizona St.
73: Utah
74: South Florida
75: Hawaii
76: San Jose St.
77: Texas Tech
78: Illinois
79: Kent St.
80: UTEP
81: UCF
82: Tennessee
83: East. Michigan
84: Connecticut
85: Navy
86: Duke
87: Rice
88: New Mexico St.
89: LA Monroe
90: Washington St.
91: Bowling Green
92: Kentucky
93: Syracuse
94: Arizona
95: Fresno St.
96: Troy
97: Oregon St.
98: Army
99: Colorado
100: Iowa St.
101: UNLV
102: UAB
103: Buffalo
104: Middle Tenn. St.
105: Minnesota
106: Boston Coll.
107: Cent. Michigan
108: Colorado St.
109: Mississippi
110: Tulane
111: Florida Atlantic
112: Memphis
113: Idaho
114: Kansas
115: New Mexico
116: Indiana
117: Maryland
118: Akron


Mathematica, 165 bytes

ContourPlot[Cos@Tr[Boole[Norm[{x,y}-#2]<#]Pi&@@@#4],{x,0,#},{y,0,#2},PlotPoints->5!,AspectRatio->Automatic,Frame->False,ContourShading->RGBColor@@@#3,Contours->{0}]&

Pure function taking four arguments: the width, the height (both integers), an ordered pair of triples of numbers between 0 and 1 (representing the two RGB colors), and a list of items of the form {r, {x, y}} to record the radii and centers of the circles. For example, the first example in the OP would be called with the arguments [300, 200, {{1, 0.784, 0}, {0.5, 0, 1}}, {{25, {50, 80}}, {40, {80, 120}}, {300, {-100, 6}}, {17, {253, 162}}}]. The positive y-axis points upwards in Mathematica.

Norm[{x,y}-#2]<# detects whether a point is inside a given circle; Boole[...]Pi converts that True or False to π or 0. After computing those πs/0s over all the input circles, Tr adds them up and Cos converts even multiples of π to 1, odd multiples of π to –1. ContourPlot[...,Contours->{0}] then colors the appropriate region of the plane in two colors depending on whether the value is greater or less than 0. AspectRatio->Automatic makes circles look like circles; PlotPoints->5! gives a decent accuracy (boost it to 9! if you really want an amazing picture, far in the future!); Frame->False gets rid of the axes; and ContourShading->RGBColor@@@#3 uses the input colors for the contours.

Sample output, with the first pair of colors (since they're nice) but the last set of circles:


Mathematica, 246 bytes
ImageAssemble@(n=Nest)[k=RandomInteger;q=Reverse;({t,r}=1~k~2;q[o=n[q/@#&,#,r]&@*(n[#&,#,t]&)])[o@#/.{a___,b:_~RepeatedNull~k[Position[o@#,i][[1,2]]-1],i,c___}:>{a,i,b,c}]&,MapAt[(i=#~ImageAdd~1)&,#~ImagePartition~Scaled[1/#2],{1,#2}~k~2],#3]&

Anonymous function. Contains U+F3C7, corresponding to Mathematica's Transpose operator. This function takes an Image object and returns an Image object.
Sample Animation, with n=16 and r=100
After 5000 iterations:
(click image for larger version)
Explanation
Initialization
n=Nest

Store the Nest function (repeating operation) in n.
k=RandomInteger;q=Reverse;

Store the RandomInteger function in k, and Reverse function in q.
Splitting the image
#~ImagePartition~Scaled[1/#2]

Partition the input image into (second input)^2 tiles.
{1,#2}~k~2

Generate two RandomIntegers between 1 and the second input. This selects a random tile.
MapAt[(i=#~ImageAdd~1)&, ..., {1,#2}~k~2]

Make that tile white. Store it in i.
Moving Tiles
{t,r}=1~k~2

Generate two random integers from 0 to 1, and store them in t and r, respectively. This randomly selects direction.
o=n[q/@#&,#,r]&@*(n[#&,#,t]&)

Define function o: the composition of

a function transposing the input t times.
a function reversing each row r times.

o@#
Apply o to the input.
Position[o@#,i][[1,2]]

Find the column of i (white image).
k[ ... -1]

Subtract one and find a random integer between 0 and that number. This randomly chooses how many tiles to move.
o@#/.{a___,b:_~RepeatedNull~ ... ,i,c___}:>{a,i,b,c}

When the said number of tiles occur before an i (white image), switch their places.
(... q[o= ... ])[ ... ]

Reverse the o function and apply that to the result of above operation. This un-reverses and un-transposes the image.
Looping and Image Assembly
(n=Nest)[ ... ,#3]

Repeat the above process (third input) times.
ImageAssemble@

Put the images together.


Python 2, 50 bytes

lambda n:`n`==`map('01xxxx9x86'.find,`n`)`[-2::-3]

The method '01xxxx9x86'.find takes a digit character to it's upside-down number, with any unflippable digit giving -1. This function is mapped to the reversed number string, producing a list of digits.
This is converted to a string with the [1::3] trick, except it's reversed instead by doing [-2::-3] (thanks to Dennis for this, saving 4 bytes),  and compared to the original number string. Any -1's from unflippable digits will misalign the conversion, making it fail.

56 bytes:
lambda n:`n`[::-1]==`n`.translate('01xxxx9x86______'*16)

Checks if the number string reversed is the same as it with the upside-down replacements. Digits that can't be flipped are replaced with 'x' to always give the wrong answer.
The replacement is done with translate on a string of 256 chars, replacing the corresponding ASCII values. Only the 10 values 48 to 57 matter, but I padded to length 16 to make the total length be 256. I wonder if there's a shorter way.
Some other approaches (lengths 59, 60, 60):
lambda n:set(zip(`n`,`n`[::-1]))<=set(zip('01896','01869'))
r=lambda s:set(zip(s,s[::-1]));lambda n:r(`n`)<=r('9018106')
lambda n:all(a+b in'001188969'for a,b in zip(`n`,`n`[::-1]))


Jelly, 42 38 37 bytes
="⁵Ḣ€Ṗ1;ṙ@"µɼ⁶ṭØAiịɗƒµ®Ṛi@ịØAɗƒ
ḷ⁹©Ç€

Try it online!
Verify each test case
This is extremely liberal with the input format. It takes input in the following way:

The three rotors (the strings, not the numbers) as the first command line argument, each rotated so that the starting points are the first characters
The message as the second command line argument
The 3 specific notches as the third command line argument
The reflector as the fourth command line argument

In the above TIO link, the Footer converts a triple of numbers (the rotors) into the rotor strings, then rotates them to the correct order, so that you don't have to do it yourself.
However, for 45 bytes we can have a program which takes input in the following way:

The message, on STDIN
The three rotors (as the strings) as the first command line argument
The 3 specific notches as the second command line argument
The reflector as the third command line argument
The three starting points for the rotors as the fourth command line argument

Again, the Footer converts the rotors from integers to the corresponding strings.
Finally, if we want to go all the way and just accept 3 inputs (the rotors, as integers, the starting positions and the message (thus have -95 to our score), we get a score of 44

How it works
As they all use the same underlying algorithm, I'll just explain the 38 byte version in full, and I'll cover how the other two versions adapt the inputs to match the shortest version. For this explanation: M is the message, R are the three rotor strings, N are the notches, F is the reflector and C is the value in the register (initially 0).
ḷ⁹©Ç€ - Main link. Takes M on the left and R on the right
 ⁹    - Yield R
  ©   - And copy it into the register. C = R
ḷ     - Discard R and yield M
    € - Over each character in M:
   Ç  -   Call the helper link
        Implicitly output the final result

="⁵Ḣ€Ṗ1;ṙ@"µɼ⁶ṭØAiịɗƒµ®Ṛi@ịØAɗƒ - Helper link. Takes a character X on the left

="⁵Ḣ€Ṗ1;ṙ@"µɼ                   - Rotate the rotors
            ɼ                   - Yield C, run the following on it, save the result to C:
           µ                    -   Initially, C = R, the list of rotors
  ⁵                             -   Yield the notches, N
 "                              -   Pair each notch with each rotor, then:
=                               -     Vectorised equality
   Ḣ€                           -   Take the head of each
                                      This yields a triple of bits [a, b, c]
                                      which indicate which rotor hits its notch
     Ṗ                          -   Remove c as rotor 3 has no affect
      1;                        -   Prepend 1 as rotor 1 always moves; [1, a, b]
          "                     -   Pair 1 with rotor 1, a with rotor 2 and b with rotor 3,
                                        then for each pair:
        ṙ@                      -     Rotate the rotor if the bit is 1

             ⁶ṭØAiịɗƒ           - Send the character through the rotors
             ⁶                  - Yield the reflector F
              ṭ                 - Tack it to the end of the rotors, call this C'
                   ɗ            - Group the previous 3 links into a dyad f(U, L):
                                   where U is a character and L a list of characters
               ØA               -   "ABC...XYZ"
                 i              -   Index of U in the alphabet
                  ị             -   Index into L
                    ƒ           - Starting with X, reduce C' by the dyad f(U, L)
                                  As C is a triple of lists of characters, this returns
                                  A = f(f(f(f(X, C[1]), C[2]), C[3]), F), a single character

                     µ®Ṛi@ịØAɗƒ - Send A back through the rotors
                     µ          - Begin a new link with A as the argument
                             ɗ  - Group the previous 3 links into a dyad g(U, L)
                        i@      -   Index of U in L, i
                          ịØA   -   i'th letter of the alphabet
                      ®         - Yield C
                       Ṛ        - Reverse C
                              ƒ - Starting with A, reduce rev(C) by the dyad g(U, L)
                                      This yields g(g(g(A, C[3]), C[2]), C[1]),
                                      which is our intended result

How the other 2 work
The 45 byte version
Taking a look at the code, we notice that the only thing that's changed is that the last line is now
ṙ"©⁶O_65¤ṛɠÇ€

The difference between this version and the 37 byte version is how the rotors are taken as input:

The three rotors (the strings, not the numbers) as the first command line argument, each rotated so that the starting points are the first characters

The three rotors (as the strings) as the first command line argument

The new bits here just rotate the rotors for us and take M from STDIN:
ṙ"©⁶O_65¤ṛɠÇ€ - Main link. Takes R on the left
        ¤     - Create a nilad:
   ⁶          -   The 3 starting points of the rotors
    O         -   Converted to char points
     _65      -   Minus 65
 "            - Zip with each rotor:
ṙ             -   Rotate the rotor that many steps
  ©           - Save this to the register
          ɠ   - Read M from STDIN
         ṛ    - Discard the rotors and yield M
           Ç€ - Call the helper link on each character of M

The 139 byte version
Let's take a look at the full code:
="³ị“QEVJZ”¤Ḣ€Ṗ1;ṙ@"µɼ“¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤ṭØAiịɗƒµ®Ṛi@ịØAɗƒ
ị“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’œ?ØAṙ"©⁴O_65¤ṛɠÇ€

Try it online!
This is very similar to our 45 byte version. In fact, here's what's different in the first lines, with everything that is unchanged, replaced with .
..³ị“QEVJZ”¤..........“¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤.................

Furthermore, you'll note that the end of the first line is ṙ"©⁴O_65¤ṛɠÇ€, which is the first line of the 45 byte version, meaning that there are really only three changes. In this case, those changes are because of the changes to the input system. Here's the first 2:

⁴ \$\to\$ ³ị“QEVJZ”¤. Rather than take the notches as input, we use the rotor list (³) to ịndex into the string of notches “QEVJZ”. The ¤ is simply a precedence marker, telling the program to treat this as a constant

⁵ \$\to\$ “¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤. Again, this is changing an input into program data, the reflector in this case. ¤ Once again acts as a precedence marker. However, we have 3 new commands here:

œ? is a dyad which takes 2 arguments - on the left, an integer x, and on the right a string, s - and returns the x'th permutation of s
ØA we've already encountered, and is the uppercase alphabet. In this context, it acts as the right argument to œ?
“¡ƝḋœṚṗḶw⁸Aß`’ is the compressed integer \$383316524290458478707255597\$, which is the left argument to œ?

Together, this returns the \$383316524290458478707255597\$th permutation of the uppercase alphabet, or the string "YRUHQSLDPXNGOKMIEBFZCWVJAT"

The final change is the entire start of the last line:
ị“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’œ?ØA

Here, we have a list of massive compressed numbers:
“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’

Each “ marks the beginning of a new compressed number, and the entire list is
[67892310845892591685803413, 5023890671354916271018308, 16834429128340685633834184, 72949485053238139997554738, 340670280577577536609579431]

We then take the three integers which correspond to the three rotor inputs with ị, and then use œ?ØA to generate the alphabet permutations we want for each rotor. Finally, these permutations are fed into the rest of the program, already covered above.


Brainfuck, 5 + 540 = 545 bytes

5 bytes of code, 540 from output of given test file (assuming  got the count right from my paste of that code).

,[.,]

Assuming EOF is 0.


Python, 217 202 176
import sys
A=sys.argv[1:]
t=A>["G"]
C=[[int(A[i]),i]for i in range(1,len(A))]
while C:
 c=min(C);d=1.5
 if t:d=c[0]%5<2;print["P",c[1]][d],
 c[0]-=2*d;t^=1
 if[0]>c:C.remove(c)

Reads input from the command line.
Strategy:

If the remaining capacity in the container with the least remaining capacity is congruent 0 or 1 modulo 5, pour 2 litres (it either overflows, or our friend pours 3 more litres into the same container, bringing us back to the same point.)
Otherwise, no move improves our position, so do nothing (note that this isn't necessarily the shortest optimal strategy.)


R, 77 74 73 bytes
-3 bytes thanks to Giuseppe and -1 byte thanks to MarcMush.

f=function(n,d=nchar(n),k=1:n)`if`(d<2,n,1+f(match(n,c(k^d,k*d,k+d))%%n))

Try it online!
Recursive function; avoids floating point issues. The vector k contains all integers from 1 to n. Concatenate k^d, k*d and k+d (yielding a vector of length 3n) and find the position p of the first occurrence of n. Then \$f(n)=1+f(p \mod n)\$. The recursion is initialized by noting that \$f(n)=n\$ for all 1-digit integers (hence the conditioning on d<2).
Works for all the test cases (although 21550 could require you to increase the stack limit on some machines).


Golfing: How many unit-length squares in a list of 2d coordinates?

APL(Dyalog), 30

+/{(2-/⍵)≡2-/,⍳2 2}¨,∘.,⍨⍣2⊂¨⎕

Well, in most cases, readability and char count is proportional.

Sample Output

⎕:
      (0 0)(0 1)(1 0)(1 1)(0 2)(1 2)(2 2)(2 1)(2 0)
4

Explaination

So, 4 points forms a unit square if and only if their relative positions are (1,1),(1,2),(2,1),(2,2)
{(2-/⍵)≡2-/,⍳2 2} is a function that return 1 or 0 (true/false) given a set of 4 points as input based on whether they are in relative positions and sorted in the order (1,1),(1,2),(2,1),(2,2):
⍳2 2 Generate a 2×2 matrix of the points (1,1),(1,2),(2,1),(2,2)
, Unravel that matrix to an array of points
2-/ Pair-wise subtraction reduce: (1,1) - (1,2) ; (1,2) - (2,1) ; (2,1) - (2,2), which gives the array [(0,-1),(-1,1),(0,-1)]
(2-/⍵) Pair-wise subtraction reduce on the input
≡ Check if the two arrays equal

The main program
⎕ Takes input and evals it. Things like (0 0)(0 1)(1 0)(1 1) evaluates to a nested array (Equivalent of [[0,0],[0,1],[1,0],[1,1]] in JS)
⊂¨ For every point (¨), enclose it in a scalar (⊂) ([[[0,0]],[[0,1]],[[1,0]],[[1,1]]])
∘.,⍨⍣2 For every pair of elements of the array, concatenate them to form a new array. ([ [[0,0],[0,0]],[[0,0],[0,1]]...) Repeat once. This gives all sets of 4 points that can be made using the given points. In some of these sets, the same point would be used multiple times, but these would not be unit squares so no need to waste keystrokes to remove them. (, concatenates 2 arrays, ∘. means "do that for every pair of elements", ⍨ means "use right operand as both left and right operands", and ⍣2 means "do this twice")
, As the previous operation would give a 4-dimensional array (note that nested arrays and multi-dimensional arrays are different things in APL), we have to unravel it to get an array of sets (of 4 points).
¨ For each of the sets,
{...} execute the aforementioned function. The result would be an array of 0s and 1s indicating whether the set is a unit square. Note that because the function also check ordering, duplicates are eliminated.
+/ Finally, sum resulting array to get the count.


Filter an array so that duplicate items are removed

1-byte built-ins
05AB1E (legacy)
Ù

Try it online!
Alternatively:
ê

Try it online!
APL (Dyalog Unicode)
∪

Try it online!
Jelly
Q

Try it online!
W
U

Stax
u

MATL
u

Try it online!
MathGolf
▀

Try it online!
Seriously/Actually
╔

Japt
â

Try it online!
Pyth
{

Try it online!
Husk
u

Try it online!
Pyke
}

Try it online!
Canvas
Ｄ

Try it online!


JavaScript (ES6), 268
An anonymous function

i=>[...i].every(c=>(c=parseInt(c,36))>9?o+="AlphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu".match(/[A-Z][^A-Z]+/g)[c-10]+' ':0,o='',!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~")?o:'Error'


Instead of ((a*10+c)*10)+d we can use ((a*2+c)*2)+d to distinguish the colors.

 r=((a*2+c)*2)+d
 if r==0:e="black"
 elif r==4:e="red"
 elif r==1:e="blue"
 elif r==2:e="green"
 elif r==5:e="magenta"
 elif r==3:e="cyan"
 elif r==6:e="yellow"
 else:e="white"

Ah, but now we're just distinguishing between values from 0 to 7, so we can index into an array instead!

 r=a*4+c*2+d
 e=["black","blue","green","cyan","red","magenta","yellow","white"][r]
 # or even shorter:
 e="black blue green cyan red magenta yellow white".split()[r]

Combining with Uriel's changes we get down to 136 bytes (164 bytes saved).

exec'x,r,g,b=map(int,raw_input().split());print"black blue green cyan red magenta yellow white".split()[x/r%2*4+x/g%2*2+x/b%2];'*input()

Try it online!


I spent a long plane ride coding this one up.  I've written a pseudo befunge compiler which runs the befunge program, extracts basic blocks, and lays them out in a compact representation.

Link to the program.

When run on this 99 bottles program:

92+9*                           :. v  <
>v"bottles of beer on the wall"+910<
,:
^_ $                             :.v
            >v"bottles of beer"+910<
            ,:
            ^_ $                     v
>v"Take one down, pass it around"+910<
,:
^_ $                           1-v
                                 :
        >v"bottles of beer"+910.:_          v
        ,:
        ^_ $                          ^
                    >v" no more beer..."+910<
                    ,:
                    ^_ $$ @

It generates the following output:

92+9*:.019+"llaw eht no "v
v  _v# :"bottles of beer"<
>    ,:    v
^  _v#     <
    >$:.019+"reeb f"v
 v _  v#:"bottles o"<
 >     ,:  v
 ^ _  v#   <
      >$019+"dnuo"v
     v"pass it ar"<
     >" ,nwod eno"v
 v _    v#:"Take "<
 >       ,:v
 ^ _    v# <
        >$1-:v
 v _      v# <
 >         :.019+"reeb "v
  v_  v#   :"bottles of"<
  >        ,v
  ^_  v#   :<
      >    $019+"llaw"v
           v" on the "<
           >"reeb fo "v
^  _^#      :"bottles"<
          >019+"...r"v
v  _v#:" no more bee"<
>    ,:    v
^  _v#     <
    >$$@

It actually isn't much more compact than the source, but it will probably do better on larger/sparser programs.

The program is laid out with a routing area on the left and basic block contents on the right.  A basic block is usually laid out in an even number of rows so the entrance and exit adjoin the routing area.  At the end of each basic block, the gadget #^_v and variants, laid out right-to-left, do the conditional branch and route flow into columns.  At the start of each basic block, these columns are routed into the rows for the destination basic block.

In addition, if the output is short it just generates the output explicitly, like this:

"output">:#,_@

I haven't done anything to optimize the basic blocks themselves, just the layout.  Todo.

So where are the tests?


SmileBASIC, 73 71 67 bytes
?"Christmas";
@L?" Eve"*(D!=P);
P=D
DTREAD OUT,M,D
IF M/D-.48GOTO@L

The program prints "Christmas", then prints " Eve" every time a day passes, until it is December 25th. (12/25 = 0.48)
May take up to a year to run.


JavaScript (ES6), 102 94 93 90 bytes

console.log('Hello',(a=`
<<<<<<<
Mine
=======
Theirs
>>>>>>>
Conflict`.split`
`)[6]||a[1])

If the conflict has been resolved, then there is no sixth line, so it prints the now first line instead. Edit: Saved 3 bytes thanks to @nderscore.


Befunge, 181 168 bytes
>>4&5pp20555>>03>16p\::5g8%6p5v
 ^p5.:g605$_ #!<^_|#:-1g61+%8g<
543217539511|:_^#->#g0<>8+00p3+5%09638527419876
v<304p$_v#:->#$$:2`#3_:^
>#\3#13#<111v124236478689189378

Positions on the board are numbered 1 to 9. By default you get the first move, but if you want to allow the computer to go first, you can just enter 0 for your first move. When you've made a move, the computer will respond with a number indicating their move.
There are no checks to make sure you don't enter a valid move, and there also no checks to see if anyone has won or lost. Once their are no more moves to be made, the program just goes into an infinite loop.
It's a bit difficult to test this online, since there are no online interpreters with interactive input. However, if you know what moves you're going to make in advance (which assumes you know how the computer is going to respond), you can kind of test on TIO with those moves preprogrammed.
User plays first: Try it online!
Computer plays first: Try it online!
To makes it easier to see what's going on, I've also got a version that outputs the board between moves.
User plays first: Try it online!
Computer plays first: Try it online!
Note that you'll have to wait for TIO to timeout before you can see the results.
Explanation
The board is stored in the Befunge memory area as a flat array of 9 values, indexed from 1 to 9. This lets us use the zero offset as a special case "no move" when we want to let the computer play first. Player moves are stored as 4, and computer moves as 5. To start with all positions are initialised to 32 (the Befunge memory default), so whenever we access the board we mod with 8, so we'll get back either 0, 4 or 5.
Given that arrangement, if we sum the values of any three positions on the board, we know that the computer is one move away from winning if the total is 10, the player is one move away from winning if the total is 8, and the positions are shared between computer and player (but still one position is free) if the total is 9.
Our entire strategy is based around this concept. We have a routine that takes a list of triples indicating sets of three positions on the board, we calculate the sum of those positions, and if the sum equals a certain total, the computer moves to whichever of the positions in the set is free.
The main list of triples that we test are the winning combinations (1/2/3, 1/5/9, 1/4/7, etc.). We first look for a total of 10 (the computer is about to win), and then a total of 8 (the player is about to win and we need to block that move). Less obviously, we also check for a total of 9 (if the player and computer each have one of the positions, it's a good strategy for the computer to take the third).
Prior to that last scenario, the other strategic move we make is to check all the corner sets (1/2/4, 2/3/6, etc.) as well as two opposing corner combinations (1/8/9 and 3/7/8). If any of these combinations sum to 8, i.e. the player has taken two of the positions, it's a good strategy for the computer to take the remaining free position.
Finally, there are a two special case moves. First, we always try and take the center position before any other move. This is achieved with the same routine as all our other moves, just passing in a single triple, 5/5/5, and a target sum of 0. Additionally, if all other test have failed to find a move, we try to take one of the top corners as a last resort. Again this is simply achieved by testing the triples 1/1/1 and 3/3/3, with a target sum of 0.
I don't think this is necessarily a perfect strategy - there may be games that the computer draws which could potentially have been won - but it's good enough to never lose a match. I've run a test script that tried to play every possible move against the computer, and for every valid sequence of moves, the computer either won or drew the game.


Find a point's position on the integral Hilbert curve


Befunge, 708 bytes

p&>:10p1-:>20p10g:20g\`v`\g02:-1\p00+1g<>g-#v_10g:*30p"~":40p50p060p070p$>^
1#+\#1<\1_^# !`0::-1$  _:00g3p\:00g2p00^^00:>#:

>>:2-#v_$30p50p60p70g1-70p
^<<<<<:#<<<<<<$$$_v#:!g87g78g79$  _v#!\-1:g88$<_ 98p87g97g*00 v:+!\`*84g++7<
^>$1-:77p1g:2g\3g1>78p97p87p10g97g->88p10g87g-0^!\-1:g89_v#-!\_$1-:v>/88g+7^
^|!-3$<   >\87g/88g+77++p:#v_$
^>:5->v   ^+g89%g78:\g77:-1<>98g88g48*577g387g97g98g88v ^>77g87g97v:^g78\+g<
^ v-4:_$77p88p98p:97p\:87p*^^g79g7>#8\#$_40pv5+"A"g77g< ^14g88g89g<>:87g%98^
^v_$88p98p97p87p:77p60g50g-:40g\`#^_$$>>>>>>>
 >#4!_::80p2g\3g*:90p30g`!v>>>#@>#.>#g^#0
^v:g06p03:-g09\2:g03g05g06_^^_7#<0#<g#<3#<1#<<`g04_$00g1->:#-8#10#\g#1`#:_>$
^>90g\-:0`*+:60p50g:90g-:0`*-:50p-80g70g:1+70p1p\!^

Try it online!

This is obviously not going to win any awards for size, but it's actually reasonably fast considering it's a basic bruce force implementation in an esoteric language. On the Befunge reference interpreter it can handle up to n=6 in a couple of seconds. With a compiler it can handle up to n=8 before it starts getting sluggish; n=9 takes a couple of minutes and n=10 is close on 2 hours.

In theory the upper limit is n=11 before we run out of memory (i.e. there's not enough space left in the playfield to fit a larger square). However, at that point, the time taken to calculate the optimal solution is probably longer than anyone would be willing to wait, even when compiled.

The best way to see how the algorithm works is by running it in one of the Befunge "visual debuggers". That way you can watch as it attempts to fit the various rectangle sizes into the available space. If you want to "fast forward" to the point where it has a good match, you can put a breakpoint on the 4 in the sequence $_40p near the middle of the tenth line (9 if zero-based). The value at the top of the stack at that point is the current area difference.

Below is an animation showing the first few frames of this process for n=5:

Each distinct rectangle is represented by a different letter of the alphabet. However, note that the final rectangle is never written out, so that section of the square will just be blank.

I've also written a debug version of the code that outputs the current layout each time it finds a new best match (Try it online!). For the smaller sizes, the first match is often the optimal solution, but once you get past n=6 you'll likely get to see several valid but non-optimal layouts before it settles on the final solution.

The best layout found for n=10 looks like this:

H F F F A A A C C I
H F F F A A A C C I
H J G G A A A C C I
H J G G A A A C C I
H J D D D D D C C I
H J D D D D D C C I
H J K K K K K K K I
H J B B B E E E E I
H J B B B E E E E I
H J B B B L L L L L

12 - 4 = 8


How many Blackjack sequences in that list?

Python 2, 215 bytes

def b(s,a=[],r=range):
 S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s)
 for i in r(12):
  for j in r(13):
   if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]and s[i:j]not in a:a+=s[i:j],
 return len(a)

Comments added:

def b(s,a=[],r=range):                                      # Define the function b and a list, a, which holds all the blackjack sequences
 S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s)      # Set S to the score of each card in b
 for i in r(12):                                            # Loop with i from 0 to 11
  for j in r(13):                                           # Loop with j from 0 to 12
   if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]\  # If 21 is included in all the possible sums that the scores between i and j in S can be
           and s[i:j]not in a:                              # And that sequence is not already included,
               a+=s[i:j],                                   # Append that sequence to a
 return len(a)                                              # Return the amount of elements in a


Python 2, 197 bytes

This solution uses string formatting to reduce repetition. Each string component is assembled, then placed within the template. It is tricky to use so many backslashes in Python strings. I used the raw string r'\\' and multi-line '''blah \n blah''' string techniques here.

def a(d,e):
 c='c|'*e;b='& '*e+r'\\';g=' '*4+b+'\n    \\hline\n';f=g*d;h='{tabular}'
 return r'''\begin%s{|c|%s}
    \cline{2-%s}
    \multicolumn{1}{c|}{} %s
    \hline
%s\end%s'''%(h,c,e+1,b,f,h)

Before the minifier, it looks like this:

def latextable(height, width):
    columns = 'c|' * width;
    linespec = '& ' * width + r'\\';
    line = ' '*4 + linespec + '\n    \\hline\n';
    block = line * height;
    mode = '{tabular}'
    return r'''\begin%s{|c|%s}
    \cline{2-%s}
    \multicolumn{1}{c|}{} %s
    \hline
%s\end%s''' % (mode, columns, width+1, linespec, block, mode)

print latextable(1, 1)
print latextable(2, 4)

The output tests:

\begin{tabular}{|c|c|}
    \cline{2-2}
    \multicolumn{1}{c|}{} & \\
    \hline
    & \\
    \hline
\end{tabular}
\begin{tabular}{|c|c|c|c|c|}
    \cline{2-5}
    \multicolumn{1}{c|}{} & & & & \\
    \hline
    & & & & \\
    \hline
    & & & & \\
    \hline
\end{tabular}

As a side note, I wrote a latex macro processor like this to format my thesis. I think I spent longer on developing that macro processor than on writing the words...


Code Golf: Create a string of 100 of the same character

golflua: 109 15

w(S.t("a",100))

Which is more-or-less equivalent to Heiko's Lua answer


Pyth, 12 10 bytes

hoSN%2.:z3

This prints the sleepiest emoticon. Verify all test cases at once  in the Pyth Compiler.

Credit goes to @Sp3000 for the idea to use sorting.

How it works

hoSN%2.:z3
              (implicit) Save the in z.
      .:z3    Compute all substrings of length 3.
    %2        Keep every seconds substring. This discards non-emoticons.
 o            Sort the emoticons by the following key:
  SN            Sort the characters of the emoticon.
                This works since '-' < '=' < 'o'.
h             Retrieve the first, minimal element.


PHP, 664 bytes

I'm not sure if 664 bytes fit for code golfing, but here it is:

$k=json_decode($argv[1]);$s=[];$f='array_shift';$r='heirs';$e='death';$y='year';function s
($k,&$e){uasort($e,function($a,$b)use($k){$c=$a->{$h='house'};$d=$b->$h;$e=$k->$h;if($c==$e
&&$d!=$e)return-1;elseif($c!=$e&&$d==$e)return 1;elseif($a->sex<$b->sex)return 1;elseif($a
->sex>$b->sex)return -1;else return$a->birth-$b->birth;});}function d(&$e,$y){foreach($e
as$i=>$h)if($h->death<=$y)unset($e[$i]);};($x=(array)$k)&&$k->$y=$k->birth;$l=[];while($x)
{$l[]=$k;$z=$k->$e;s($k,$k->$r);d($k->$r,$k->$e);if($k->$r){$s=$k->$r;$k=$f($s);}else{s($k
,$s);d($s,$k->$e);$k=$f($s);}if(!$k)break;$k->$y=$z;}foreach($l as$k)
echo"{$k->$y}-{$k->$e}: $k->name, ";echo"LINE EXTINCT";

It receives the JSON string input as the first command line argument.

The algorithm follows the steps described in the challenge (starts from the king, then sorts the heirs and then the siblings to find the next king).

Demo


Pari/GP, 14 bytes

polinterpolate

Takes two lists [x1, ..., xn] and [y1, ..., yn] as input. Outputs a polynomial.

Try it online!

Pari/GP, 37 bytes, without built-in

f(x,y)=y/matrix(#x,#x,i,j,x[j]^(i-1))

Takes two lists [x1, ..., xn] and [y1, ..., yn] as input. Outputs a list of coefficients.

Try it online!


Zsh, 3 bytes

>$0

Truncates the script to length 0.

Unlike its Bash counterpart, this handles filenames that contain whitespace.

Try it online!


R, 159 153 148 bytes

function(P,Q,a=h(P),b=h(Q))paste0(b[1,]%o%a[1,],"x^",outer(b,a,"+")[2,,2,],collapse=" + ")
h=function(s,`/`=strsplit)sapply(el(s/" . ")/"x.",strtoi)

Try it online!

I really wanted to use outer, so there's almost surely a more efficient approach.


J, 57

(,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'

eg

   (,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'
Carl buys for Earl
Andy buys for Barb
Fran buys for Didi
Didi buys for Fran
Barb buys for Andy
Earl buys for Carl