Mathematica 1170 1270 1096 1059 650 528 570 551 525 498 bytes

The latest version saves 27 bytes by not requiring that the plate be "trimmed" before it is parsed.  The penultimate version saved 26 bytes by using only 10 of the original 24 sample points.

z=Partition;h@i_:=i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@z[{45,99,27,81,63,81,9,63,45,63,9,45,45,45,63,45,45,27,45,9},2];f@p_:=h/@SortBy[Select[p~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},100<Last@ImageDimensions@#[[2,1]]<120&],#[[2,2,1]]&][[All,2,1]]/.Thread[IntegerDigits[#,2,10]&/@(z[IntegerDigits[Subscript["ekqeuiv5pa5rsebjlic4i5886qsmvy34z5vu4e7nlg9qqe3g0p8hcioom6qrrkzv4k7c9fdc3shsm1cij7jrluo", "36"]],4]/.{a__Integer}:> FromDigits[{a}])-> Characters@"BD54TARP89Q0723Z6EFGCSWMNVYXHUJKL1"]

122 bytes saved through LegionMammal978's idea of packing the long list of base 10 numbers as a single, base 36 number.  He pared another 20 bytes off the final code.

The jump from 528 to 570 bytes was due to additional code to ensure that the order of the letters returned corresponded to the order of the letters on the license plate. The centroid for each letter contains the x-coordinate, which reveals the relative positions of the letters along x.

Ungolfed Code

coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1];
h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :>  ⌈z⌉  & /@ coordinates, {6, 4}];
plateCrop[img_]:=ColorReplace[ImageTrim[img,{{100,53},{830,160}}],Yellow];
codes={{{15,13,15,13,13,15},"B"},{{15,8,8,8,9,15},"C"},{{15,13,13,13,13,15},"D"},{{15,8,14,8,8,15},"E"},{{15,8,14,8,8,8},"F"},{{15,8,8,11,9,15},"G"},{{6,6,6,6,15,9},"A"},{{9,9,15,15,9,9},"H"},{{8,8,8,8,8,15},"L"},{{9,15,15,15,13,9},"M"},{{15,9,9,9,9,15},"0"},{{9,10,12,14,10,9},"K"},{{9,13,13,11,11,9},"N"},{{8,8,8,8,8,8},"1"},{{1,1,1,1,9,15},"J"},{{15,9,15,14,8,8},"P"},{{15,9,9,9,15,15},"Q"},{{15,9,15,14,10,11},"R"},{{15,8,12,3,1,15},"S"},{{9,15,6,6,6,6},"V"},{{15,6,6,6,6,6},"T"},{{9,15,15,15,15,15},"W"},{{9,9,9,9,9,15},"U"},{{9,14,6,6,14,9},"X"},{{9,14,6,6,6,6},"Y"},{{15,3,2,4,12,15},"Z"},{{15,9,9,9,9,15},"0"},{{8,8,8,8,8,8},"1"},{{15,1,3,6,12,15},"2"},{{15,1,3,1,9,15},"3"},{{2,6,6,15,2,2},"4"},{{7,12,14,1,1,15},"5"},{{15,8,14,9,9,15},"6"},{{15,1,2,2,6,4},"7"},{{15,9,15,9,9,15},"8"},{{15,9,15,1,9,15},"9"}};
decryptRules=Rule@@@codes;
isolateLetters[img_]:=SortBy[Select[ComponentMeasurements[plateCrop[img],{"Image","Centroid"}],ImageDimensions[#[[2,1]]][[2]]>100&],#[[2,2,1]]&][[All,2,1]]
f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolateLetters[plate]/.decryptRules

Overview

The basic idea is to check whether a systematic sampling of pixels from the input image matches pixels from the same location on the bonafide images.  Much of the code consists of the bit signatures for each character,

The diagram shows the pixels that are sampled from the letters "J", "P","Q", and "R".

The pixel values can be represented as matrices. The dark, bold 1's correspond to black cells. The 0's correspond to white cells.

These are the decryption replacement rules for J  P  Q  R.

{1, 1, 1, 1, 9, 15} -> "J",
{15, 9, 15, 14, 8, 8} -> "P",
{15, 9, 9, 9, 15, 15} -> "Q",
{15, 9, 15, 14, 10, 11} -> "R"

It should be possible to understand why the rule for "0" is:

{15, 9, 9, 9, 9, 15} -> "0"

and thus distinguishable from the letter "Q".

The following shows the 10 points used in the final version.  These points are sufficient for identifying all of the characters.

What the functions do

plateCrop[img] removes the frame and left edge from the plate, makes the background white.  I was able to eliminate this function from the final version by selecting image components, possible letters  that were between 100 and 120 pixels high.

isolateLetters[img] removes the individual letters from the cropped image.

We can display how it works by showing where the cropped image, output from plateCrop goes as input for isolateLetters. The output is a list of individual characters.

Coordinates are 24 evenly distributed positions for checking the pixel color. The coordinates correspond to those in the first figure.

coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1];

{{9, 99}, {27, 99}, {45, 99}, {63, 99}, {9, 81}, {27, 81}, {45,
  81}, {63, 81}, {9, 63}, {27, 63}, {45, 63}, {63, 63}, {9, 45}, {27,
  45}, {45, 45}, {63, 45}, {9, 27}, {27, 27}, {45, 27}, {63, 27}, {9,
  9}, {27, 9}, {45, 9}, {63, 9}}

h converts the pixels to binary.

h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :>  ⌈z⌉  & /@ coordinates, {6, 4}];

codes are the signature for each character.  The decimal values are abbreviations of the binary code for black (0) and White (1) cells. In the golfed version, base 36 is used.

codes={{{15, 9, 9, 9, 9, 15}, "0"}, {{8, 8, 8, 8, 8, 8}, "1"}, {{15, 1, 3,6,12, 15}, "2"}, {{15, 1, 3, 1, 9, 15}, "3"}, {{2, 6, 6, 15, 2, 2}, "4"}, {{7, 12, 14, 1, 1, 15},"5"}, {{15, 8, 14, 9, 9, 15}, "6"}, {{15, 1, 2, 2, 6, 4},"7"}, {{15, 9, 15, 9, 9, 15}, "8"}, {{15, 9, 15, 1, 9, 15},"9"}, {{6, 6, 6, 6, 15, 9}, "A"}, {{15, 13, 15, 13, 13, 15}, "B"}, {{15, 8, 8, 8, 9, 15}, "C"}, {{15, 13, 13, 13, 13, 15}, "D"}, {{15, 8, 14, 8, 8, 15}, "E"}, {{15, 8, 14, 8, 8, 8},"F"}, {{15, 8, 8, 11, 9, 15}, "G"}, {{9, 9, 15, 15, 9, 9}, "H"}, {{1, 1, 1, 1, 9, 15}, "J"}, {{9, 10, 12, 14, 10, 9}, "K"}, {{8, 8, 8, 8, 8, 15}, "L"}, {{9, 15, 15, 15, 13, 9}, "M"}, {{9, 13, 13, 11, 11, 9}, "N"}, {{15, 9, 15, 14, 8, 8}, "P"}, {{15, 9, 9, 9, 15, 15}, "Q"}, {{15, 9, 15, 14, 10, 11}, "R"}, {{15, 8, 12, 3, 1, 15}, "S"}, {{15, 6, 6, 6, 6, 6}, "T"}, {{9, 9, 9, 9, 9, 15}, "U"}, {{9, 15, 6, 6, 6, 6}, "V"}, {{9, 15, 15, 15, 15, 15}, "W"}, {{9, 14, 6, 6, 14, 9}, "X"}, {{9, 14, 6, 6, 6, 6}, "Y"}, {{15, 3, 2, 4, 12, 15}, "Z"}};

(* decryptRules are for replacing signatures with their respective character *)

decryptRules=Rule@@@codes;

f is the function that takes an image of a license plate and returns a letter.

f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolate[plateCrop@plate]/.decryptRules;

{"A", "B", "C", "D", "E", "F", "G"}
{"H", "1", "J", "K", "L", "M", "N", "0"}
{"P", "Q", "R", "S", "T", "U", "V", "W"}
{"X", "Y", "Z", "0", "1", "2", "3", "4"}
{"5", "6", "7", "8", "9"}

Golfed

The code is shortened by using a single decimal number to represent all 24 bits (white or black) for each character. For example, the letter "J" uses the following replacement rule: 1118623 -> "J".

1118623 corresponds to

IntegerDigits[1118623 , 2, 24]

{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1,
  1}

which can be repackaged as

ArrayReshape[{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1}, {6, 4}]

{{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {1, 0, 0,
  1}, {1, 1, 1, 1}}

which is simply the matrix for "J" that we saw above.

%//MatrixForm

Another savings comes from representing the alphabet as "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" rather than as a list of letters.

Finally, all of the functions from the long version, except h, were integrated into the function f rather than defined separately.

h@i_:=ArrayReshape[i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@Join@@Table[{x,y},{y,99,0,-18},{x,9,72,18}],{6,4}];f@p_:=#~FromDigits~2&/@(Join@@@h/@SortBy[Select[p~ImageTrim~{{100,53},{830,160}}~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},Last@ImageDimensions@#[[2,1]]>100&],#[[2,2,1]]&][[;;,2,1]])/.Thread[IntegerDigits[36^^1c01agxiuxom9ds3c3cskcp0esglxf68g235g1d27jethy2e1lbttwk1xj6yf590oin0ny1r45wc1i6yu68zxnm2jnb8vkkjc5yu06t05l0xnqhw9oi2lwvzd5f6lsvsb4izs1kse3xvx694zwxz007pnj8f6n,8^8]->Characters@"J4A51LUHKNYXVMW732ZTCGSFE60Q98PRDB"]


Python [on Windows], 262 bytes

from time import*
import os,random
t,i=time(),0
while time()-t<15:print([""",d88b.d88b,
88888888888
`Y8888888Y'
  `Y888Y'
    `Y'""",""" d8b d8b
888888888
`Y88888P'
 `Y888P'
  `Y8P'
   `Y'"""][i%2]);i+=1;sleep(random.randint(3,14)/10);os.system('cls')
print(i*4)

For linux and macOS use os.system('clear') for 2 more bytes.


Golfscript, 2 characters
`,

(stringify (`) the number and count (,) the digits)
J, 3 characters
#q:

is the count (#) of the prime factors (q:) of its input.
The vector form involves more bookkeeping, but that's not our contestant:
#@q:L:0&.<

the first 40 terms are: 0 1 1 2 1 2 1 3 2 2 1 3 1 2 2 4 1 3 1 3 2 2 1 4 2 2 3 3 1 3 1 5 2 2 2 4 1 2 2 4
see more at OEIS
The sequence is 1 at every prime position, 2 at every prime multiple of a prime, 3 at every prime multiple of a product of two primes...

If you are not convinced this is aperiodic, here are plenty of other sequences:
##:

(the number of bits = floor of the base-2 logarithm)
+/#:

(count of 1-bits in the binary representation of the number). This (reduced under any modulus)
#b#:
+/b#:

(the same in base-b)
<.^.
>.^.
<.b^.
>.b^.

(floor or ceiling of the (natural) log - this time without stringification)
*./#:
+./b#:
*./b#:

(GCD or LCM of all base-b digits (except GCD of bits won't work))
1{#:!
9{#:!
({#:@!)

(second/tenth/nth highest bit of the factorial of n)
(=<.&.%:)

(Is the number equal its floor under the square root operation? Is the number equal the square of the floor of its square root? Is the number a square?)


Processing, 197 195 bytes
void setup(){size(255,255);int r=255,a=r,g=0,b=0,i,j,k;background(a);for(i=0;i<a;k=i<43?g+=6:i<85?r-=6:i<a/2?b+=6:i<170?g-=6:i<213?r+=6:a>1?b-=6:0,i++)for(j=0;j<a;point(i,j++))stroke(r,g,b,a-j);}

This outputs the image in a 255x255 sized window
Explained
void setup(){            //this is required
  size(255,255);         //size of sketch
  int r=255,a=r,g=0,b=0,i,j,k; //declaring our vars
  background(a);         //set the background colour as white
  //for-loop for the x-coordinates, it also increments/decrements rgb values
  //  based on the x-coordinate
  for(i=0;i<a;k=i<43?g+=6:i<85?r-=6:i<a/2?b+=6:i<170?g-=6:i<213?r+=6:a>1?b-=6:0,i++)
    //for-loop for the y-coordinate (alpha)
    for(j=0;j<a;point(i,j++))   //2) then draw the point at the location
      stroke(r,g,b,a-j);        //1) set the colour of point
}

Edits

Used int instead of float
THIS SOLUTION IS INVALID DUE TO NEW RULES BEING ADDED. I WILL UPDATE ANSWER SOON


Retina, 16 bytes

(?<=# *) (?= *#)

Try it online! Link includes test case. Works by counting the spaces which are surrounded by #s.


Find the results of the poll with the Borda count method

Perl 5, 131 bytes

for(split/, /,$ARGV[0]){($n,@v)=split/:? /;$s{$v[@v-$_]}+=$n*$_ for 1..@v}$,=": ";map{say++$i,"$_ ",$s{$_}}sort{$s{$b}<=>$s{$a}}@v

Use as perl -E'the string above' 'the input string'


Do n and n^3 have the same set of digits?

Python 3, 36 32 bytes
lambda x:{*str(x)}=={*str(x**3)}

I think this only works in Python 3.5 and later.
Four bytes have gone, thanks to Copper.


Jelly, 25 bytes

ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j

Try it online!

This unfortunately does not contain the error-if-invalid feature.

Explanation

This is what I call the Jelly syndrome: the easy part is explaining the algorithm, the hard part is explaining how you found the exact order to put the code in to make it execute correctly.

ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j
                       ¿     While
                 j           joining the input list
                  ⁴          with the glue produces a string
                   L         whose length
                    >        is larger than
                     ⁵       the maximum,
               ¦             in the input array at the
             Ḣ               first of the positions that
            M                have maximal
          L€                 length,
ṖṖ                           remove the last two characters,
  ;                          append
   ⁽÷ẓ                       the number 8230
      Ọ                      and cast it to a character.
                        j    Finally, join again with the glue.


8086 machine code, 32 31 28 26 bytes

00000000  b8 0f 00 cd 10 b8 02 10  ba 18 01 cd 10 b8 03 00  |................|
00000010  cd 33 4b b8 01 0c eb f3  3f 00                    |.3K.....?.|
0000001a

Assumes the presence of a VGA graphics card, and any Microsoft-compatible mouse driver.

-2 bytes thanks to @berendi!

How it works:

            |   org 0x100
            |   use16
b8 0f 00    |       mov ax, 0x000f      ; set screen mode: 640x350 monochrome
cd 10       |       int 0x10            ; call video bios
b8 02 10    |       mov ax, 0x1002      ; set palette
ba 18 01    |       mov dx, palette     ; pointer to palette data
cd 10       |   @@: int 0x10            ; call video bios
b8 03 00    |       mov ax, 0x0003      ; get mouse position in (CX, DX) and button status in BL
cd 33       |       int 0x33            ; call mouse driver
4b          |       dec bx              ; if no buttons pressed, --BX = 0xFFFF (invalid page)
b8 01 0c    |       mov ax, 0x0c01      ; plot pixel with color AL at (CX, DX) in page BH
eb f3       |       jmp @b              ; repeat
3f 00       |   palette db 0x3f, 0x00   ; palette in 2:2:2 rgb. color 0 = white, 1 = black.
            |                           ; this should be a 17-byte struct, but we only care about the first two colors here

That's all there is to it. No magic involved, just a few function calls.


C# (Visual C# Interactive Compiler), 73 85 bytes

a=>Encoding.UTF8.GetBytes(a).Select(b=>Encoding.GetEncoding(850).GetString(new[]{b}))

Try it online!

+12 bytes to use the updated code page


JavaScript (ES6),  75 74  67 bytes
Expects a list of [color, label] pairs, using 0-2 for both. Returns a binary array describing which wires must be cut.
a=>a.map(([c,w])=>(m[c]/=8)>>w&1,m=[334844576,228136272,611931512])

Try it online!
63 bytes
We can save a few bytes by taking A=1, B=2, C=4 and returning a list of zero / non-zero values.
a=>a.map(([c,w])=>w&=m[c]/=8,m=[334844576,228136272,611931512])

Try it online!
How?
Each color is encoded as a bit mask describing the wire labels for the 1st to the 9th appearance.
 #     |  9   8   7   6   5   4   3   2   1  (0)
 Label | CBA CBA CBA CBA CBA CBA CBA CBA CBA ---
-------+-----------------------------------------
 Red   | 010 011 111 101 010 101 001 010 100 000 -> 334844576
 Blue  | 001 101 100 110 010 001 010 101 010 000 -> 228136272
 Black | 100 100 011 110 010 101 010 101 111 000 -> 611931512

Whenever a color appears, we right-shift the corresponding bit mask by 3 positions (by dividing it by 8) and we test the bit 0, 1 or 2 according to the label.


Pyth, 13 11 bytes

+*.xwd-Qlzz

Try it here.

Takes input from STDIN as the string on the first line, length on the second line, and padding char optionally on a third line.


Here's a whole bunch of micro-optimisations you can do:

Use .split() to create a long list (-17 bytes):

c=['yellow','blue','white','green','Black', 'purple', 'silver', 'cyan', 'magenta', 'red']
c='yellow blue white green Black purple silver cyan magenta red'.split()

Remove extraneous brackets (-2 bytes):

l+=y[0]*(random.randint(n[o],n[o+1]))
l+=y[0]*random.randint(n[o],n[o+1])

Use splat (-2 bytes):

random.randint(n[o],n[o+1])
random.randint(*n[o:o+2])

Use extended iterable unpacking to turn something into a list (-4 bytes):

l=list(l)
*l,=l

Import all the things (-15 bytes):

import random;random.randint;random.shuffle;random.shuffle
from random import*;randint;shuffle;shuffle

Use other functions that can do the same job here (-5 * 2 = -10 bytes):

j.capitalize()
j.title()

print separates by space by default (-11 bytes):

print(str(l.count(b[0])) + " "+b)
print(l.count(b[0]),b)

More unpacking (-3 bytes):

r=l.pop()
*l,r=l

Abuse side-effects (-1 byte, plus indents):

if j[0]==r:print(j.capitalize())
r!=j[0]or print(j.capitalize())

Anything reused and over 5 chars might be worth saving as a variable (-1 byte):

len(s);len(s)
L=len(s);L;L

Simplify fractions (-5 bytes):

len(s)*25/100
len(s)/4

Unary abuse (-4 bytes):

if(i<(len(m)-1)):i+=1
if~-len(m)>i:i+=1

Or the biggest one of all...

Look at your algorithm, and see if it needs changing altogether

from random import*
*s,P,S=print,shuffle
P("Welcome to the CIMS Gumball Machine Simulator\nYou are starting with the following gumballs:")
*l,c,C='yellow blue white green Black purple silver cyan magenta red'.split(),s.count
for x,y,z in zip(c,[10,1,6,10,1,5,4,5,0,1],[15,10,15,25,12,10,6,12,10,1]):n=randint(y,z);l+=[x]*n;P(n,x)
S(l)
P("Here are your random purchases:")
while'red'in l:S(l);*l,r=l;s+=r,;P(r.title())
L=len(s)
P("You purchased %i gumballs, for a total of $%.2f\nMost common gumball(s):"%(L,L/4))
for x in c:C(x)!=max(map(C,c))or P(x.title())

(If you ever find yourself importing Counter in a code-golf, you're probably doing something very wrong...)


Pyth, 10 bytes

}CQsyMCMyE

Test suite

This is fairly straightforward. First, we consider B as a list of rows, and take all subsets using yE. Then, each of those matrices is transposed with CM, and all subsets are taken of their rows, with yM. Concatenating these sublists with s gives all possible transposed submatrices. So we transpose A with CQ, and check if it is present with }.


Ruby (60) (61) (93) (80) (75) (71) (69 / 57)

Program changed to handle the new requirement of handling multiple words.

EDIT: Golfed down to 80. 75. 71. 69.

w=[];gets.gsub(/(\S*?)([aeiouy]\S*)/i){w+=[$2,' ',$1]};$><<w.pop+w*''

If we're only spoonerizing words that start with a consonant, here's a solution in 73. 65. (I realized I can just use scan instead of gsub.) 57.

$><<gets.gsub(p=/\b[^aeiouy\s]+/i){($'+$`+$&).scan(p)[0]}

Old program (two words only):

p='(.*?)([aeiou].+)';puts gets.gsub(/#{p} #{p}/i,'\3\2 \1\4')


Haskell, 40 37 bytes

f 0=[0]
f a=[(*2),(+1).(*2)]<*>f(a-1)

Try it online!

Thanks to @Laikoni for three bytes!


Find the date that is n days from January 1st 1984

05AB1E, 111 106 103 bytes
•3zb•2ôI5°7*+F©`т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹i®ć>šë®1¾ǝDÅsD12‹i>1ǝë<sθ>ª]εNi”……‚æ‡‰…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”#sè

Output as a triplet [day, "Month", year].
Try it online. (Sort of, since it times out for any input above \$\geq-650000\$..)
Explanation:
Since 05AB1E doesn't have any date builtins, I've calculated things manually before. I've used the code of going to the next day from this answer of mine, which in turns also uses the leap year calculation of this answer of mine.
Since this challenge also asks to go back in time, I would need to implement something to go to a previous day as well for negative inputs, which would cost a lot of bytes. Instead, since the challenge input is limited to the range \$[-700000,700000]\$, I used that to my advantage and start going upwards in days from date June 21st, 0067 onward, which is 700,000 days before January 1st, 1984.
In pseudo-code, I therefore do the following steps:
1   Date currentDate = [21,06,0067]
2   Loop input + 700000 amount of times:
3*   currentDate += 1;  # Set currentDate to the next date in line
4   Convert month-integer to month-string and output the result

Where step 3 is divided into substeps:
a   Integer isLeapYear = ...;
b   Integer daysInCurrentMonth = currentDate.month == 2 ?
c                                 28 + isLeapYear
d                                :
e                                 31 - (currentDate.month - 1) % 7 % 2;
f   If(currentDate.day < daysInCurrentMonth):
g     nextDate.day += 1;
h   Else:
i     nextDate.day = 1;
j     If(currentDate.month < 12):
k       nextDate.month += 1;
l     Else:
m       nextDate.month = 1;
n       nextDate.year += 1;

Transforming that into code:
1) Date currentDate = [21,06,0067] is done like this:

•3zb•     # Push compressed integer 210667
     2ô   # Split it into parts of size 2: [21,06,67]
...
©         #  Store the current date in variable `®` (without popping)

2) Loop input + 700000 amount of times: is done like this:

I         # Push the input-integer
 5°       # Push 10 to the power 5: 100000
   7*     # Multiply that by 7: 700000
     +    # Add it to the input-integer
      F   # Loop that many times:

3a) Integer isLeapYear = ...; is done like this:

`         # Pop and push the day, month, and year separated to the stack
 т‰       # Take the divmod of 100
   0K     # Remove all 0s
     θ    # Pop and leave its last value
      4Ö  # And check if it's divisible by 4 (1 if it's a leap year; 0 if not)
        U # Pop and store this in variable `X`

3b) currentDate.month == 2 ? and 3c) 28 + isLeapYear:

D         # Duplicate the month that is still on the stack
 2Qi      # If it's equal to 2 (thus February):
    \     #  Discard the duplicated month from the stack
     28X+ #  And add 28 and `X` (the isLeapYear check) together

3d) : and 3e) 31 - (currentDate.month - 1) % 7 % 2;:

ë         # Else:
 <        #  Month - 1
  7%      #  Modulo-7
    É     #  Is odd (short for modulo-2)
     31α  #  Absolute difference with 31
}         # Close the if-else statement

3f) If(currentDate.day < daysInCurrentMonth)::

‹         # Check if the day that is still on the stack is smaller than this value
 i        # If it is:

3g) nextDate.day += 1;:

®         #  Push the entire date from variable `®` again
 ć        #  Extract its head (the days); pop and push [month,year] and day separated
  >       #  Day + 1
   š      #  Prepend it back in front of the list

3h) Else: and 3i) nextDate.day = 1;:

ë         # Else:
 ®        #  Push the entire date from variable `®` again
  1       #  Push a 1
   ¾      #  Push index 0
    ǝ     #  Insert the 1 at index 0 (to replace the day) in the list `®`

3j) If(currentDate.month < 12)::

D         # Duplicate it
 Ås       # Pop and push the middle item (the month)
   D12‹   # Check if the month is below 12:
       i  # And if it is:

3k) nextDate.month += 1;:

>         # Month + 1
 1        # Push index 1
  ǝ       # Insert the month + 1 at index 1 (to replace the month) in the list `®`

3l) Else:, 3m) nextDate.month = 1; and 3n) nextDate.year += 1;:

ë         # Else:
 <        #  Decrease the month by 1 to 11
  s       #  Swap so list `®` is at the top of the stack again
   θ      #  Pop and push its last item (the year)
    >     #  Year + 1
     ª    #  Convert the 11 to list [1,1] and append the year + 1

4) And finally we convert the month-integer to month-string in the resulting date, and output the result:

]         # Close both if-else statements and the infinite loop
 ε        # Map the resulting date to:
  Ni      #  If the (0-based) index is 1 (thus the month)
    ”……‚æ‡‰…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”
          #   Push the dictionary string of months ("December January ... November"
     #    #   Split it on spaces to a list of strings
      s   #   Swap so the month is at the top of the stack
       è  #   And index it into the list (0-based and with wraparound,
          #   which is why "december" is the first item)
          # (after which the resulting date is output implicitly)

See this 05AB1E tip of mine (sections How to use the dictionary? and How to compress large integers?) to understand why •3zb• is 210667 and ”……‚æ‡‰…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í” is "December January February March April May June July August September October November".


I palindrome the source code, you palindrome the input!

Haskell, Full program, 39 bytes
iddi=(++)<*>reverse;main=interact--
 id

Try it online!
Mirrored

iddi=(++)<*>reverse;main=interact--
 iddi
--tcaretni=niam;esrever>*<)++(=iddi

Try it online!
Very simple approach for a full program.  We have two "lines" (separated by ; rather than an actual line break) of boilerplate ending in -- and then the function id.  When the program is reversed id gets changed to iddi, which we have defined to do the intended operation.
Haskell, Function, 20 bytes
f x=x--x esrever++

Try it online!
Mirrored
f x=x--x esrever++

 ++reverse x--x=x f

Try it online!
This one is also a pretty simple approach.  We have a function f x=x and   a payload hidden in a comment.  When the code is revealed the payload extends our function with ++reverse x.
Haskell, Function, No Comments, 95 bytes

i=id
ko 'a' b=i id b
ko u m=i reverse m
u=flip ko
k s="ab">>=s
yf i=k<$>u
erehw l=l
fy=i erehw

Try it online!
Mirrored
i=id
ko 'a' b=i id b
ko u m=i reverse m
u=flip ko
k s="ab">>=s
yf i=k<$>u
erehw l=l
fy=i erehw  where i=yf
l=l where
u>$<k=i fy
s=>>"ba"=s k
ok pilf=u
m esrever i=m u ok
b di i=b 'a' ok
di=i

Try it online!
The relevant function is fy. This one is likely not optimal.  I will explain it when I shorten it down a bit.


CJam, 40 39 38 bytes

q~21Ue]e!{21,Af-Aest.*:+!}=0'_erNAS*'^

Try it online.

How it works

q~                                     e# Read and evaluate the input.
  21Ue]                                e# Append zeroes to achieve a length of 21.
       e!                              e# Push all unique permutations.
         {               }=            e# Find the first permutation such that:
          21,                          e#  Push [0 ... 20].
             Af-                       e#  Subtract 10 from each.
                Aest                   e#  Replace the element at index 10 with the
                                       e#  current time (ms since epoch) to push
                                       e#  [-10 ... -1 <big number> 1 ... 10].
                    .*                 e#  Multiply each number of the permutation
                                       e#  by the corresponding distance.
                      :+               e#  Add the products.
                                       e#  The timestamp makes sure that this sum
                                       e#  is non-zero for a non-zero element in
                                       e#  the middle of the permutation.
                        !              e#  Push the logical NOT of the sum.
                           0'_er       e# Replace zeroes with underscores.
                                NAS*'^ e# Push a linefeed, ten spaces and a caret.


JavaScript ES6, 18 bytes

n=>-~(n/3)*(1-n%3)

Turned out very similar to @LeakyNun's answer but I didn't see his until after I posted mine.

Explanation and Ungolfed

-~ is shorthand for Math.ceil, or rounding up:

n =>               // input in var `n`
    Math.ceil(n/3) // Get every 3rd number 1,1,1,2,2,2, etc.
    *
    (1-n%3)        // 1, 0, -1, 1, 0, -1, ...

function f(n){n=i.value;o.value=-~(n/3)*(1-n%3);}
Input: <input id=i oninput="f()"/>

Output: <input id=o readable/>


C#

This might not be completeley what you envisioned, but this is the best I could do right now. (At least with C# and CodeDom).

So how it works:

It calculates the digitsum base 2 (the base wasn't specified in the statement)
It tries to generate an expression with a lot of terms that look like ((i & v1) >> v2). These terms will be the genes that will be mutated through the run.
The fitness function simply compares the values with a pre-calculated array, and uses the sum of the absolute value of the differences. This means a 0 value means we have arrived to the solution, and the less the value the fitter the solution.

The code:

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;

namespace Evol
{
    class MainClass
    {
        const int BASE = 2;
        static int[] correctValues;
        static List<Evolution> values = new List<Evolution>();

        public static CodeCompileUnit generateCompileUnit(CodeStatementCollection statements) {
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace samples = new CodeNamespace("CodeGolf");
            compileUnit.Namespaces.Add(samples);
            samples.Imports.Add(new CodeNamespaceImport("System"));
            CodeTypeDeclaration digitSumClass = new CodeTypeDeclaration("DigitSum");
            samples.Types.Add(digitSumClass);
            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "digitsum";
            method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            method.ReturnType = new CodeTypeReference (typeof(int));
            method.Parameters.Add (new CodeParameterDeclarationExpression (typeof(int), "i"));
            method.Statements.AddRange (statements);
            digitSumClass.Members.Add(method);
            return compileUnit;
        }

        public static long CompileAndInvoke(CodeStatementCollection statements, bool printCode) {
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add( "System.dll" );
            cp.GenerateInMemory = true;
            CodeGeneratorOptions cgo = new CodeGeneratorOptions ();
            CodeDomProvider cpd = new CSharpCodeProvider ();
            CodeCompileUnit cu = generateCompileUnit (statements);
            StringWriter sw = new StringWriter();
            cpd.GenerateCodeFromCompileUnit(cu, sw, cgo);
            if (printCode) {
                System.Console.WriteLine (sw.ToString ());
            }

            var result = cpd.CompileAssemblyFromDom (cp, cu);

            if (result.Errors.Count != 0) {
                return -1;
            } else {
                var assembly = result.CompiledAssembly;
                var type = assembly.GetType ("CodeGolf.DigitSum");
                var method = type.GetMethod ("digitsum");
                long fitness = CalcFitness (method);
                return fitness;
            }
        }

        public static long CalcFitness(MethodInfo method) {
            long result = 0;
            for (int i = 0; i < correctValues.Length; i++) {
                int r = (int)method.Invoke (null, new Object[] { i });
                result += Math.Abs (r - correctValues[i]);
            }
            return result;
        }

        public static CodeStatementCollection generateCodeDomFromString (Term[] terms) {
            CodeStatementCollection statements = new CodeStatementCollection ();
            CodeExpression expression = null;
            foreach (Term term in terms) {
                CodeExpression inner = new CodeArgumentReferenceExpression ("i");
                if (term.and.HasValue) {
                    inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.BitwiseAnd, new CodePrimitiveExpression(term.and.Value));
                }
                if (term.shift.HasValue) {
                    inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.Divide, new CodePrimitiveExpression(Math.Pow (2, term.shift.Value)));
                }
                if (expression == null) {
                    expression = inner;
                } else {
                    expression = new CodeBinaryOperatorExpression (expression, CodeBinaryOperatorType.Add, inner);
                }
            }
            statements.Add (new CodeMethodReturnStatement (expression));
            return statements;
        }

        public static void Main (string[] args)
        {
            correctValues = new int[10001];
            for (int i = 0; i < correctValues.Length; i++) {
                int result = 0;
                int num = i;
                while (num != 0) {
                    result += num % BASE;
                    num /= BASE;
                }
                correctValues [i] = result;
            }
            values.Add (new Evolution (new Term[] { new Term (null, null) }));
            Random rnd = new Random ();
            while (true) {
                // run old generation
                foreach (var val in values) {
                    CodeStatementCollection stat = generateCodeDomFromString (val.term);
                    long fitness = CompileAndInvoke (stat, false);
                    val.score = fitness;
                    System.Console.WriteLine ("Fitness: {0}", fitness);
                }
                Evolution best = values.Aggregate ((i1, i2) => i1.score < i2.score ? i1 : i2);
                CodeStatementCollection bestcoll = generateCodeDomFromString (best.term);
                CompileAndInvoke (bestcoll, true);
                System.Console.WriteLine ("Best fitness for this run: {0}", best.score);

                if (best.score == 0)
                    break;

                // generate new generation
                List<Evolution> top = values.OrderBy (i => i.score).Take (3).ToList();
                values = new List<Evolution> ();
                foreach (var e in top) {
                    values.Add (e);
                    if (e.term.Length < 16) {
                        Term[] newTerm = new Term[e.term.Length + 1];
                        for (int i = 0; i < e.term.Length; i++) {
                            newTerm [i] = e.term [i];
                        }
                        int rrr = rnd.Next (0, 17);
                        newTerm [e.term.Length] = new Term ((int)Math.Pow(2,rrr), rrr);
                        values.Add (new Evolution (newTerm));
                    }
                    {
                        int r = rnd.Next (0, e.term.Length);
                        Term[] newTerm = (Term[])e.term.Clone ();
                        int rrr = rnd.Next (0, 17);
                        newTerm [r] = new Term ((int)Math.Pow(2,rrr), rrr);
                        values.Add (new Evolution (newTerm));
                    }
                }
            }
        }

        public struct Term {
            public int? and;
            public int? shift;

            public Term(int? and, int? shift) {
                if (and!=0) {
                    this.and = and;
                } else this.and = null;
                if (shift!=0) {
                    this.shift = shift;
                } else this.shift=null;
            }
        }

        public class Evolution {
            public Term[] term;
            public long score;

            public Evolution(Term[] term) {
                this.term = term;
            }
        }
    }
}

Tested on OSX with Mono C# compiler version 3.2.6.0.

At each iteration it prints the fitness value of the current calculation. At the end it will print the best solution along with its fitness. The loop will run until one of the results have a fitness value of 0.

This is how it starts:

// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return i;
        }
    }
}

Best fitness for this run: 49940387

And after a while (takes around 30 minutes), this is how it ends (showing the last and almost last iteration):

// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return ((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 128) / 128)) + ((i & 65536) / 65536)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048));
        }
    }
}

Best fitness for this run: 4992
Fitness: 4992
Fitness: 7040
Fitness: 4993
Fitness: 4992
Fitness: 0
Fitness: 4992
Fitness: 4992
Fitness: 7496
// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return (((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 64) / 64)) + ((i & 32768) / 32768)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048)) + ((i & 32768) / 32768));
        }
    }
}

Best fitness for this run: 0

Notes:

CodeDOM doesn't support the left shift operator so instead of a >> b I'm using a / 2^b
The initial iteration is just a return i; as required by the problem.
In the first few iterations priority is given to adding new terms (genes) to the sum. Later there is more priority in changing values (mutation) in terms randomly.
I'm generating terms that look like i & a >> a instead of i & a >> b, as in the latter case the evolution was simply too slow to be practical.
This is also why the solution is limited to finding an answer in the form return (i&a>>b)+(i&c>>d)+..., as any other kind (like trying to generate a "proper" code, with loops, assignments, condition checks, etc.) would simply converge too slowly. Also this way it is very easy to define the genes (each of the term), and is very easy to mutate them.
This is also the reason why I'm adding the digits in base 2 (the base wasn't specified in the problem statement, so I consider this fine). A base 10 solution would've been just to slow, and also it would've been really hard to define the actual genes. Adding a loop would also mean that you have to manage the running code, and find a possible way to kill it, before it enters a potentially infinite loop.
Genes are only mutated, there is no crossover in this solution. I don't know whether adding that would speed up the evolution process or not.
The solution is only tested for numbers 0..10000 (if you check the found solution you can see that it won't work for numbers larger than 16384)
The whole evolution process can be checked at this gist.


05AB1E, 15 bytes
On the phone, so explanation will have to follow later. Code:
gF¹N>ã})€`€JDÚQ

Uses CP-1252 encoding. Try it online!.
Takes too much memory for the last test case, so that might not work...


convey, 36 29 bytes
v<<<<,{
\~./."
>"`=>!
 >!0<"}

Try it online!

{ gets the input, that will get looped around in the upper two rows, while outputting downwards the length \, its indices /. and a copy of itself ". It will only continue after ~. (batch) if n elements reach ~., whereas n will be the length.

We then take ! n copies of the current index i (starting with 0) and compare = them to the indices of the list. This returns either 1 or 0. We take the correspondent element of the copied list so many times, effectively filtering the others out. The next index then gets copied to the output "} and waits for the next iteration.


Most optimized algorithm for incrementing squares

The tag says "code-challenge", but I don't see any challenge. Just some mathematics we studied when I was about 12.

import java.util.*;

public class IncSquares
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int min = in.nextInt();
        int max = in.nextInt();

        int sq = min * min;
        System.out.print(sq);
        while (min < max) {
            sq += (min << 1) + 1;
            min++;
            System.out.print(", " + sq);
        }
        System.out.println();
    }
}


CJam, 57 56 49 47 bytes

Thanks to Sp3000 for saving 7 bytes.

q{_eu_el={Pmrmc1.mrml-50*mq*A+mo{48mr'̀+}*}|}/

Test it here.

Explanation

This uses Box–Muller for the normal distribution: the basic algorithm generates two uniform variables in the range [0,1), U and V and then computes two normally distributed values from them. We only need one and the simpler one is X = √(-2 ln U) cos(2πV). This generates a distribution with mean 0 and standard deviation 1, so we need to multiply it by 5 to correct the standard deviation and add 10 to correct the mean. We can also simplify the cosine, because omitting the 2 gives the same distribution. So we compute X = √(-50 ln U) cos(πV) + 10 before rounding to get the number of combining marks.

Here is the code:

q{          e# For each character in the input...
  _eu_el=   e#   Make an upper case and a lower case copy and check if they are equal.
  {         e#   If they aren't... (i.e. if this is a letter)
    Pmr     e#     Generate a uniformly random value in [0,π).
    mc      e#     Take the cosine.
    1.mr    e#     Generate a uniformly random value in [0,1).
    ml      e#     Take the natural logarithm.
    -50*    e#     Multiply by -50.
    mq*     e#     Take the square root and multiply by the cosine.
    A+      e#     Add 10.
    mo      e#     Round to nearest integer.
    {       e#     That many times...
      48mr  e#       Generate a uniformly random integer in [0,47].
      '̀+    e#       Add it to the first combining mark.
    }*
  }|
}/

This means we just dump all the characters and combining marks on the stack in the correct order, where they are printed automatically at the end of the program.


Draw an asterisk analog clock for hour N

Javascript (ES6), 105 76 65 bytes

F=N=>`  *
ab*12
 9@3
87654`.replace(/\w/g,y=>'0x'+y^N%12?' ':'*')
<!-- Snippet Demo: -->
N =  <input type="number" min="0" max="24" value="2" id="I" />
<button onclick="console.log(F(I.value))">Run</button>

-29 bytes:

Reduced size of minute and hour hand to 2 and 1 asterisks respectively. Smaller clock = less bytes :-P

-11 bytes:

Changed string comparison to numeric comparison.
y==(N%12).toString(16)?'*':' ' -> '0x'+y^N%12?' ':'*'

Original with longer hands: (105 94 bytes)

F=N=>`    *
a b * 1 2
  ab*12
  99@33
  87654
8 7 6 5 4`.replace(/\w/g,y=>'0x'+y^N%12?' ':'*')
<!-- Snippet Demo: -->
N =  <input type="number" min="0" max="24" value="2" id="I" />
<button onclick="console.log(F(I.value))">Run</button>


Perl, 166

@p=<>;/=/,$_{$`}=$' for split$",pop@p;$o='\w+';(map{($r
,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p),$_=$o=($_{$r}
+=','cmp$o)<0?do{$_{$r}=0;$b}:$,until/"/;say for eval,%_

Run with perl -M5.010 file.

It started wildly different, but I'm afraid it converged with the Ruby solution in many areas towards the end.  Seems like Ruby's advantage is "no sigils", and Perl's "better regex integration".

A bit of detail from the innards, if you don't read Perl:

@p=<>: read the whole machine description to @p
/=/,$_{$`}=$' for split$",pop@p: for each (for) assignment (split$") in the last machine description line (@p), locate equal sign (/=/) then assign value $' to hask %_ key $`
$o='\w+': initial state would be first one to match Perl regex "word characters"
until/"/: loop until we reach a termination state:

map{($r,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p: loop on machine description @p: when we're on the line matching current state (if/^$o :/), tokenize (/".*?"|\S+/g) the rest of the line $' to variables ($r,$o,$,,$b).  Trick: the same variable $o if used initially for label name and subsequently for operator.  As soon as the label matches, the operator overrides it, and as a label can't (reasonably) be named + or -, it never matches again.
$_=$o=($_{$r}+=','cmp$o)<0?do{$_{$r}=0;$b}:$,:- adjust target register $_{$r} up or down (ASCII magic: ','cmp'+' is 1 whereas ','cmp'-' is -1);- if the result is negative (<0?, can only happens for -)- then stay at 0 ($_{$r}=0) and return second label $b;- else return first (possibly sole) label $,
BTW, it's $, instead of $a so it can be glued to next token until with no whitespace in between.

say for eval,%_: dump report (eval) and contents of registers in %_


Python (335 bytes)

t=raw_input().replace(*': ').split();x='PMCE'.index(t[2][0]);t[0]=int(t[0])+x;print '%s:%s PM PDT' % tuple(t[:1]);x=t[0]*60+int(t[1]);print ['%s minutes until the pre-show!'%(360-x),'Pre-show started %s minutes ago; UNCOVERED is starting in %s minutes!'%((x-360),(420-x)), 'UNCOVERED started %s minutes ago!'%(x-420)][(x>360)+(x>420)]

Output:

1:00 MDT
2:00 PM PDT
240 minutes until the pre-show!

6:00 CDT
8:00 PM PDT
UNCOVERED started 60 minutes ago!

6:50 PDT
6:50 PM PDT
Pre-show started 50 minutes ago; UNCOVERED is starting in 10 minutes!


Pyth, 11 - 50% = 5.5 bytes

L?+IbY_yMbb

Try it online: Demonstration or Test Suite.

This defines a function y. The additional 3 bytes <newline>yQ simply call the function with the input list and therefore doesn't need to be counted towards the bytes total.

Explanation:

L?+IbY_yMbb
L             define a function y(b), that returns:
 ?+IbY           if b + [] == b (test if b is a list):
      _yMb           recursively call y on all elements in b, then reverse the list
          b      else: b


Jelly, 55 54 52 47 46 bytes

“=÷¡v⁺ʋiṂYR¤"bİɲ}Ñ1Ṇ⁴ẠV⁹yȥGẇ’“¿mŻ“p’Dx39jBo88V

There are more convoluted approaches in the revision history, but this simple one beats them all.

Try it online!

How it works

“=÷¡v⁺ʋiṂYR¤"bİɲ}Ñ1Ṇ⁴ẠV⁹yȥGẇ’

This is a numeric literal, encoded in bijective base 250, where the digits are taken from Jelly's code page. The chain's (left) argument and the return value are set to the encoded integer,
n := 0x21871c77d7d7af6fafafeff0c37f72ff7fbfbdbfdfef5edfeff8e3.

“¿mŻ“p’

A similar literal to the above one, but the second “ separates two encoded integers. The return value is replaced with the encoded array, [777711, 113].

Dx39

D converts the return value to decimal ([[7, 7, 7, 7, 1, 1], [1, 1, 3]]), then x39 repeats each individual integer/digit in the result 39 times. This yields a pair of arrays, which contains the digits before and after the 7-character high text, respectively. Let's call this array A.

jB

First, B converts the (left) argument n to binary. This yields the digits that form the 7-character high text, where each 88 has been replaced by 0.

Then, j joins the array A, using the binary array as separator.

o88

This performs logical OR with 88, replacing each 0 with 88.

V

We have the correct digits now, but in an array of 7's, 1's, 88's, and 3's. V implicitly turns this array into a string and then evals it, yielding a single integer.


Changeling, 2 bytes

That's two linefeeds. Valid Changeling must always form a perfect square of printable ASCII characters, so it cannot contain two linefeeds in a row.

The error is always a parser error and always the same:

This shape is unpleasant.

accompanied by exit code 1.

Try it online!


All squares that match a wildcard sequence

Mathematica, 44 bytes
Print@@@IntegerDigits[Range@1*^3^2]~Cases~#&

The input is a list of digits with a _ (no quotes) as a wildcard. e.g. {4, _, _, 6}
Explanation
Range@1*^3

Generate list {1, 2, 3, ... , 1000}
... ^2

Square it. (list of all squares from 1 to 1,000,000)
IntegerDigits[ ... ]

Split each square into a list of digits.
... ~Cases~#

Find the ones that match the pattern specified by the input.
Print@@@ ...

Print them.


Wolfram Language (Mathematica), 23 bytes
¯\__(ツ)_/¯   of course there is a built in for this...
"BD"~CountryData~"Flag"

but you can also get the same result with...
Wolfram Language (Mathematica), 78 bytes
Graphics@{(c=RGBColor)@"#006a4e",{0,0}~Cuboid~{5,3},c@"#f42a41",Disk[{9,6}/4]}

-8 bytes {first code) thanks to @Makonede for "Bangladesh" to "BD"
-4 bytes (second code) thanks to @att


J, 62 bytes

f=:3 :'~.(2#~2^y)([:<@~.@/:~((i.@!A.i.)y)|:(y#2)$])@#:i.2^2^y'

Try it online!

-3 bytes for anonymous function (removing f=:)

For each boolean function (truth table), generate its equivalence class, then remove duplicates.


Create a universal two-dimensional cellular automaton cell using two-way universal logic processors

114 107 gates

A diagram of the setup, with example inputs (link to full-sized image):

Created in Logisim

This uses a simple approach; first it counts the number of live neighbouring cells, and then checks if that number fulfills a birth/survival condition.


JavaScript (ES6), 53 49 bytes

f=(a,b)=>b<2||a>1&&(a&b&1?a<=b:a&1|~b&f(a/2,b/2))

Explanation:

If b is 1, then a precedes (or equals) b
Otherwise, if a is 1, then a does not precede b
Otherwise, if both a and b are odd, then use regular inequality check
Otherwise, if a is odd, then it precedes b
Otherwise, if b is odd, then a does not precede b
Otherwise, divide both a and b by 2 and try again.

Edit: Saved 2 bytes thanks to @Arnauld.


Output ISO8601 date string from seconds and nanoseconds

Bash + sed, 37, 59, 50 bytes

printf '%(%FT%T)T.%06d' $1 $[$2/1000]

printf "%(%FT%T)T.%06d" $1 ${2::-3}|sed s/\\.0*$//

Try it online!
8 bytes saved thanks to @DigitalTrauma


Brachylog, 25 bytes

hsS&t⊇.g;Sz{∋ʰ}ᵐhᵍ{tᵐc}ᵐp

Try some of the faster test cases online!

Extremely slow brute force, that I haven't verified on the longer test cases yet. It wouldn't surprise me if a clever implementation of a smarter algorithm turns out considerably shorter. Takes input as a list [entry,codes] through the input variable and outputs through the output variable if it succeeds. Seems to comply fully with the spec to the extent to which I've tested it at all.

The exact nature of the brute force is that for every substring of the entry (until there's a match), it tries every subset of the codes until it's possible to assign one code to each letter of the substring such that the letters assigned to each code taken in order form that code. The worst case complexity, where the worst case is failure, is something vaguely along the lines of \$O(x^22^yy^x)\$ with \$x\$ the length of the entry and \$y\$ the number of codes.


Depth:7 (logarithmic), 18x AND, 6x OR, 7x XOR, 31 gates (linear)

Let me calculate the digit sum in base four, modulo three:

circuit drawn in Logisim

Generalisation, formally (hopefully somewhat readable):

balance (l, h) = {
  is1: l & not h,
  is2: h & not l,
}

add (a, b) =
  let aa = balance (a.l, a.h)
      bb = balance (b.l, b.h)
  in  { l:(a.is2 & b.is2) | (a.is1 ^ b.is1),
        h:(a.is1 & b.is1) | (a.is2 ^ b.is2)}

pairs [] = []
pairs [a] = [{h:0, l:a}]
pairs [rest.., a, b] = [pairs(rest..).., {h:a, l:b}]

mod3 [p] = p
mod3 [rest.., p1, p2] = [add(p1, p2), rest..]

divisible3 number =
  let {l: l, h: h} = mod3 $ pairs number
  in  l == h

now in english:

While there are more than two bits in the number, take two lowest pairs of bits and sum them modulo 3, then append the result to the back of the number, then return if the last pair is zero modulo 3. If there is an odd number of bits in the number, add an extra zero bit to the top, then polish with constant value propagation.

Appending to the back instead of to the front ensures the addition tree is a balanced tree rather than a linked list. This, in turn, ensures logarithmic depth in the number of bits: five gates and three levels for pair cancellation, and an extra gate at the end.

Of course, if approximate planarity is desired, pass the top pair unmodified to the next layer instead of wrapping it to the front. This is easier said than implemented (even in pseudocode), however. If the number of bits in a number is a power of two (as is true in any modern computer system as of March 2014), no lone pairs will occur, however.

If the layouter preserves locality / performs route length minimisation, it should keep the circuit readable.

This Ruby code will generate a circuit diagram for any number of bits (even one). To print, open in Logisim and export as image:

require "nokogiri"

Port = Struct.new :x, :y, :out
Gate = Struct.new :x, :y, :name, :attrs
Wire = Struct.new :sx, :sy, :tx, :ty

puts "Please choose the number of bits: "
bits = gets.to_i

$ports = (1..bits).map {|x| Port.new 60*x, 40, false};
$wires = [];
$gates = [];

toMerge = $ports.reverse;

def balance a, b
y = [a.y, b.y].max
$wires.push Wire.new(a.x   , a.y , a.x   , y+20),
          Wire.new(a.x   , y+20, a.x   , y+40),
          Wire.new(a.x   , y+20, b.x-20, y+20),
          Wire.new(b.x-20, y+20, b.x-20, y+30),
          Wire.new(b.x   , b.y , b.x   , y+10),
          Wire.new(b.x   , y+10, b.x   , y+40),
          Wire.new(b.x   , y+10, a.x+20, y+10),
          Wire.new(a.x+20, y+10, a.x+20, y+30)
$gates.push Gate.new(a.x+10, y+70, "AND Gate", negate1: true),
          Gate.new(b.x-10, y+70, "AND Gate", negate0: true)
end

def sum (a, b, c, d)
y = [a.y, b.y, c.y, d.y].max
$wires.push Wire.new(a.x   , a.y , a.x   , y+40),
          Wire.new(a.x   , y+40, a.x   , y+50),
          Wire.new(a.x   , y+40, c.x-20, y+40),
          Wire.new(c.x-20, y+40, c.x-20, y+50),
          Wire.new(b.x   , b.y , b.x   , y+30),
          Wire.new(b.x   , y+30, b.x   , y+50),
          Wire.new(b.x   , y+30, d.x-20, y+30),
          Wire.new(d.x-20, y+30, d.x-20, y+50),
          Wire.new(c.x   , c.y , c.x   , y+20),
          Wire.new(c.x   , y+20, c.x   , y+50),
          Wire.new(c.x   , y+20, a.x+20, y+20),
          Wire.new(a.x+20, y+20, a.x+20, y+50),
          Wire.new(d.x   , d.y , d.x   , y+10),
          Wire.new(d.x   , y+10, d.x   , y+50),
          Wire.new(d.x   , y+10, b.x+20, y+10),
          Wire.new(b.x+20, y+10, b.x+20, y+50)
$gates.push Gate.new(a.x+10, y+90, "XOR Gate"),
          Gate.new(b.x+10, y+80, "AND Gate"),
          Gate.new(c.x-10, y+80, "AND Gate"),
          Gate.new(d.x-10, y+90, "XOR Gate")
$wires.push Wire.new(a.x+10, y+90, a.x+10, y+100),
          Wire.new(b.x+10, y+80, b.x+10, y+90 ),
          Wire.new(b.x+10, y+90, a.x+30, y+90 ),
          Wire.new(a.x+30, y+90, a.x+30, y+100),
          Wire.new(d.x-10, y+90, d.x-10, y+100),
          Wire.new(c.x-10, y+80, c.x-10, y+90 ),
          Wire.new(c.x-10, y+90, d.x-30, y+90 ),
          Wire.new(d.x-30, y+90, d.x-30, y+100)
$gates.push Gate.new(d.x-20, y+130, "OR Gate"),
          Gate.new(a.x+20, y+130, "OR Gate")
end

def sum3 (b, c, d)
y = [b.y, c.y, d.y].max
$wires.push Wire.new(b.x   , b.y , b.x   , y+20),
          Wire.new(b.x   , y+20, b.x   , y+30),
          Wire.new(b.x   , y+20, d.x-20, y+20),
          Wire.new(d.x-20, y+20, d.x-20, y+30),
          Wire.new(c.x   , c.y , c.x   , y+60),
          Wire.new(c.x   , y+60, b.x+30, y+60),
          Wire.new(b.x+30, y+60, b.x+30, y+70),
          Wire.new(d.x   , d.y , d.x   , y+10),
          Wire.new(d.x   , y+10, d.x   , y+30),
          Wire.new(d.x   , y+10, b.x+20, y+10),
          Wire.new(b.x+20, y+10, b.x+20, y+30),
          Wire.new(b.x+10, y+60, b.x+10, y+70)
$gates.push Gate.new(b.x+10, y+60 , "AND Gate"),
          Gate.new(d.x-10, y+70 , "XOR Gate"),
          Gate.new(b.x+20, y+100, "OR Gate" )
end

while toMerge.count > 2
puts "#{toMerge.count} left to merge"
nextToMerge = []
while toMerge.count > 3
 puts "merging four"
 d, c, b, a, *toMerge = toMerge
 balance a, b
 balance c, d
 sum *$gates[-4..-1]
 nextToMerge.push *$gates[-2..-1]
end
if toMerge.count == 3
 puts "merging three"
 c, b, a, *toMerge = toMerge
 balance b, c
 sum3 a, *$gates[-2..-1]
 nextToMerge.push *$gates[-2..-1]
end
nextToMerge.push *toMerge
toMerge = nextToMerge
puts "layer done"
end

if toMerge.count == 2
b, a = toMerge
x = (a.x + b.x)/2
x -= x % 10
y = [a.y, b.y].max
$wires.push Wire.new(a.x , a.y , a.x , y+10),
          Wire.new(a.x , y+10, x-10, y+10),
          Wire.new(x-10, y+10, x-10, y+20),
          Wire.new(b.x , b.y , b.x , y+10),
          Wire.new(b.x , y+10, x+10, y+10),
          Wire.new(x+10, y+10, x+10, y+20)
$gates.push Gate.new(x, y+70, "XNOR Gate")
toMerge = [$gates[-1]]
end

a = toMerge[0]
$wires.push Wire.new(a.x, a.y, a.x, a.y+10)
$ports.push Port.new(a.x, a.y+10, true)

def xy (x, y)
"(#{x},#{y})"
end
circ = Nokogiri::XML::Builder.new encoding: "UTF-8" do |xml|
xml.project version: "1.0" do
xml.lib name: "0", desc: "#Base"
xml.lib name: "1", desc: "#Wiring"
xml.lib name: "2", desc: "#Gates"
xml.options
xml.mappings
xml.toolbar do
  xml.tool lib:'0', name: "Poke Tool"
  xml.tool lib:'0', name: "Edit Tool"
end #toolbar
xml.main name: "main"
xml.circuit name: "main" do
  $wires.each do |wire|
    xml.wire from: xy(wire.sx, wire.sy), to: xy(wire.tx, wire.ty)
  end #each
  $gates.each do |gate|
    xml.comp lib: "2", name: gate.name, loc: xy(gate.x, gate.y) do
      xml.a name: "facing", val: "south"
      xml.a name: "size", val: "30"
      xml.a name: "inputs", val: "2"
      if gate.attrs
        gate.attrs.each do |name, value|
          xml.a name: name, val: value
        end #each
      end #if
    end #comp
  end #each
  $ports.each.with_index do |port, index|
    xml.comp lib: "1", name: "Pin", loc: xy(port.x, port.y) do
      xml.a name: "tristate", val: "false"
      xml.a name: "output",   val: port.out.to_s
      xml.a name: "facing",   val: port.out ? "north" : "south"
      xml.a name: "labelloc", val: port.out ? "south" : "north"
      xml.a name: "label",    val: port.out ? "out" : "B#{index}"
    end #port
  end #each
end #circuit
end #project
end #builder

File.open "divisibility3.circ", ?w do |file|
file << circ.to_xml
end

puts "done"

finally, when asked to create an output for 32 bits, my layouter generates this. Admittedly, it's not very compact for very wide inputs:


Python 2, 174 bytes

x,y=input()
a=abs(x)
b=abs(y)
r=a%b*10
L=[]
M=''
while~-(r in L):L+=r,;M+=str(r/b);r=r%b*10
i=L.index(r)
t=M[:i]+"(%s)"%M[i:]*(M[i:]>'0')
print"-%d."[x*y>=0:(t>'')+3]%(a/b)+t

I'm not quite convinced about the validity of this answer, but it's worked for the test cases above and other test cases I've thrown at it. It looks like a right mess though, so I'm sure there's plenty of room for golfing.

The initial setup takes absolute values of both arguments to ensure that we're dealing with nonnegative numbers (saving the sign calculation for later), and delegates the quotient part of the result to Python's arbitrary precision arithmetic. The fractional part is done with the grade-school division algorithm until we get a repeat in the remainder. We then look up when we last saw this repeat in order to get the period, and construct the string accordingly.

Note that the algorithm's actually quite slow due to the O(n) in operation, but it's fast enough for the examples.


Husk, 9 8 bytes

Ö†€¨tfṡn

Try it online!

Algorithm "inspired" by recursive's Stax answer (I've just changed the lookup string a bit), go upvote him!

The trick is mapping each letter to its position in the string tfsen (compressed at the end of this program). Husks lists are 1-based, and missing items return 0, so we get this mapping:

"one"        [0,5,4]
"two"        [1,0,0]
"three"      [1,0,0,4,4]
"four"       [2,0,0,0]
"five"       [2,0,0,4]
"six"        [3,0,0]
"seven"      [3,4,0,4,5]
"eight"      [4,0,0,0,1]
"nine"       [5,0,5,4]

As you can see, the lists are perfectly ordered.

In order to be clear, here's how list comparison works in Husk (and in many other languages):

If one of the two lists is empty, that's the smaller one.
If the first elements of the two lists are different, the one with the smaller first element is the smaller list.
Otherwise, discard the first element from both lists and go back to point 1.


Python 2, 93 89 84 83 82 78 bytes

l=input()
for c in l[1]:l=[x.replace(c,c.lower(),c in l[0])for x in l]
print l

Try it online!

Takes input as two strings. Prints two strings

Saved

-5 bytes, thanks to Dead Possum
-4 bytes, thanks to Lynn


Haskell, 49 bytes

import Data.List
f[_]=0
f c=1+f(length<$>group c)

Try it online!


Total Score 669 683 753
Pattern 1 (379 steps):
x = 100, y = 94
97b2o$96bo2bo$97bobo$98bo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$3o$2bo$bo!

Pattern 2 (126 steps):
x = 11, y = 2
o5b2obo$3bo$2b2o2bo2b2o!

Pattern 1 + Pattern 2 (248 steps):
x = 112, y = 94
97b2o$96bo2bo$97bobo$98bo2bo5b2obo$104bo$103b2o2bo2b2o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$3o$2bo$bo!

Pattern 1 is a self-destructing glider + loaf combination where the glider and loaf are spaced as far apart as possible.
Pattern 2 is the result of searching for random disappearing patterns which can be placed next to pattern 1 to destroy the loaf, giving a valid solution to the puzzle. I generated a large number and took the one with the best score.
I'm sure its possible to do better by adding an independent diehard to the far corner of pattern 2 (or even pattern 1), but I'm done for now.


C, 315 302 bytes
t,i;double o,w,h,x,y,k,a,b,c;double g(N,S)double N,S[][2];{for(t=0;t<N;t++)k+=S[t][1];k/=N;for(i=0;i<9;i++){o=w=h=0;for(t=0;t<N;t++)x=S[t][0],y=S[t][1],a=y-k,c=k*k-2*k*y+x*x+y*y,o+=-a/sqrt(x*x+a*a),w+=x*x/pow(c,1.5),h+=3*x*x*a/pow(c,2.5);a=h/2;b=w-h*k;c=o-w*k+a*k*k;k=(-b+sqrt(b*b-4*a*c))/h;}return k;}

This is far from pretty, and it's not short either. I figured since I'm not going to win the length contest, I can try to win the (theoretical) accuracy contest! The code is probably an order of magnitude or two faster than the bruteforce solution, and relies on a bit of mathematical tomfoolery.
We define a function g(N,S) which takes as input the number of houses, N, and an array of houses S[][2].
Here it is unraveled, with a test case:
t,i;
double o,w,h,x,y,k,a,b,c;
double g(N,S)double N,S[][2];{
    /* Initially, let k hold the geometric mean of given y-values */
    for(t=0;t<N;t++)
        k+=S[t][1];
    k/=N;

    /* We approximate 9 times to ensure accuracy */
    for(i=0;i<9;i++){
        o=w=h=0;
        for(t=0;t<N;t++)
            /* Here, we are making running totals of partial derivatives */
            /* o is the first, w the second, and h the third*/
            x=S[t][0],
            y=S[t][1],
            a=y-k,
            c=k*k-2*k*y+x*x+y*y,
            o+=-a/sqrt(x*x+a*a),
            w+=x*x/pow(c,1.5),
            h+=3*x*x*a/pow(c,2.5);
        /* We now use these derivatives to find a (hopefully) closer k */
        a=h/2;
        b=w-h*k;
        c=o-w*k+a*k*k;
        k=(-b+sqrt(b*b-4*a*c))/h;
    }
    return k;
}
/* Our testing code */
int main(int argc, char** argv) {
    double test[2][2] = {
        {5.7, 3.2},
        {8.9, 8.1}
    };
    printf("%.20lf\n", g(2, test));
    return 0;
}

Which outputs:
5.11301369863013732697

Warning: Knowledge of some calculus may be required for a complete understanding!
So, let's talk about the math.
We know the distance from our desired point (0, k) and a house i:

And thus the total distance D from n houses can be defined as follows:

What we would like to do is minimize this function by taking a derivative with respect to k and setting it equal to 0. Let's try it. We know that the derivatives of D can be described as follows:

But the first partial derivative of each Di is pretty bad...

Unfortunately, even with n == 2, setting these derivatives to 0 and solving for k becomes disastrous very quickly. We need a more robust method, even if it requires some approximation.
Enter Taylor Polynomials.
If we know the value of D(k0) as well as all of D's derivatives at k0, we can rewrite D as a Taylor Series:

Now, this formula's got a bunch of stuff in it, and its derivatives can get pretty unwieldy, but we now have a polynomial approximation of D!
Doing a little bit of calculus, we find the next two derivatives of D by evaluating the derivatives of Di, just as before:

By truncation and evaluating the derivatives, we may now approximate D as a 3rd degree polynomial of the form:

Where A, B, C, D are simply real numbers.
Now this we can minimize. When we take a derivative and set it equal to 0, we will end up with an equation of the form:

Doing the calculus and substitutions, we come up with these formulas for a, b, and c:

Now our problem gives us 2 solutions given by the quadratic formula:

The entire formula for k would be a massive burden to write out, so we do it in pieces here and in the code.
Since we know that the higher k will always result in the minimum distance of our approximate D (I have a truly marvelous proof of this, which the margin of this paper is insufficient to contain...) we do not even have to consider the smaller of the solutions.
One final problem remains. For accuracy purposes, it is necessary that we begin with a k0 that is at least in the ballpark of where we expect the answer to be. For this purpose, my code chooses the geometric mean of the y-values of every house.
As a fail-safe, we repeat the entire problem again 9 times, replacing k0 with k at every iteration, to ensure accuracy.
I haven't done the math about how many iterations and how many derivatives are truly necessary, but I've opted to err on the side of caution until I can confirm accuracy.
If you made it through that with me, thank you so much! I hope you understood, and if you spot any mistakes (of which there are likely many, I'm very tired), please let me know!


Generate basis elements of the Steenrod algebra

05AB1E, 16 12 bytes

Saved 4 bytes thanks to Grimy

Åœíʒx¦@P}ʒÆ@

Try it online!

Explanation

Åœ              # integer partitions
  í             # reverse each
   ʒ    }       # filter, keep only elements true under:
    x           # each element doubled
     ¦          # remove the first element in the doubled list
      @         # compare with greater than or equal with the non-doubled
       P        # product
         ʒ      # filter, keep only elements true under:
          Æ     # reduce by subtraction
           @    # compare with greater than or equal to second input


Manufactoria: generate the slowest possible accepting program

~1023 iterations ~1015 iterations ~108 iterations

http://pleasingfungus.com/Manufactoria/?lvl=32&code=g9:7f2;b12:8f2;p13:8f5;p11:8f3;r14:8f0;q11:10f3;q13:7f1;y13:9f1;r10:10f1;c12:9f2;c9:9f2;i11:9f7;i10:9f4;c9:8f3;i10:8f2;c14:9f0;c15:9f0;c15:8f3;c15:7f3;c14:7f2;g12:7f0;c11:7f3;c10:7f2;q9:6f7;r10:6f1;r9:5f3;c11:6f0;r10:5f2;r11:5f1;r9:4f3;r10:4f0;r11:4f0;y12:5f2;y13:5f2;y14:5f3;y14:6f0;y13:6f0;y12:6f0;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0;

The machine is basically an odometer running in base three, using the red, blue and yellow symbols to stand for the digits 0, 1, and 2 respectively. The green symbol is used to mark the end of the number. At the start, the tape is initialized with 49 red symbols. This is done by the parts in the top three rows of the machine. The bottom four rows handle the task of incrementing the number in a loop. On each iteration, the two branch cells on left-hand side work out how to apply the increment to current number, and then the branch cells on the right-hand side copy the remaining, unaffected digits.

Previously I've tried to estimate the machine's running time, were it allowed to run to completion, but at this level it makes more sense to just go by the number of iterations. Roughly speaking, it takes about a minute to complete one iteration -- but even if it took a second that would only decrease the running time by a single order of magnitude.


05AB1E, 10 bytes

LRL˜Íoî.¥ï

Try it online!

L                 # range [1..input]
 R                # reversed
  L               # convert each to a range: [[1..input], [1..input-1], ..., [1]]
   ˜              # flatten
    Í             # subtract 2 from each
     o            # 2**each
      î           # round up (returns a float)
       ï          # convert to integer
        .¥        # undelta


List all palindromic prime dates between 0000-01-01 and 99999-12-31

Ruby, 144 141 bytes (134+7 for the -rprime flag)

Saved 3 bytes thanks to benj2240!

('01'..'12').map{|m|('01'..'31').map{|d|(?0..?9).map{|k|q=m+d
y=q.reverse+k
r=y+q
Time.new(y,m,d).day==d.to_i&&r.to_i.prime?&&(p r)}}}

Try it online!

The algorithm:

generate all possible MMDD combinations, from "0101" to "1231"
generate all years for that date that would result in a palindrome, by reversing the MMDD string and adding in the middle, in turn, all chars in the (0..9) range
check if that is a valid date by creating a Time instance with the given y, m, d values. If the resulting time object has a #day value equal to d, then that was a valid date. Otherwise, it would shift the date (for example, Time.new 2018,2,30 returns 2018-03-02).
check if the valid palindrome date is also a prime and display it if it is.

The inner loop was initially a function that was called for each element in the (?0..?9) range, as well as for the empty string.

Since the empty string produced no results (there are no valid 8 digit prime palindromes), I decided to remove it and refactor to this version.


Jelly, 14 10 bytes

(no doubt there is golfing to do here! - yep...)
-4 bytes thanks to @Dennis - replace check for greater than n by using a range

ÆRẆP€ḟÆRfR

Note - this is both extremely inefficient and the results are unsorted.

Test it at TryItOnline

How?

ÆRẆP€ḟÆRfR - main link takes an argument, n
ÆR    ÆR   - primes up to n
  Ẇ        - all sublists
   P€      - product for each
     ḟ     - filter out the primes (since the sublists include those of lnegth 1)
        fR - filter out any not in range [1,N]
             (yep, it's calculating all products of primes up to n - gross)


Arbitrary-Length Ternary Squarefree Words

Python, 94

n=input()
x=[0]
exec"x+=[1-y for y in x];"*n
print''.join('ABC'[x[i+1]-x[i]]for i in range(n))

It uses the Thue–Morse sequence method from wikipedia.

Efficient version (100 chars):

n=input()
x=[0]
while x==x[:n]:x+=[1-y for y in x]
print''.join('ABC'[x[i+1]-x[i]]for i in range(n))


Generating minimal regular expression character classes

No answers after a few days, so thought I'd have a go. Found it trickier than expected, so the answer's pretty long, but I'm reasonably confident it works. Should be able to trim it a fair bit more.
Python 3.8, 431 405 410 bytes

import re,itertools as I
B,M,C,P="\-]^"
s=sorted;x=s({*input()})
d=[ord(x)-i for i,x in enumerate(x)];l=[];i=0
for _,g in I.groupby(d):n=len([*g]);l+=[[x[i]+M+x[i+n-1]],x[i:i+n]][n<4];i+=n
o="".join(s(l,key=lambda i:2*(M in i[::2])+(P in i)-3*(i[0]==M<C not in x)-2*(C in i)))
print("["+re.sub(".",lambda m:B*((x:=m.group())==B or x==P==o[0]or x==M<M*2==o[(i:=m.start()):i+2]in o[1:-1]or x==C in o[1:])+x,o)+C)

Try it online!
Explanation
The overall approach is to:

Split the letters into ranges of length at least 4 and individual characters. Note that ranges of length 3 are never necessary (eg. "[abc]" is the same length as "[a-c]" and "[]\\[]" is the same length "[[-\]]") and are sometimes worse (e.g. "]-./" is shorter as  "[]./-]" than as "[]\--/]" or "[--/\]]").

Sort the letters and ranges, so "]" goes first, otherwise "-" goes first, otherwise "-" goes last, and with "^" as late as posssible. There is no conflict between putting "]" first and "-" last since "]--" is not a valid range.

Escape as necessary: \ always, ] unless it's first, ^ if it's first, and - if it's in the middle (which will only happen if it's the beginning of a range).

Extra test cases
"-^"      => "[-^]"
"-4]"     => "[]4-]"
"abcde^"  => "[a-e^]"
"XYZ[\\]" => "[X-\]]"
"-./0]"   => "[]\--0]"
"+*,-^"   => "[\^*--]"
"^_`a"    => "[\^-a]"


Arguably perfect score

There are some possible loopholes in the scoring system. In particular,

  8 points for every loop statement (including loops in the called functions. You can presume that any called function has no more than one loop)

According to PHP documentation,

  array() is a language construct used to represent literal arrays, and not a regular function.

So it's arguable that

$hash = array(
    '' => 0,
    '.-' => -1,
    ...
);
return $hash[$morse];

contains no called functions and should score a perfect 100 + (137 - 1) = 236 points.


Pyth: 34 33 bytes

Sml{dCuS?+G,hhGtehGHm,_ekhkGQ],ZZ

Input is a list of ones and zeros, like in the question. Try it online: Pyth Compiler/Executor

Explanation:

It's a one-on-one translation of the following Python 2 code (126 bytes).

print sorted(map(len,map(set,zip(*reduce(lambda s,i:([[-b,a]for a,b in s],s+[[min(s)[0],min(s)[1]-1]])[i],input(),[[0,0]])))))

I create a list of coordinates of the single magnets. This is initialized with the magnet [0,0]. Then for each of the integers of the blueprint I manipulate the list in the following way. If the next integer is 0, I rotate the sculpture by changing the coordinates for each magnet [a,b] to [-b,a] (basically multiplying with a rotation matrix). If the next integer is a 1, I search for the minimal piece [a,b] (which is automatically the lowest magnet of the leftmost column) and append the magnet [a,b-1] to the list.

After all the input is processed, I create 2 sets (for removing duplicates), one for the x-values and one for the y values, and print the sizes of them in sorted order.

Sml{dCuS?+G,hhGtehGHm,_ekhkGQ],ZZ
                             ],ZZ  starting list G=[(0,0)]
      u                     Q],ZZ  for H in input(): manipulate G
       S                              Sort G after each manipulation
        ?          H                  G = ... if H==1 else ...
                    m,_ekhkG            [(-b,a) for a,b in G)] (rotate)
         +G,hhGtehG                     G+[(G[0][0],G[0][1]-1)]
                                        (G[0] is the lowest magnet in the leftmost column)
     C                             Zip the coords together
                                    (creates 2 lists, x- and y-coords)
 ml{d                              for each of those list compute number of unique values
S                                  sort and print

An idea for improvement: Using complex numbers as coords for the magnets. A rotation is just a multiplication by j and subtracting j from the lowest magnet in the leftmost column. Sadly finding this lowest leftmost magnet takes way too many chars in Python, not even talking of finding the rectangle.


Ostrich, 46 45 chars

Don't have a version number in the header because this is actually just the latest commit. I added the O (ascii code to string) operator after releasing the latest version (but still before this challenge was posted).

{a95,{32+O}%:d3@{:x\.3@?3@\+\x-x\+}/;{d=}%s*}

Explanation:

a             this is the "r" array (a is short for [], empty array)
95,{32+O}%:d  this is the "d" array
3@{...}/      for each character in the input (as an "argument")...
  :x            store in variable x (stack is now [r d c])
  \.3@?         find index in d     (stack is now [r d idx])
  3@\+          append index to r   (stack is now [d modified_r])
  \x-           remove char from d, and then...
  x\+           prepend char to d   (stack is now [modified_r modified_d])
;             throw away modified_d
{d=}%         map r to indices of (original) d
s*            join (s is short for ``, empty string)


Pyth - 29 bytes
Brute force.
hf&!@JsCBTsm.>RdJStQ.A{IMJ^.p

Does not finish online even for n=4, but you can try it out locally, or run this modified version online for one more byte.


Fastest way to compute order of magnitude in x86 assembly

7 cycles, constant time
Here's a solution based on my answer to this SO Question.
It uses BSR to count how many bits are needed to hold the number. It looks up how many decimal digits needed to represent the largest number that many bits can hold. Then it subtracts 1 if the actual number is less than the nearest power of 10 with that many digits.

    .intel_syntax noprefix
    .globl  main
main:
    mov rdi, 1000000000000              #;your value here
    bsr rax, rdi
    movzx   eax, BYTE PTR maxdigits[1+rax]
    cmp rdi, QWORD PTR powers[0+eax*8]
    sbb al, 0
    ret
maxdigits:
    .byte   0
    .byte   0
    .byte   0
    .byte   0
    .byte   1
    .byte   1
    .byte   1
    .byte   2
    .byte   2
    .byte   2
    .byte   3
    .byte   3
    .byte   3
    .byte   3
    .byte   4
    .byte   4
    .byte   4
    .byte   5
    .byte   5
    .byte   5
    .byte   6
    .byte   6
    .byte   6
    .byte   6
    .byte   7
    .byte   7
    .byte   7
    .byte   8
    .byte   8
    .byte   8
    .byte   9
    .byte   9
    .byte   9
    .byte   9
    .byte   10
    .byte   10
    .byte   10
    .byte   11
    .byte   11
    .byte   11
    .byte   12
powers:
    .quad   0
    .quad   10
    .quad   100
    .quad   1000
    .quad   10000
    .quad   100000
    .quad   1000000
    .quad   10000000
    .quad   100000000
    .quad   1000000000
    .quad   10000000000
    .quad   100000000000
    .quad   1000000000000

Compiles on GCC 4.6.3 for ubuntu and returns the value in the exit code.
I'm not confident interpreting that cycles table for any modern processor, but using @DigitalTrauma's method, on the Nehalim processor, I get 7?
ins        uOps Latency
---        -    -
BSR r,r  : 1    3
MOVZX r,m: 1    -
CMP m,r/i: 1    1
SBB r,r/i: 2    2


A keyboard so real you can almost TASTE it

V, 189, 179, 175, 164, 161, 157, 155, 149, 145, 141, 135 bytes

¬19É`A0-=BS´
TAB³ qwertyuiop[]\
CAPS³ asdfghjkl;'ENTER
SHIFT´ ÄJizxcvbnm,./Í„A-Z ]/Õ&
ÍÓ«ü$/|||&
òÙÓ„|]/_
ÙÓ×«/Ü|¯
kkPÓ/_ _
kòÎx$x

Try it online!

This answer is now tweetable!

Watch it run! This is a slightly modified version that updates as it runs so you can sorta see how it works. This is an outdated version since I haven't gotten around to re-recording it yet, but the general approach is identical.

This is probably the longest V answer ever written. It certainly didn't help that V's interpreter is extremely slow. It took me around an hour to write the first revision, but I've been repeatedly coming back to it to shave a couple bytes off each time. Since the full keyboard is 1215 bytes, currently this answer is 91% shorter than the output, so I'm pretty happy with the results.

Since this contains some unprintable characters, and a lot of gross non-ASCII, here's a hexdump:

00000000: ac31 39c9 6041 302d 3d42 53b4 200a 5441  .19.`A0-=BS. .TA
00000010: 42b3 2071 7765 7274 7975 696f 705b 5d5c  B. qwertyuiop[]\
00000020: 0a43 4150 53b3 2061 7364 6667 686a 6b6c  .CAPS. asdfghjkl
00000030: 3b27 454e 5445 5220 0a53 4849 4654 b420  ;'ENTER .SHIFT.
00000040: 1bc4 4a69 7a78 6376 626e 6d2c 2e2f 1bcd  ..Jizxcvbnm,./..
00000050: 8441 2d5a 205d 2fd5 2620 0acd d3ab fc24  .A-Z ]/.& .....$
00000060: 2f7c 7c7c 260a f2d9 d384 7c5d 2f5f 0ad9  /|||&.....|]/_..
00000070: d3d7 ab2f dc7c af0a 6b6b 50d3 2f5f 205f  .../.|..kkP./_ _
00000080: 0a6b f2ce 7824 78                        .k..x$x

How the heck does it work?

Alright, this explanation is gonna be a doozy. You ready? First off, we need enter the letters so we can build up the keys around them. This is

¬19É`A0-=BS´
TAB³ qwertyuiop[]\
CAPS³ asdfghjkl;'ENTER
SHIFT´ <esc>ÄJizxcvbnm,./<esc>

Which inserts:

`1234567890-=BS
TAB   qwertyuiop[]\
CAPS   asdfghjkl;'ENTER
SHIFT    zxcvbnm,./SHIFT

It enters it pretty straightforward, but there are a few tricks that we use to save characters. For example, ¬19 enters "123456789", ³ enters three spaces, and we duplicate the shift so that we don't need to enter it multiple times.

Note how the letters are lowercase here. This is so that we can easily distinguish between the uppercase keys like "ENTER" and the single letters. Writing them this way makes it easier to tell which characters to put a bar before, and only adds one byte to convert them to lowercase later. So we do a substitute command to convert these to uppercase, and add one space after each of them:

Í               " Globally replace
 [^A-Z ]        " Anything but a uppercase alphabet character or a space
        /       " with
         Õ&     " The matched pattern made uppercase, followed by a space

Now, we take each key sequence (any run of non-whitespace), and put three bars before and after them:

Í           " Globally replace
 Ó«         "   Any number of non-space characters
   ü        "   or
    $       "   an end of line
     /      " with
      |||   "    Three bars
         &  "    And the matched pattern

At this point, the buffer looks like this:

|||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= |||BS    |||
|||TAB   |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ |||
|||CAPS   |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER |||
|||SHIFT    |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT    |||

Having three bars on the first and last columns is actually very convenient and ends up saving many bytes in the long run.

And here is where we run one giant loop. This will convert something like this:

|||SHIFT    |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT    |||

into something like this:

 ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________
||SHIFT    |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT    ||
||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________||
|/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\|

Everything between two instances of ò will run until an error happens, which will happen when we try to go up into a line that does exist yet. Since we just ran a globally substitute command, our cursor is on the last line, and we'll transform these working our way up.

ò         " Recursively:
 Ù        "   Duplicate this line
  Ó       "   Substitute all on this line:
   [^|]   "     Anything but a bar
       /  "   With:
        _ "     An underscore

This is the

|||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________|||

line.

Ù         "   Duplicate this line
 Ó        "   Subsitute all on this line:
  ×«      "     A run of *non-word characters* (that is, [^0-9A-Za-z_])
    /     "   With:
     Ü|¯  "     '\|/'

This is the

\|/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\|/

Line.

kk        "   Move up two lines (to the original text with "SHIFT")
  P       "   Paste the last line we duplicated (the one with all the underscores)
   Ó      "   Substitute:
          "     Since we don't give any regex here, it re-uses the last one
          "     (a run of *non-word* characters)
    /     "   With:
     _ _  "     '_ _'

This is the:

_ ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ _

Line.

k         "   Move up a line (this will throw an error, breaking the loop when we're done)
 ò        " Endwhile

Now we have the full keyboard, but each line contains either an extra bar, an extra slash (forward or backward), or an extra underscore. Super easy fix

Î             " On every line:
 x            "   Delete a character
  $           "   Move to the end of the line
   x          "   and delete another character

After all that madness, the buffer is implicitly printed.


WhiteSpace, 146 bytes

Since all whitespace may occur everywhere, this is is just the golfed Hello World program. Since whitespace doesn't show properly here, take the following program and replace all . by spaces, > by tabs and ; by newlines.

...;..>>..>.>.;..>>>>;...>;...>>>;...>..;..>>.>..;..>>..>.>>;..>>>>>>>;...>..;...>;.;...>>>.;..>>...>>;;..;.;.;>.>;...>>.>.>>;>...>;..;.;;;..>;;;;

Note

I didn't golf this, LukStorms did. His answer can be found here.


Find the area of the largest convex polygon


Haskell: 10 characters

y f=f$y f

Example of use to create recursive definitions of factorial or nth-Fibonacci:

> map ( y(\f n->if n <= 1 then 1 else n*f(n-1)) ) [1..10]
[1,2,6,24,120,720,5040,40320,362880,3628800]

> map ( y(\f n->if n <= 1 then 1 else f(n-1)+f(n-2)) ) [0..10]
[1,1,2,3,5,8,13,21,34,55,89]

Though, a more common way to use y would be to generate these sequences directly, rather than as functions:

> take 10 $ y(\p->1:zipWith (*) [2..] p)
[1,2,6,24,120,720,5040,40320,362880,3628800]

> take 11 $ y(\f->1:1:zipWith (+) f (tail f))
[1,1,2,3,5,8,13,21,34,55,89]

Of course, with Haskell, this is a bit like shooting fish in a barrel! The Data.Function library has this function, called fix, though implemented somewhat more verbosely.


Mathematica, 24 23 bytes
Saved 1 byte thanks to Greg Martin
D[1/#2,{x,#}]/#!/.x->0&

Pure function with two arguments # and #2. Assumes the polynomial #2 satisfies PolynomialQ[#2,x]. Of course there's a built-in for this:
SeriesCoefficient[1/#2,{x,0,#}]&


For a given period, getting the smallest list of dates, using jokers

PHP, 541 343 bytes
I wanted to get the algorithm working in the first place; but golfing it down was actually far more fun than I expected (especially browsing the supported date & time formats).
Three major actions saved about 130 bytes; but the 70 bytes from minor golfings
(which also rendered one of the large steps obsolete) carried a lot of fun.
for($a=($f=strtotime)($argv[1]);!$p=$a>$z=$f($argv[2]);$a+=86400){$x=$z<$e=$f(Dec31,$a);(101<$q=date(md,$a))?$q-1001|$x?:$a=$e+$p="1*":($x?($t=$f(IX30,$a))>$z?:$a=$t+$p="0*":$a=$e+$p="*");$p?:($q%100>1|$z<($t=$f(date(Ymt,$a)))?$q%10>0&$q%100>1|$z<($t=min($t,$a+777600))?:$a=$t+$p="m-$q[2]*":$a=$t+$p="m-*");echo date("Y-".($p?:"m-d"),$a),"
";}

takes input from command line arguments. Run with -nror test it online.
notes

prints Y-m-3* for Y-m-30; add 7 bytes to fix: Insert |$a==$t after 777600)).
throws warnings in PHP 7.1; add 5 bytes to fix: Replace +$p with +!$p.
A breakdown and some golfings explained are ready to be posted;
but I´ll wait a bit to see if someone else submits before I spoil.


Haskell, 104 64 63 bytes

(-26 thanks to H.PWiz, additional -14 thanks to Sriotchilism O'Zaic, additional -1 thanks to cole)

This is a function.

f x=[y|y<-[1..],x==until(>=x)(foldr((+).read.pure)<*>show)y]!!0

Try it online!

Explanation:

(foldr((+).read.pure)<*>show)

Sequence of composited functions that returns y+digital sum of y. Converts to string first, then does some monad gymnastics to get the sum of the characters and the original number (thanks to Cole).

The <*> operator in this context has type and definition

(<*>) :: (a -> b -> c) -> (a -> b) -> c
f <*> g = \x -> f x (g x)

so we can write the above as

\x -> foldr ((+) . read . pure) x (show x)

This read . pure converts a Char into a number, so (+) . read . pure :: Char -> Int -> Int adds a digit to an accumulated value. This value is initialized to the given number in the fold.

until (>=x) {- digital sum function -} y

until repeatedly applies a function to its result (in this case, the y+digital sum y) until it meets a requirement specified by a function in the first argument. This gives the smallest y-DSS element that's greater or equal to x.

[y | y<-[1..]; x == {- smallest y-DSS element >= x -} ]

Infinite lazy list of y's such that the smallest y-DSS element >= x is actually x. Uses Haskell's list comprehension notation (which I'd also totally forgotten about, thank y'all).

f x = {- aforementioned list -} !! 0

First element of that list, which is the smallest y that satisfies the requirement of the challenge.


Jelly, 13 bytes

...turns out it's slightly different to Dylnan's method, I thought they just beat me to it

ṙ€1T€ịØD;”-¤U

A monadic link accepting a list of lists of 1s and 0s which returns a list of lists of characters the output "numbers".

Try it online!

How?

ṙ€1T€ịØD;”-¤U - Link: list of lists of integers (in {0,1})
ṙ€1           - rotate €ach list left by one
   T€         - get the truthy (1-based) indices of €ach
           ¤  - nilad followed by link(s) as a nilad:
      ØD      -   decimal digit characters = "0123456789"
         ”-   -   literal '-' character
        ;     -   concatenate
     ị        - index into (vectorises)
            U - upend (reverses each resulting list of characters)


Compact coding of integer into bitstring


JavaScript (ES6), 111 90 83 bytes

f=(a,b,p=q=[],u=[...p,[a,b]])=>a-b?f(...(q=[[a*2,b+1,u],[a+1,b*2,u],...q]).pop()):u

Try it online!
Commented
f = (                       // f = recursive function taking:
  a, b,                     //   (a, b) = input integers
  p =                       //   p[] = current path
  q = [],                   //   q[] = queue
  u = [...p, [a, b]]        //   u[] = updated path with [a, b] appended to it
) =>                        //
  a - b ?                   // if a is not yet equal to b:
    f(...                   //   recursive call, using spread syntax:
      (q = [                //     prepend the next 2 possible moves in the queue:
        [a * 2, b + 1, u],  //       a * 2, b + 1
        [a + 1, b * 2, u],  //       a + 1, b * 2
        ...q                //
      ]).pop()              //     use the move on the top of the queue
    )                       //   end of recursive call
  :                         // else:
    u                       //   success: return the (updated) path


Nothing, 0 chars

The source code is an empty file. It does nothing, like any Nothing program, therefore it is the correct execution of every such program.


05AB1E, 35 bytes
FтLΩˆ}>µ¯©=´vy®N<N>‚èy.SDPiн+ë\}ˆ}¼

Takes n as first input, and m as second. Doesn't use any threads, since 05AB1E has none.
Try it online.
Explanation:

F    }               # Loop the (implicit) input `n` amount of times:
 тL                  #  Push a list in the range [1,100]
   Ω                 #  Pop and push a random value from this list
    ˆ                #  Pop and add it to the global array
>                    # Increase the second (implicit) input `m` by 1
 µ                   # Loop until the counter_variable is equal to that:
  ¯                  #  Push the global array
   ©                 #  Store it in the register (without popping)
    =                #  Print it with trailing newline (without popping)
     ´               #  And clear the global array
   v                 #  Loop over each item of the array that is still on the stack:
      N<             #   Get the index-1
        N>           #   And the index+1
          ‚          #   Pair them together
     ®     è         #   Index both into the previous array we stored in the register
                     #   (NOTE: 05AB1E has automatic wrap-around when indexing)
            y.S      #   Compare both of them to the current integer `y`
                     #   (-1 if `y` is larger; 1 if `y` is smaller; 0 if equal)
               D     #   Duplicate this pair
                Pi   #   If the product is 1 (only true for [1,1] and [-1,-1]):
                  н  #    Only leave the first element of the duplicated pair
    y              + #    And add it to the current integer `y`
                 ë   #   Else:
                  \  #    Discard the duplicated pair, so `y` is at the top of the stack
                 }ˆ  #   After the if-else: add it to the global array
   }¼                #  After the inner loop: increase the counter_variable by 1


all occurences of each line from a file in another file for each line in the first file


JavaScript (ES6), 184 bytes

Takes the file F as a character and the rank R as an integer in currying syntax (F)(R). Returns an array of strings.

F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)

How?

Step #1: convert file/rank to Cartesian coordinates

We convert the hexagonal chess coordinates to Cartesian coordinates (x, y) with x in [0 .. 10] and y in [0 .. 20]:

      00 01 02 03 04 05 06 07 08 09 10
   +----------------------------------
00 |                f11                     F = file (letter)
01 |             e10   g10                  R = rank in [1 .. 11]
02 |          d09   f10   h09
03 |       c08   e09   g09   i08            F | a b c d e f g h i k l
04 |    b07   d08   f09   h08   k07         --+-----------------------
05 | a06   c07   e08   g08   i07   l06      x | 0 1 2 3 4 5 6 7 8 9 10
06 |    b06   d07   f08   h07   k06
07 | a05   c06   e07   g07   i06   l05      y = 22 - |x - 5| - 2R
08 |    b05   d06   f07   h06   k05
09 | a04   c05   e06   g06   i05   l04
10 |    b04   d05   f06   h05   k04
11 | a03   c04   e05   g05   i04   l03
12 |    b03   d04   f05   h04   k03
13 | a02   c03   e04   g04   i03   l02
14 |    b02   d03   f04   h03   k02
15 | a01   c02   e03   g03   i02   l01
16 |    b01   d02   f03   h02   k01
17 |       c01   e02   g02   i01
18 |          d01   f02   h01
19 |             e01   g01
20 |                f01

Step #2: apply the move vectors

Below is the list of the move vectors in the Cartesian system:

(-2, +4), (-1, -5), (+3, +1),
(-3, +1), (+1, -5), (+2, +4),
(-3, -1), (+2, -4), (+1, +5),
(-2, -4), (+3, -1), (-1, +5)

We apply each of them to the source coordinates (x, y) and get a list of target coordinates (X, Y).

Step #3: test the target coordinates

We now need to check which target coordinates are actually located inside the board. This is done by testing X + Y and X - Y:

The coordinates are valid if all the following comparisons are true:

X + Y > 3
X + Y < 27
X - Y < 7
X - Y > -17

We should also verify that X is in [0 .. 10]. This is not done explicitly because s[X] is undefined if it's not, which eventually results in a falsy value that gets filtered out.

Step #4: convert back to hexagonal chess coordinates

Finally the valid target coordinates are converted back to hexagonal chess coordinates, using the inverse of the formulas described at step #1.

Test cases

let f =

F=>R=>[...'100124566542'].map((X,i)=>(X-=3-(x=(s='abcdefghikl').search(F)))-7<(Y=('9641001469'[i]||10)-(A=Math.abs)(x-5)+17-2*R)&X+Y>3&X+16>Y&X+Y<27&&s[X]+(22-Y-A(X-5))/2).filter(n=>n)

console.log(JSON.stringify(f('b')(6)))
console.log(JSON.stringify(f('f')(6)))
console.log(JSON.stringify(f('f')(11)))
console.log(JSON.stringify(f('i')(1)))


CJam, 41 38 bytes

lee_S+W%\{Xa-X1='`-/(Xa+\L*+}fX1>W%1f=

Test it here.