Jelly, 18 bytes

ṣ”#L€ṙ-I%127”;ẋp”$

Try it online!

How it works

ṣ”#L€ṙ-I%127”;ẋp”$  Main link. Argument: s (string)

ṣ”#L€               Split s at hashes. Take the length of each resulting chunk.
     ṙ-             Rotate the result -1 units to the left / 1 unit to the right.
                    Since s won't have trailing semicola, the length of the last
                    chunk will be 0. Rotating moves this 0 to the beginning.
       I            Increments; take all forward differences. Because of the 0 we
                    removed to the beginning, the first forward difference will be
                    the length of the first chunk.
        %127        Take the differences modulo 127. In Python, `n % d' is either 0
                    or has the same sign as d, so this reports how many semicola
                    are needed to get from one code point to the next one.
            ”;ẋ     Repeat ';' k times, for each modulus k.
               p”$  Take the Cartesian product with "$", appending '$' to each run
                    of semicola.


Python 2, 287 271 270 276 275 bytes

import time,random
r,n=input()
c=n*-~r or-r
while c:
 c-=1;L=[list(' '*i+'\\'+'  '*(r-i)+'/')for i in range(r)];x=c%-~r;time.sleep(1);y=x+1;exec"L[x][y]=random.choice('\xaf/\_'[L[x][y-1]in'\_'::2][y==2*r-x:]);y+=1;"*2*(r-x)
 for l in['']*99+L+[' '*r+'\xaf'*2]:print''.join(l)

Try it online!

Does not clear the screen on tio, but works in a console.

Gif of it running:


05AB1E, 5 bytes

ΣêR}R

Try it online!
or as a Test suite

Explanation

Σ  }    # sort input by
 ê      # its sorted unique characters
  R     # reversed (to sort descending)
    R   # reverse the result (to sort descending)


Haskell, 100 bytes, by Laikoni

main=interact$id doid lines id words
doid oi d o id=do
 iddoid<-do oi id
 oid<-do o iddoid
 do d oid


Haskell, 57 54 bytes

f 0=cycle
f n|n<0=f(-n).reverse|n>0=concat.replicate n

Explanation:

f 0           -- If n=0 ..
 =cycle       -- infinitely repeat the input
f n|n<0       -- Otherwise, if n<0 ..
 =f(-n)       -- call f with the negative of n ..
 .reverse     -- and the reverse of the input
 |n>0         -- Finally, if n>0 ..
 concat       -- concatenate the result of ..
 .replicate n -- repeating the input n times

-3 bytes thanks to @nimi


JavaScript, 46 58 56 45 bytes

ES6 update: Turns out there's more features available to us now that five years have passed.

let f=(i=0,a=0)=>i>1e6?a:f(i+4,a+8/-~i/(i+3))

This version (45 bytes; yes, the let is required) works in ES6 strict mode in theory.  In practice, you can run it in V8 (e.g. with node) with --use-strict --harmony-tailcalls; the Proper Tailcalls feature isn't widely implemented yet, alas.  However, it's specified behaviour, so it should be fine.

If we want to stick to what's widely implemented, and not require strict-mode, we can simply use the ES6 fat-arrow syntax for functions but otherwise retain the same implementation as before (suggested by Brian H) for a cost of 48 bytes.

a=>{for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}

The choice of name for the single parameter doesn't really matter, but we might as well pick one of the names we use so as to minimise the global-scope pollution.

function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}

This version is a function expression; add two characters (e.g. " f") if you want it named.  This version clobbers the globals a and i; this could be prevented if we added "a,i" to the parameter list.

Makes use of a reformulated version of the algorithm in order to circumvent the need for subtraction.

 1/1 - 1/3  +   1/5 - 1/7   +    1/9 - 1/11  + ...
(3/3 - 1/3) + (7/35 - 5/35) + (11/99 - 9/99) + ...
    2/3     +      2/35     +       2/99     + ...
  2/(1*3)   +    2/(5*7)    +     2/(9*11)   + ...

Here's a "plain" version without this adjustment:

function(){for(a=0,i=1;i<1e6;i+=2)a+=[,4,,-4][i%4]/i;return a}

which clocks in at 64 62 characters.

Thanks to @ardnew for the suggestion to get rid of the 4* before the return.

History

function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}     // got rid of `i+=4`; restructured
// Old versions below.
function(){for(a=0,i=1;i<1e6;i+=4)a+=8/i/-~-~i;return a}    // got rid of `4*`
function(){for(a=0,i=1;i<1e6;i+=4)a+=2/i/-~-~i;return 4*a}


Find the largest number that's adjacent to a zero

MATL, 10 bytes
t~5BZ+g)X>

Try it online! Or verify all test cases.
Explanation
Let's take input [-4 -6 -2 0 -9] as an example.
t     % Input array. Duplicate
      %   STACK: [-4 -6 -2 0 -9],  [-4 -6 -2 0 -9]
~     % Logical negate. Replaces zeros by logical 1, and nonzeros by logical 0
      %   STACK: [-4 -6 -2 0 -9],  [0 0 0 1 0]
5B    % Push logical array [1 0 1] (5 in binary)
      %   STACK: [-4 -6 -2 0 -9], [0 0 0 1 0], [1 0 1]
Z+    % Convolution, maintaining size. Gives nonzero (1 or 2) for neighbours of
      % zeros in the original array, and zero for the rest
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
g     % Convert to logical
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
)     % Use as index into original array
      %   STACK: [-2 -9]
X>    % Maximum of array.
      %   STACK: -2
      % Implicitly display


Retina, 58 bytes

(?<!\n)\n(?!\n)
<space>
- (?! |[A-Z][a-z])| (?= )|(?<=-) (?=[A-Z])
<empty>

<space> represents a single space on its own line and <empty> represents an empty trailing line. For counting purposes, each line goes into a separate file and the \n are replaced with actual linefeed characters. For convenience you can put all of the above in a single file though and run it with the -s flag.

I'm pretty sure there's a shorter way to do this, so I'll wait with an explanation until I'm done golfing.


Excel, 3(+7?)

=A1

with format

yyy/m/d

Pure port


Javascript (ES6) 106 105 100
This function takes input as an an array and outputs a javascript object.
f=i=>i.map(a=>{for(b of c=a.toLowerCase(d=0)+d+123456789)d<!o[e=b>=0?c[0]+b:b]&&(o[d=e]=a)},o={})&&o

Results:
f(['File', 'Edit', 'View', 'Help']);
// {"f":"File","e":"Edit","v":"View","h":"Help"}

f(['Foo', 'Bar', 'FooBar', 'FooBars']);
// {"f":"Foo","b":"Bar","o":"FooBar","a":"FooBars"}

f(['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba']);
// {"a":"a","b":"b","a0":"aa","b0":"bb","q":"bbq","b1":"bbb","b2":"ba"}

Ungolfed / Commented:
f=i=>{
  o={};                                        // initialize an object for output
  i.map(a=>                                    // loop through all values in input
    for(b of c=a.toLowerCase(d=0)+d+123456789) // loop through all characters of the string with 0123456789 appended to the end
                                               // and initialize d as 0 to be used as a flag
      e=b>=0?c[0]+b:b                          // if b is a number, set e to the first character + the number, otherwise b
      if(d<!o[e])                              // if the flag hasn't been triggered and o doesn't have a property e
        o[d=e]=a                               // then store the value at e and trigger the d flag
  )
  return o                                     // return the output object
}


Python 2, 55 49 42
I have no idea what's going on, but it seems hard to beat the Maple formula from the OEIS page.
This uses 0-based indexing.
f=lambda n,t=0:n<1or f(n/2,n%2)-~-t*f(n-1)

Thanks to @PeterTaylor for -6 bytes.


C, 201-20-20=161
Completely refactored since rev 0. Bonuses claimed: non-square and over 9000.
#define B i%w][j]
char a[22000][5999];n,m,i,j,w=21669,c;main(){scanf("%d%d",&n,&m);
for(a[w/2][w/4]=1;i<w*(n+m);i+=2)for(j=5418;j--;a[1+B-=c*10)c=(a[1+B=(a[B+a[2+B+c)%48+48)>57;
printf("%s",a[w/2+n-m]);}

Algorithm
Calculating a number like 4000!/(2000!)^2 using multiplication and division seemed rather complicated to me. Instead I went for an approach based on iterating through the rows of Pascal's triangle, using only addition.
Here's an example using an int32 type, just to show the algorithm clearly:
int a[999],n,m,i,w=997;
main(){
  scanf("%d %d",&n,&m);
  a[w/2]=1;
  for(i=0;i<w*(n+m);i+=2)a[i%w+1]=a[i%w]+a[i%w+2];
  printf("%d",a[w/2+n-m]);
}

Where n+m is the number of rows of Pascal's triangle (counting the 1 at the top as row zero.) At the end of the program, a[] contains rows x and x-1 of Pascal's triangle, the even row in the even cells, and the odd row in the odd cells.
It's important that w is an odd number, so that on each pass through the array it alternates between writing to the odd and even cells. Also, it is important to ensure that the 1 used to initialise the array is not overwritten on the first pass. This requires that w/2 be even. I will explain this later.
This program will give the right answer, up to about n=m=16, after which the integer type overflows.
Ungolfed code
This works in the same way, but uses an array of char to store the decimal digits (in big endian format.)  In order to minimise the code needed to print the answer, the calculations are performed using the ASCII values (add 48 to each value.)
Note that the value of w is enough to hold rows 9000 and 8999 the same time (a total of 9001+9000=18001 big numbers.) We actually get as far as row 18000 of Pascal's triangle, so by that stage there will not be enough space in the array to hold all 9001+9000 big numbers, and some wrapping around will occur. But this does not affect the central cell of row 9000, which is the only cell we are interested in.
Besides adding whitespace, I have explicitly spelt out the #define and ungolfed w/4 to the correct value of 5417. This value is chosen because 18000C9000 has 5417 digits.
char a[22000][5999];
n,m,i,j,w=21669,c;
main(){
  scanf("%d%d",&n,&m);
  for(a[w/2][5417]=1;i<w*(n+m);i+=2)                       //Initialise array with a 1 in least significant bit of the middle cell of [a]. Loop through the numbers of each row of Pascal's triangle.
    for(j=5418;j--;a[1+i%w][j]-=c*10)                      //Loop through the digits of each number. The code to subtract 10 from the digit if carry flag `c` is executed after the following line.
      c=(a[1+i%w][j]=(a[i%w][j]+a[2+i%w][j]+c)%48+48)>57;  //Update the cell with a digit that is the sum of the ones to the left and right, taking into account the carry, and using mod 48 arithmetic in order to store the number as its ASCII code. The return value of the assigment to a[1+i%w][j] is compared with ASCII 57 (`9`) and if it is greater the carry flag `c` is set.
  printf("%s",a[w/2+n-m]);
}

Output
My first program took about an hour to print 4000C2000. This one can handle more digits and a higher number of rows to comply with the over 9000 rule. Consequently it takes about 15 hours to print 4000C2000 and would take several days to print 18000C9000.
For 2000x2000 it prints the following (formatted to 80 columns for clarity.) This can be verified to be correct here: http://www.wolframalpha.com/input/?i=4000C2000
First 50 rows of 80 zeros (total 4000) omitted
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000001662897875033835069539536
82646038155801622559738864034512798427681344501750925293497511985938004836061174
06787175851646432467983900275415704358907838322828226892377078626044702804227263
60225612674740415245206094268141079326236405795693301673758014841914146088010797
10165776274135023159100265188426666848338060694979313461996523028997743355283203
07681570747572865349817098575890269928612521344100050157521073022188690505729147
51382188762791861883958161617214384992392748400481691029679535864524592128327086
43054316262086765263594646961335049751537926540975614276702537605304524934071255
73064101385096253973516475386956779128378613359541658838021140118989221026997673
52312197112642059780157612212146003819787455505953360709346068359603711700350715
41788401648588967587345651743656288974543012791416766391390825096496908159194487
46858927217899313004799502582220660617063988223169179908327236982684836052004811
13856792890524143074688488766572261180609865630282282923756619604128170737791195
46057911790152387847927530536412500605466256862821891455217494809727772321234293
80354002249110229834175370966913440248688425483608677217484634416362795730488526
6233145705056647940287649067948285761750402006009891416640


Ruby, 26 characters
a=->n{1-(k=n-n/4*4)+k/3*2}

Example:
> p (0..10).map{|n| a[n]}
[1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1]

Note: This solution assumes that integer division / is an allowed operation.


J - 73 char

Takes input on stdin, as the 0-origin index in characters and the source, separated by a newline. Introduces a copy of the program at the specified point as a string.

((".@{.~({.,}.,~'(',')',~(LF;''',LF,''')rplc~quote@])(}.~>:))i.&LF)1!:1]3

Explained by explosion:

(                                  )1!:1]3  NB. stdin
 (                           )i.&LF         NB. find the first newline
     {.~                                    NB. the index part of input
  ".@                                       NB. convert index to integer
                      (}.~>:)               NB. the source program part
        ({.,}.,~     )                      NB. program before and after index
                ...@]                       NB. program quoted properly

For example, given input

3
abcdef'ghij'
kl mn 0p1

the output is

abc('abcdef''ghij''',LF,'kl mn 0p1')def'ghij'
kl mn 0p1

because J uses Pascal-style strings: 'Isn''t this great?'


Your calculator is pretty smart at inferring the end of lines for you, and thus you can omit quite a few characters.

:Disp "HELLO WORLD    //is the same as...
:Disp "HELLO WORLD"

For( loops have a syntax like this - For(variable, start, end, increment), but you can omit the increment and it will use 1:

:For(A,1,5     //is the same as...
:For(A,1,5,1)

and you can omit ending parentheses (at the end of lines) across the board:

:Output(1,1,A
:int(A
:round(A
etc.

Tested on my TI-84 Silver Edition calculator

If you think this is more than one idea (inferring endings) then I'll split them up


CJam → CJam, score 1046877.4413

I'm not going to participate in my own challenge, but since this one doesn't contain its core part (figuring out the optimal transformation to make the original image more compressible), here I go:

q"@#+';:,.` ":P9,easdf*.4f+:iPf=S+er_N/z,:L;N-__&W%:Pf#2f+e`{(2b1>}%
e_P,2+b256b:c`P`":P,2+\256b\b{_2,#)_(@a?)+}%{(2-a\2b)*}%e_Pf="L"/N*"

The linefeed is for "readability" only.

It should be possible to improve the score by improving or simplifying the compression.

Summary

e# Read the input and modify the palette according to the quality.

q"@#+';:,.` ":P9,easdf*.4f+:iPf=S+er

e# Compute the line length and the unique characters of the palette.

_N/z,:L;N-__&W%:P

e# Replace each character by its index in the palette, plus two.

f#2f+

e# Perform run-length ecnoding, saving the runs using bijective base-2 numeration.
e# All related code has been adapted from this answer:
e# http://codegolf.stackexchange.com/a/53065

e`{(2b1>}%

e# Convert from base length(palette)+2 to byte array (string).

e_P,2+b256b:c`

e# Push the palette and the code for the decoder.

P`":P,2+\256b\b{_2,#)_(@a?)+}%{(2-a\2b)*}%e_Pf="L"/N*"

Score

$ LANG=en_US
$ for i in {1..5}; do for q in 0.{5..9}; do
> cjam comp.cjam $q < image$i.txt > image-$i-$q.cjam
> done; done
$ wc -c comp.cjam
136 comp.cjam
$ wc -c image*.cjam
 2131 image-1-0.5.cjam
 2248 image-1-0.6.cjam
 2346 image-1-0.7.cjam
 2350 image-1-0.8.cjam
 2446 image-1-0.9.cjam
 3006 image-2-0.5.cjam
 3718 image-2-0.6.cjam
 3894 image-2-0.7.cjam
 3356 image-2-0.8.cjam
 4064 image-2-0.9.cjam
 2949 image-3-0.5.cjam
 2947 image-3-0.6.cjam
 3582 image-3-0.7.cjam
 3784 image-3-0.8.cjam
 3745 image-3-0.9.cjam
 2879 image-4-0.5.cjam
 2887 image-4-0.6.cjam
 3379 image-4-0.7.cjam
 3615 image-4-0.8.cjam
 3537 image-4-0.9.cjam
 4427 image-5-0.5.cjam
 4802 image-5-0.6.cjam
 5536 image-5-0.7.cjam
 6030 image-5-0.8.cjam
 6111 image-5-0.9.cjam
89769 total


C, 257 253 222 220

Uses system("cls") instead of curses (use system("clear") for Linux systems) and a clever algorithm to fit the map into an 8-digit number. Non-extended keys end the program, e.g. escape.

EDIT: Now also shows your hero below the map by using a<230 instead of a<132:

    ##
   ####
 ###  ###
 # #  # #
## #  # ##
   ####
  #    #
 ##    ##

Code:

a,p=14,w=11,X,Y;m(I){X=I%w-1,Y=I/w;return 70313263>>(Y>5?w-Y:Y)*5+(X>4?9-X:X)&1;}main(){do{system("cls");a=a&4?1:a&2?-1:a&8?-w:w;p+=!m(p+a)*a;for(a=0;++a<230;)putch(a%w?a-p?m(a)*35:64:10);}while(a=getch()>>7?getch():0);}


(Can I) Add parentheses to make this true

Python 2, 286 285 282 bytes

from fractions import*
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
for p in P(['Fraction(%s)'%e for e in x[::2]]):
 try:print 1/(eval(''.join(sum(zip(eval(`p`.replace("['","'(").replace("']",")'")),x[1::2]+[0]),())[:-1]))==y)
 except:0

Try it online
Explanation:
This version will print all of the working expressions (with the Fraction objects).
from fractions import*
# Sublist Partitions (ref 1)
P=lambda L:[p+[L[i:]]for i in range(len(L))for p in P(L[:i])]or[L]
x,y=input()
x=x.split()
# Convert all numbers to Fractions for division to work
n=['Fraction(%s)'%e for e in x[::2]]
# Operators
o=x[1::2]
# Try each partition
for p in P(n):
    # Move parens to be inside strings
    n=eval(`p`.replace("['","'(").replace("']",")'"))
    # Alternate numbers and operators (ref 2)
    x=''.join(sum(zip(n,o+[0]),())[:-1])
    # Prevent division by zero errors
    try:
        # Evaluate and check equality
        if eval(x)==y:print x
    except:0

Try it online
References:

Partitioning function

Alternating zip

Saved 3 bytes thanks to Felipe Nardi Batista


Brachylog, 28 bytes

⟦₁⊇ᶠk⊇pSs₂ᶠ{c≠&⟨+/l⟩ᵐ<ᵈ}ᵐ∧Sl

Try it online!

This is really damn slow. Takes about 30 seconds for N = 3, and it didn't complete after 12 minutes for N = 4.

Explanation

⟦₁                             Take the range [1, …, Input]
  ⊇ᶠk                          Find all ordered subsets of that range, minus the empty set
     ⊇                         Take an ordered subset of these subsets
      pS                       Take a permutation of that subset and call it S
       Ss₂ᶠ                    Find all substrings of 2 consecutive elements in S
           {           }ᵐ      Map for each of these substrings:
            c≠                   All elements from both sets must be different
              &⟨+/l⟩ᵐ            And the average of both sets (⟨xyz⟩ is a fork like in APL)
                     <ᵈ          Must be in strictly increasing order
                         ∧Sl   If all of this succeeds, the output is the length of L.

Faster version, 39 bytes

⟦₁⊇ᶠk⊇{⟨+/l⟩/₁/₁}ᵒSs₂ᶠ{c≠&⟨+/l⟩ᵐ<₁}ᵐ∧Sl

This takes about 50 seconds on my computer for N = 4.

This is the same program except we sort the subset of subsets by average instead of taking a random permutation. So we use {⟨+/l⟩/₁/₁}ᵒ instead of p.

{         }ᵒ     Order by:
 ⟨+/l⟩             Average (fork of sum-divide-length)
      /₁/₁         Invert the average twice; this is used to get a float average

We need to get a float average because I just discovered a ridiculous bug in which floats and integers don't compare by value but by type with ordering predicates (this is also why I use <ᵈ and not <₁ to compare both averages; the latter would require that double inversion trick to work).


How can I golf this code to count all perfect squares below 100?

For the exact question posed: since we know that 1 is a perfect square and all integers between that and the maximal one (here 9) will be included we can simply find that maximal one:

print((100-1)**.5//1)

(//1 performing integer division by one to remove any fractional part may be replaced with /1 prior to Python 3.)

with both endpoints (an inclusive start and exclusive stop equivalent to a range) this could be extended to a function (negative inputs catered for with max):

f=lambda start, stop:print(max(0,stop-1)**.5//1-max(0,start)**.5//1)


Pyth, 20 16 14 bytes
hol@GNf!-GrT0.:

Explanation:
             .: - substrings of input()
      f!-GrT0   - filter to ones which contain the alphabet
 ol@GN          - sort by number of alphabetical chars
h               - ^[0]

      f!-GrT0   - filter(lambda T:V, substrings)
          rT0   -    T.lower()
        -G      -   alphabet-^
       !        -  not ^

 o              - sort(^, lambda N:V)
   @GN          -   filter_presence(alphabet, N)
  l             -  len(^)

Try it here!
When there isn't a correct solution, the program exits with an error with no output to stdout.


Jelly, 5 bytes

ĠLÐṀị

Try it online!

How it works

ĠLÐṀị  Main link. Argument: A (array)

Ġ      Group; partition the indices of A by their corresponding values.
 LÐṀ   Select all index arrays with maximal length.
    ị  Unindex; retrieve the items of A at the specified indices.


Husk, 5 4 bytes
üoEė

Try it online!

Saved 1 byte thanks to Razetime
Saved 2 bytes thanks to Jo King

Thanks to Razetime for suggesting ü and Jo King for letting me know I could leave the superscript arguments out, saving me 2 bytes. It removes duplicates with a custom predicate that makes sure both arguments are equal to the number to be removed.
Explanation:
üoEė
ü     Remove duplicates by binary function (implicit second argument)
 o    Compose 2 functions
   ė  Make a list of 3 elements (first element is implicitly added)
  E   Are they all equal?


Jelly, 43 36 35 bytes

ḶṚ3*µ5B¤xÐ€ṁ€Ṁ×\Ṛ©1,‘xS$¤ṁ×®ị“*# ”Y

Just a start, I'm sure this could be shorter.

Try it online!

*For n > 5, your browser might wrap the output but if you copy-paste it into a non-wrapping editor, you will see the proper output.

Explanation

ḶṚ3*µ5B¤xÐ€ṁ€Ṁ×\Ṛ©1,‘xS$¤ṁ×®ị“*# ”Y  Input: integer n
Ḷ                                    Create the range [0, n)
 Ṛ                                   Reverse it
  3*                                 Raise 3 to the power of each
    µ                                Begin a new monadic chain on the powers of 3
     5B¤                             Nilad. Get the binary digits of 5 = [1, 0, 1]
        xÐ€                          Duplicate each of [1, 0, 1] to a power of 3 times
             Ṁ                       Get the maximum of the powers of 3
           ṁ€                        Reshape each to a length of that value
              ×\                     Cumulative products
                Ṛ©                   Reverse and save the result
                  1,‘xS$¤            Niladic chain.
                  1                    Start with 1
                    ‘                  Increment it
                   ,                   Pair them to get [1, 2]
                       $               Operate on [1, 2]
                      S                  Sum it to get 3
                     x                   Repeat each 3 times to get [1, 1, 1, 2, 2, 2]
                         ṁ           Reshape that to the saved table
                          ×®         Multiply elementwise with the saved table
                            ị“*# ”   Use each to as an index to select from "*# "
                                  Y  Join using newlines
                                     Return and print implicitly


Create a memory leak, without any fork bombs

Windows

The Win32 API allows you to allocate memory in other processes, and then to read/write that memory remotely. This program has only one thread, which it uses to enumerate each running process on the system, and then repeatedly allocate 1MB buffers in each process until the allocation fails. When it finishes with one process, it moves on to the next. The allocations are not released when the calling program finishes - only when/if each target process finishes. This hangs a 2GB Windows 7 VM in about 10 seconds. It does require running as admin.

To compile: cl /MD leak.cpp /link psapi.lib

#include <windows.h>
#include <psapi.h>

typedef void (*ProcFunc)(DWORD pid);
#define ALLOC_SIZE 0x100000
LPVOID buf;

void ForEachProcess(ProcFunc f)
{
    DWORD aProcesses[1024], cbNeeded;

    if (!EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded))
        return;

    for (unsigned int i = 0; i < cbNeeded / sizeof(DWORD); i++)
        if (aProcesses[i] != 0)
            f(aProcesses[i]);
}

void RemoteLeak(DWORD pid)
{
    HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid );
    if (hProcess == NULL)
        return;

    for (;;)
    {
        LPVOID ptr = VirtualAllocEx(hProcess, NULL, ALLOC_SIZE,
                                    MEM_COMMIT, PAGE_READWRITE);
        if (ptr == NULL)
            return;

        WriteProcessMemory(hProcess, ptr, buf, ALLOC_SIZE, NULL);
    }
}

int main(void)
{
    buf = malloc(ALLOC_SIZE);
    if (buf == NULL)
        return 0;

    memset(buf, 0xFF, ALLOC_SIZE);

    ForEachProcess(RemoteLeak);

    return 0;
}


Python, 270 228 166 156 bytes

a=input();b=input();m=lambda s:[c=="#"for c in s];f=m(a);g=m(b);s=p=0
for i in range(len(a)):q=2*f[i]+g[i];r=p&q;s+=r!=0;p=r or p|q
print(s+(any(f)&any(g)))

PEP8-ified:

a = input()
b = input()
m = lambda s: [c == "#"for c in s]
f = m(a)
g = m(b)
s = p = 0
for i in range(len(a)):
    q = 2*f[i]+g[i]
    r = p & q
    s += r != 0
    p = r or p | q
print(s+(any(f) & any(g)))

Try it online!

This is my first time here, be gentle please ;)

There is always a horizontal wall in the middle, except when prisoners are only on one side -- the addition in print() takes this into account. Strategy here is to break horizontal bar into sections such that there is no more than one prisoner on each side, for each section.

The for loop uses an int, p, to hold two bit flags, indicating whether the current top/bottom section already contains a psychopath. We & this with the flags from the new gridsquare to check whether we are going to overflow, and need to place a wall; if so, we increment s. We also use p&q to decide how to update the state: if we overflow, we hold onto just the overflowed prisoner (p&q). Otherwise, we | the new prisoners onto our current prisoner state. Using and and or as a ternary operator again here.

There are some helper functions at the top, as well as throwaway variable names for values used more than once.

Edit:
It seems like this got simpler as it got shorter. It used to use all kinds of wacky behaviour


Cubically, 1664 1631 1089 bytes

⇒FD2F'R'D2RUR'D2RFD2F'U'
⇒Ff1F'
⇒LFf1F'L'
⇒F'f1F
⇒F2f1F2
⇒L'F2f1F2L
⇒D'F'f1FD
⇒LR'FLR'DLR'B2L'RDL'RFL'RU2
⇒LFf8F'L'
⇒R'F'f8FR
⇒Ff8F'
⇒F'f8F
⇒ULU'f8UL'U'
⇒U'R'Uf8U'RU
⇒F2f8F2
⇒Df15D'
⇒D'f15D
⇒D2f15D2
⇒UF2UF2D'L2B2U'B2DL2F2D2B2D2F2
⇒U'DL2UD'B2
⇒UF2UF2D'L2B2D'R2UR2F2D2B2U2B2
⇒BL'BU2D2F'RF'U2D2
⇒LD'F2U'B2U'RU2R'F2R2F2D'R2DF2D
⇒B2URB2D2B2RB2U'D'L2D'B2
⇒B2LF'U'B2UFL'R2B2U'D2L2D'B2U
⇒B2RB2D2B2RB2U'L2UD'F2U'F2B2
⇒D2R'FUB2U'F'RU2B2D'F2R2UF2UF2
⇒B2R2U'L'D2B2U2R'U2R2F2L2R2UR2
⇒D2L'B2U2F2RUL2U'F2R2U'R2U2F2DL2D'
⇒UB2U'L2DL2B2DB2D'B2
⇒BR'BL2B'RBL2B2
⇒UF2B2U'F2B2U'F2L2R2B2R2
⇒R2U'F2DR2UF2D'R2DF2R2D'F2
⇒U'F2DF2UL2F2DL2DF2L2D2F2
⇒U2D'L2U'F2L2U'B2L2R2U'L2B2
⇒F2D'R2U2L2B2UF2L2U2F2L2UF2R2
⇒[f1]3
⇒[f2f37]3
⇒[f3f38]3
⇒[f4f39]3
⇒[f5f40]3
⇒[f6f41]3
⇒[f7f42]3
⇒[f8f43]2
⇒[f9f44]2
⇒[f10f45]2
⇒[f11f46]2
⇒[f12f47]2
⇒[f13f48]2
⇒[f14f49]2
⇒[f15f50]2
⇒[f16f51]2
⇒[f17f52]2
⇒[f18f53]2
⇒[f19f54]2
⇒[f20f55]3
⇒[f21f56]4
⇒[f22f57]5
⇒[f23f58]6
⇒[f24f59]7
⇒[f25f60]8
⇒[f26f61]9
⇒[f27f62]9[f27f62]2
⇒[f28f63]9[f28f63]3
⇒[f29f64]9[f29f64]4
⇒[f30f65]2
⇒[f31f66]3
⇒[f32f67]4
⇒[f33f68]5
⇒[f34f69]6
⇒[f35f70]7
rs[f36f71]8

Output if solvable: Solved!
Output if unsolvable: (empty, no output)

Input should be formatted as a Cubically cube-dump (see the Debug section). This was explicitly allowed by the OP.

Explanation

This program takes the approach of using a Devil's Algorithm to iterate over every possible state of the cube in the same group as the solved cube. If the cube is solvable, it will be solved at some point before the algorithm has finished (assuming the algorithm I used works properly).

Every line beginning with ⇒ (0x84 in Cubically's codepage) is a function definition; these functions build off of each other to make up the actual Devil's Algorithm. The first line to be executed is the last one:

rs[f36f71]8

r reads a cube from stdin and sets the memory cube to it. s puts the interpreter into "solvemode", which means that it exits and prints Solved! if the cube becomes solved (after being unsolved) at any point. The rest of the commands (which simply repeat f36f71 8 times) correspond to the final algorithm at the bottom of the linked page:

(D) = (CP) = (CPT8) = [(CPC8)(CPT7)]8 (3,847,762,288,469,010,006,992 moves)

(D) is the Devil's Algorithm. If you apply it to the cube, it will be solved at some point before you have done the algorithm once. As you can see, it is terribly long, nearly a thousand times more moves than there are possible positions.

How can I run it?

You can try it online, but that link doesn't work. TIO will almost definitely time out before this algorithm finishes (the maximum runtime for an interpreter is 60 seconds). If the cube is not solvable, this algorithm will take up to 11 million years for Cubically to finish (at ~15.2 million moves per second, which is what my Cloud9 IDE gets).

Additionally, you need a lot of memory to perform 3 sextillion moves. Cubically can perform about 4 million moves per second, but the process will most likely be killed due to overcommitted memory. It dies after 15 seconds on my VM with 512MB of memory. Why should performing moves on an already-allocated flat array cost memory? Found a memory leak (or twenty) and fixed it.

Here is a much more readable version that behaves the same way.

But I really want to see that it works!

The first actual move that is executed in this devil's algorithm is F2, so the quickest cube to solve would be one scrambled with F2:

   000
   000
   555
113222133444
113222133444
113222133444
   000
   555
   555

This indeed executes in 0.007 seconds on TIO.

How can this be improved?

There are certainly more devil's algorithms; I've found one that uses less than a thirtieth of the moves this one does. However, that would come at the cost of several thousand bytes (around 100MB more) and several dozen hours of converting a complex Hamiltonian circuit to Cubically code.

It's also possible to remove some of the functions and put them straight in the loop at the bottom. However, I'm going to sacrifice some bytes for some readability.

Additionally, I'm considering a modification of Cubically's looping behavior so that I can more easily repeat algorithms 7 or 8 times (instead of just hard-coding them with the function calls repeated 7 or 8 times in the source). Or I'll work some magic out with the notepad, and golf this using more loops.

Note that I will continue to optimize anything possible in the interpreter, so this may work on an average PC sometime in the future!

Cubically, 2 bytes

r▦

I like the above answer better so I'm adding this as an alternate solution. This runs in under a second, as opposed to a few million years.

r    read cube from standard in
 ▦   and solve it

Output if the cube is solvable: (nothing)
Output if the cube is unsolvable: Error: The cube has reached an unsolvable state.


Compute the most efficient binary function

Haskell, 110 bytes

f q=head[i|let c=[(-1,0)]:[[(f a,f b)|n<-[0..k],a<-c!!n,b<-c!!(k-n)]|k<-[0..]],(p,i)<-zip(concat c)[0..],p==q]

The argument here is taken to be the tuple (x,y). Pretty similar to the answer above, but the lookup list holds just the pairs of left and right indices instead of the trees.


APL (Dyalog Extended), 16 bytes

+/⍬∘⍋(⍸⊣⊃¨⍕⍛⍷¨)⊂

Try it online!

Takes a string of digits.

How it works

+/⍬∘⍋(⍸⊣⊃¨⍕⍛⍷¨)⊂  ⍝ Input: character vector of digits
  ⍬∘⍋             ⍝ X←Array of 1-based indices
     (    ⍕⍛ ¨)   ⍝ Stringify each of X
     (      ⍷¨)⊂  ⍝ And for each of above, build a boolean array where
                  ⍝   substring matches are marked as 1
                  ⍝ e.g. '10'⍷'10428104' is [1 0 0 0 0 1 0 0]
       ⊣⊃¨        ⍝ Extract X-th indices from each of above
      ⍸           ⍝ Convert ones to its 1-based locations
+/                ⍝ Sum


Python 3 (with sympy),  61 60 58 54  48 bytes
-6 (maybe even -10 if we do not need to handle n=1) thanks to xnor (further trigonometric simplification plus further golfing to handle edge case of 1 and save parentheses by moving a (now unnecessary) float cast).
Hopefully beatable with no 3rd party libraries? Yes!! but Lets get things rolling...

lambda n:1%n*n/2/(1-cos(pi/n))
from math import*

Try it online!
This uses a formula for the sum of the lengths if a polygon is inscribed inside a unit circle, n*cot(pi/2/n)/2 and adjusts the result to one for the side length being one by dividing by the sin of that cord length sin(pi/n).
The first formula is acquired by considering the n-1 cord lengths of all the diagonals emanating from one corner which are of lengths sin(pi/n) (again), sin(2*pi/n), ..., sin((n-1)pi/n). The sum of this is cot(pi/2/n), there are n corners so we multiply by n, but then we've double counted all the cords, so we divide by two.
The resulting n*cot(pi/2/n)/2/sin(pi/n) was then simplified by xnor to n/2/(1-cos(pi/n)) (holding for n>1)
...this (so long as the accuracy is acceptable) now no longer requires sympy over the built-in math module (math.pi=3.141592653589793).


QBASIC 211 bytes

SCREEN 13
WINDOW(-160,-100)-(159,99)
FOR x=0TO 63
 PALETTE x,x*65793
NEXT
FOR i=16TO-16STEP-.1
 FOR j=16TO-16STEP-.05
  s=SQR(i*i/2+j*j/2)
  PSET(i*10,j*5+17.32*COS(s)),18.2*(COS(s)-SIN(s)*j/s)+31+RND
 NEXT
NEXT

The color for each pixel is chosen by adding the z value on the curve with the partial derivative with respect to y, generating a 'fake' lighting effect. The added random value helps to smooth the borders between regions. Produces something similar to the following:


><>, 56 bytes

^
.
+
8
f
0
o
a
o
~
:
?
~
:
?
:
-
*
4
8
:
^
^
}
*
3
d
'

Try it online! or verify all mutations.

How the original program works (outdated)

The interpreter starts in cell (0, 0). ^ sets the direction to upwards, so the instruction pointer (IP) wraps around to cell (0, 20).

' activates string mode: until the next ' is encountered, all characters under the IP are pushed on the stack. The same ' is found again after wrapping around, so we push

d3*}^^:84*=?~oao0f.^

The IP lands at (0, 19), still going upwards. Executing d3*} pushes 13 = 0xd, then 3, multiplies both values (39 / single quote), then rotates the stack to the right. This leaves the stack as follows.

'd3*}^^:84*=?~oao0f.^

The next two instructions (^) do nothing at this point.

:84*= duplicates the top of the stack, pushes 8 and 4, multiplies them (32 / space), then tests the duplicated character for equality with space. For the unaltered program, this will always push 0.

? skips the next instruction if the top of the stack is falsy. For the original program, it always is, so ~ is always skipped.

oao pops and prints the top of the stack, pushes a 10 / linefeed, then pops and prints linefeed.

Finally 0f. jumps to cell (0, 15) (the bottommost ^), starting over with the next character on the stack.

Once the stack is empty, the entire source code has been printed. : will fail and the program exits.

How the mutated programs work (outdated)

Duplicating any non-linefeed character will only extend the program horizontally. Since the program is executed vertically, these extra instructions will never get executed.

Duplicating any linefeed before the bottomost ^ will shift cells (0, 14) and (0, 15) to (0, 15) and (0, 16). 0f. will now jump to the cell before the bottommost ^, which is also a ^, so the program is not affected by the shift.

Finally, any duplicated linefeed character will also alter the string. Short lines are padded with spaces, so a 32 / space will be inserted at the linefeed's position. 84*= will push 1 for space, so ? doesn't skip the next instruction. In this case, ~ pops and discards space, so the following o will print the character above space instead.


Decode Arabic to Arabic Presentation Form

JavaScript (ES6),  231 ... 148  146 bytes
I/O format: list of code points

a=>a.map(t=(c,i)=>c%32?(g=A=>n^c%49?g([x=n%32<26,k*x,x&=454642>>n++*25%54%26,x].map(x=>x&&++k)):A[t=t>1^2*(a[i+1]>1569)]||A[t^=2])(n=k=0)+65151:c)

Try it online!
a =>                             // a[] = input array
a.map(t = (c, i) =>              // for each code point c at position i in a[]:
  c % 32 ?                       //   if c is not 0x0640:
    ( g = A =>                   //     g is a recursive function taking a list A[]
        n ^ c % 49 ?             //       if we haven't reached the correct character:
          g(                     //         do a recursive call:
            [                    //           build a list describing the existence of:
              x = n % 32 < 26,   //           - isolated: if not in range 0x063B-0x0640
              k * x,             //           - final: same as isolated, except for the
                                 //             first entry which is undefined
              x &=               //           - initial: we use a lookup bit-mask
                454642 >> n++    //             with the following hash formula:
                * 25 % 54 % 26,  //               ((n * 25) mod 54) mod 26
              x                  //           - medial: same as initial
            ].map(x => x && ++k) //           turn it into a list of indices
          )                      //         end of recursive call
        :                        //       else:
          A[                     //         output the relevant entry from A[]:
            t =                  //           update t:
              t > 1 ^ 2 * (      //             (previous was initial or medial) XOR
                a[i + 1] > 1569  //             2 * (this is not the last letter
              )                  //             and the next letter is not 0x0621)
          ] ||                   //         if A[t] is not defined:
            A[t ^= 2]            //           use A[t ^ 2] instead
    )(n = k = 0)                 //     initial call to g with n = k = 0
    + 65151                      //     add 0xFE7F
  :                              //   else:
    c                            //     output c unchanged
)                                // end of map()


GolfScript, 53 chars

n%(0=2%{~.,[{26rand 65+}*]:K]}*zip{{-}*~)26%65+}%K]n*

This is a task for which GolfScript seems just about perfectly suited.

To keep the code short, I'm using the same code for both encryption and decryption: to decrypt, I subtract the key from the ciphertext, while for encryption, I first generate a random ciphertext and then subtract the plaintext from it.  Even so, the extra code for implementing encryption mode takes just a little over half the length of the program.

De-golfed version with comments:

n %             # split input into an array of lines

# KEY GENERATION FOR ENCRYPTION MODE:
(               # extract the first line from the array
0 = 2 %         # check if the first char of that line is odd (E = 69)...
{               # ...and execute this block if it is:
    ~           # dump the remaining lines (of which the should be only one) on the stack
    . ,         # calculate the length of the last line...
    [ { 26 rand 65 + } * ]  # ...make an array of that many random letters...
    :K          # ...and assign it to K
    ]           # collect all the lines, including K, back into an array
} *

# ENCRYPTION / DECRYPTION ROUTINE:
zip             # transpose the array of 2 n-char strings into n 2-char strings...
{               # ...and execute this block for each 2-char string:
    {-} *       # subtract the second char code from the first
    ~ )         # negate the result (using the two's complement trick -x = ~x+1)
    26 % 65 +   # reduce modulo 26 and add 65 = A
} %

# OUTPUT:
K ] n*         # join the result and K (if defined) with a newline, stringifying them


Jelly, 21 19 11 10 7 bytes

²~³¡H+2

Try it online!

Idea

Assume for a second that the first term of the final sum is subtracted rather than added.

Let n be a positive integer.

Even case

 1              6
    8       11
      15 16
      21 22
   26       29
31             36

The differences between the diagonal elements on the lower half of the rows are the first n ÷ 2 odd natural numbers. Since 1 + 3 + 5 + … + (2k + 1) = k2, they sum to (n ÷ 2)2 = n2 ÷ 4.

In this example

- 1 + 6 - 8 + 11 - 15 + 16 - 21 + 22 - 26 + 29 - 31 + 36  =
-(1 - 6)-(8 - 11)-(15 - 16)-(21 - 22)-(26 - 29)-(31 - 36) =
(    5   +   3    +    1  )+(   1    +    3    +    5   ) =
             9             +              9               = 18

Thus, the sum is 2 × n2 ÷ 4 = n2 ÷ 2.

Odd case

 1           5
    7     9
      13
   17    19
21          25

The differences between the diagonal elements on the corresponding rows from above and below (1 and 5, and 21 and 25; 7 and 9, and 17 and 19) is the same, so they will cancel out in the alternating sum.

In this example

- 1 + 5 - 7 + 9 - 13 + 17 - 19 + 21 - 25  =
-(1 - 5)-(7 - 9)- 13 +(17 - 19)+(21 - 25) =
    4   +   2   - 13 -    2    -    4     = -13

All that's left is the negative of the central element, which is the arithmetic mean of the first and last number, so it can be calculated as -(n2 + 1) ÷ 2.

General case

Since ~x = -(x + 1) for two's complement integers (~ denotes bitwise NOT), the formula for the odd case can be rewritten as ~n2 ÷ 2.

Also, since the first term (1) of the original sum is added instead of subtracted, the above formulas leave an error of 2, which has to be corrected.

Therefore, the nth cross-alternate sum is n2 ÷ 2 + 2 if n is even, and ~n2 ÷ 2 + 2 if it is odd.

Finally, bitwise NOT is an involution, i.e., ~~x = x for all x. This way ~~~x = ~x, ~~~~x = x, and, in general, ~nx (meaning that ~ is applied n times) is x if n is even and ~x if it is odd.

Thus, we can rewrite our general formula as ~nn2 ÷ 2 + 2 for all positive integers n.

Code

²~³¡H+2    Main link. Input: n

²          Yield n².
 ~         Apply bitwise NOT to n²...
  ³¡           n times.
    H      Halve the result.
     +2    Add 2.


Pyth, 14 13 bytes
Update: saw this got accepted and noticed a trivial 1 byte golf. Whoops.
:D"ll|ch|."1Q

Try it online. Test suite.
For each word, find all non-overlapping matches for the regex ll|ch|.. This splits the word into the "letters". Then, just sort the words by the splitted lists.


80386 machine code, 40 38 bytes

Hexdump of the code:

60 33 db 51 0f c7 f0 f7 e0 52 0f c7 f0 f7 e0 58
03 d0 72 03 83 c3 04 e2 eb 53 db 04 24 58 db 04
24 58 de f9 61 c3

How to get this code (from assembly language):

    // ecx = n (number of iterations)
    pushad;
    xor ebx, ebx; // counter
    push ecx; // save n for later
myloop:
    rdrand eax; // make a random number x (range 0...2^32)
    mul eax; // calculate x^2 / 2^32
    push edx;
    rdrand eax; // make another random number y
    mul eax; // calculate y^2 / 2^32
    pop eax;
    add edx, eax; // calculate D = x^2+y^2 / 2^32 (range 0...2^33)
    jc skip; // skip the following if outside the circle
    add ebx, 4; // accumulate the result multiplied by 4
skip:
    loop myloop;
    push ebx; // convert the result
    fild dword ptr [esp]; // to floating-point
    pop eax;
    fild dword ptr [esp]; // convert n to floating-point
    pop eax;
    fdivp st(1), st; // divide

    popad;
    ret;

This is a function using MS fastcall calling convention (number of iterations is passed in register ecx). It returns the result in the st register.

Fun things about this code:

rdrand - just 3 bytes to generate a random number!
It uses (unsigned) integer arithmetic until the final division.
The comparison of squared distance (D) with squared radius (2^32) is performed automatically - the carry flag contains the result.
To multiply the count by 4, it counts the samples in steps of 4.


Perl: 15 Bytes +1 for -p option

s/ ?\([^,"]+//g

Usage:

perl -pe 's/ ?\([^,"]+//g' file.csv


bash - every man dies alone
This line writes the poem:
echo echo view echo renice yes make apropos nice date identify echo start apropos locate octave nice echo | xargs -n 1 | awk '{s = s substr($1, 1, 1); if ($1 == "echo"){print $1, "-n", s; s = "";}else print $1, "--they >.said 2>&1";}' > acrostic.sh

To see the poem:
$ cat acrostic.sh

To see the poem within the poem:
$ sh acrostic.sh


05AB1E, 13 bytes

0.ø.γ.u}'"ý¦¨

Try it online!

0.ø              # surround input string with 0s
   .γ  }         # group characters by:
     .u          #  is uppercase?
        '"ý      # join groups with quotes
           ¦¨    # remove the first and last characters (0s)


Congratulations on getting 10,000 reputation!

Ruby, 209 bytes

Edit: I switched to Ruby which shortened this by about 30%. See the edit history for the original Mathematica version. I suppose the main savings come from Ruby's permutation not ignoring switched positions of identical elements (which I had to trick Mathematica into).

This uses the newline-separated format.

gets.split('
').map{|s|s.split.map &:to_i}.each_cons(2){|a,b|a.permutation.map{|q|q.zip(b).map{|x,y|y-x}}.reject{|d|d.any?{|x|x<0||x>200}}.size!=1?abort(':('):(puts':D '*(a.count{|d|d<1e4}-b.count{|d|d<1e4}))}

The gist is this:

Get all consecutive pairs of days.
Get all permutations of the former day, and subtract each of these from the current day.
Ditch all results which contain differences that are negative or greater 200.
If the number of remaining permutations isn't 1, output :(.
Otherwise, output as many :D as there are new 10k users.
At the end, drop all days after the first :(.

Less golf:

gets.split("\n").map{|s|
  s.split.map &:to_i
}.each_cons(2){|a,b|
  a.permutation.map{|q|
    q.zip(b).map{|x,y|
      y-x
    }
  }.reject{|d|
    d.any?{|x|
      x<0||x>200
    }
  }.size!=1 ? abort(':(') : (puts ':D '*(a.count{|d|d<1e4}-b.count{|d|d<1e4}))
}

I think that's one beautiful chain of enumerators. :)

PS: Is it weird that I was the first one to submit an answer to this?


C# (534 characters)

using System.IO;using B=System.Byte;class X{static void Main(string[]a){var f=File.ReadAllBytes(a[0]);int l=f.Length,i=0,j;var p=new uint[256];for(uint k=0,r=0;k<256;r=++k){for(j=0;j<8;j++)r=r>>1^(r&1)*0xedb88320;p[k]=r;}uint c=~(uint)0,n=c;using(var o=File.Open(a[0]+".gz",FileMode.Create)){o.Write(new B[]{31,139,8,0,0,0,0,0,4,11},0,10);for(;i<l;i++){o.Write(new B[]{(B)(i<l-1?0:1),1,0,254,255,f[i]},0,6);c=p[(c^f[i])&0xFF]^c>>8;}c^=n;o.Write(new[]{(B)c,(B)(c>>8),(B)(c>>16),(B)(c>>24),(B)l,(B)(l>>8),(B)(l>>16),(B)(l>>24)},0,8);}}}

Much more readable:

using System.IO;
using B = System.Byte;
class X
{
    static void Main(string[] a)
    {
        // Read file contents
        var f = File.ReadAllBytes(a[0]);
        int l = f.Length, i = 0, j;

        // Initialise table for CRC hashsum
        var p = new uint[256];
        for (uint k = 0, r = 0; k < 256; r = ++k)
        {
            for (j = 0; j < 8; j++)
                r = r >> 1 ^ (r & 1) * 0xedb88320;
            p[k] = r;
        }

        uint c = ~(uint) 0, n = c;

        // Write the output file
        using (var o = File.Open(a[0] + ".gz", FileMode.Create))
        {
            // gzip header
            o.Write(new B[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 11 }, 0, 10);
            for (; i < l; i++)
            {
                // deflate block header plus one byte of payload
                o.Write(new B[] { (B) (i < l - 1 ? 0 : 1), 1, 0, 254, 255, f[i] }, 0, 6);
                // Compute CRC checksum
                c = p[(c ^ f[i]) & 0xFF] ^ c >> 8;
            }
            c ^= n;
            o.Write(new[] {
                // CRC checksum
                (B) c, (B) (c >> 8), (B) (c >> 16), (B) (c >> 24),
                // original file size
                (B) l, (B) (l >> 8), (B) (l >> 16), (B) (l >> 24)
            }, 0, 8);
        }
    }
}

Comments:

Expects path to file as first command-line argument.
Output file is input file + .gz.
I am not using any libraries to do the gzip, deflate or CRC32. It’s all in there.
This “compressor” increases the filesize by a factor of 6. But it’s in valid gzip format!
Tested using GNU gunzip and WinRAR.


Jelly, 12 bytes

L!_UÆ¡$œ?J’U

Try it online!

Explanation

We can basically see the two lists (the input and the output) as encoding an integer; the input encodes an integer in factorial base, and the output encodes an integer as a permutation. Luckily, Jelly has builtins that are already very close to both of these encodings, so it's simply a matter of writing small pieces of code to convert to an integer, then back to the other encoding.

L!_UÆ¡$œ?J’U
   U           Reverse {the input}
    Æ¡         and convert from base factorial to integer;
  _   $        subtract that from
L!             the factorial of the length of {the input};
       œ?      then take the nth permutation of
         J     [1,2,...,l], where l is the length of {the input},
          ’    subtract 1 from every elevent,
           U   and reverse it

In the case of base factorial, we can observe that the first element of the list must be 0, the second can be 0 or 1, the third must be 0/1/2, and so on. Thus, we have to reverse the input in order to get its elements into the normal writing order for base conversion.

Additionally, for the relative orders of the factorial conversion and the permutation conversion to match up with the operation that insertion sort uses, we need to make two adjustments: reversing the sequence of the permutations, and reversing the order of the output list. Reversing the output list is easy enough, needing only a U at the end of the program. To reverse the sequence of permutations, we subtract from the factorial of the input length (this works because the base factorial produces a number in the range 0 to (length!-1), whereas the permutations are numbered by Jelly from 1 to length!, producing an implicit off-by-one that cancels out the off-by-one that you normally get when subtracting a permutation index from a factorial).

Jelly, 9 bytes, in collaboration with @JonathanAllan

UÆ¡Nœ?J’U

This version of the program is very similar, but uses a different method of reversing the sequence of permutations; simply negating the input with N is enough to make œ? treat the order in reverse. Apart from that, it works identically to the previous program.

Try it online!


Output all numbers below certain number containing certain digits

Ruby, 186 181 177 bytes

a=gets.split;puts ([0]+(0...gets.to_i).select{|x|(x.to_s.split('')&a).any?}).each_cons(2).slice_before{|m,n|m+1<n}.map{|a|c=a.map &:last;c.count>9?[c[0],'-->',c.last]:c}.join' '

Ungolfed explanation:

# Read numbers from input and split into array
a = gets.split

# Loop from 0 to maximum number, exclusive
puts ([0]+(0...gets.to_i).select { |x|
  # Only include numbers that include at least one input digit
  (x.to_s.split('')&a).any?
})    # Add dummy element to the beginning of array
.each_cons(2)   # Get each array of 2 consecutive elements
.slice_before { |m, n| #
  m + 1 < n # "Slice" the array if m and n are not consecutive
}.map { |a|
  c = a.map &:last # Get all the last elements in `a`
  if c.count > 9
    # 10 or more consecutive elements. Get the first and last, and
    # an arrow in-between
    [c[0],'-->',c.last]
  else
    c
  end
}.join ' ' # Add space in-between all elements, and print result


44 bytes
Got this from \x y -> (fst x + fst y, snd x + snd y)

(<*>).((,).).(.fst).(+).fst<*>(.snd).(+).snd

Try it online!
Or, 42 bytes using do:
do a<-fst;((,).(a+).fst<*>).(.snd).(+).snd

Try it online!


PHP, 3 bytes

PHP

Try it online!

It looks like it outputs the language name, but it's actually the letters in reversed order.


Python 2, 201 bytes

array = input()
index = 0
while index < len(array) - 1:
	if index >= 0 and array[index] == array[index + 1]:
		array = array[:index] + array[index + 2:]
		index -= 1
		continue
	index += 1
print(array)

Try it online!

Optimizations thanks to Mr. Xcoder


JavaScript (ES6), Score 643
 656 651 646  642 bytes, no error
Returns an integer from 1 to 13.
s=>`qv%s!u.r0vPyqv*s"r'yqyu@y2r%{ }1u!v(u{y8|!ru;rur&z+z,w'z-{){{0x'r*z/{Py$t w#z,xFt,}qzr.{#s$t%vv6{@s&v z$x@{!{6v,sCr6s<v z.r s*w=w,r0u5s r){,y!s-s%v8t.xrqyWr7r?z#uBz9r&v#v5yBw+w"})vNw-u4sz)y"zEu/z r"}/rqw w\\t0|(r*rw(uAw&v {uYw#x wqz*|)v2u/|'v!r#sBs}0w&r2y&s r%r6w+}){"r2{-usqw'}C|/v$y={!r!x!t/rt>r1r"svuCy*{qr>v1x2r6x#{5{.wv8wGwqr!r:vJ|#r#u%uqst-}'r"z\`zqw uHy$sYr-z0w#|3{8x7vqz.w!|Ez$uvw!z.{t'w+{5x&|.xmrt"s,u"vuqwy{$t5u&s'wAv"vsTw#z%u*z0s r/w v#}+w'r9}0r0|AvxHv,r*}qw:x r3w}!u0v(w{qvv"y.rSr0w4yr#r.}qw"}%s"v#r!w!u/| tCs u`.replace(/[ -p]/g,c=>"q".repeat(c[C='charCodeAt']()-30))[C]([...s].map((c,i)=>s^=c[C]()<<i%5)|s%8788*3672%4051)%56

Try it online!
Or test all kaomojis.
How?
The input string is turned into an integer N with:
[...s].reduce((p, c, i) => p ^ c.charCodeAt() << i % 5, 0)

(using .map() instead of .reduce() in the golfed code)
Example for ٩(◕‿◕｡)۶:
 code | << |  shifted bit-mask
------+----+--------------------
 1641 |  0 |        11001101001
   40 |  1 |            101000.
 9685 |  2 |   10010111010101..
 8255 |  3 |  10000000111111...
 9685 |  4 | 10010111010101....
65377 |  0 |   1111111101100001
   41 |  1 |            101001.
 1782 |  2 |      11011110110..
------+----+--------------------
       XOR = 110010100100101110 = 207150

In the lookup string:

The emotions are encoded as 'q' to '}' (ASCII codes 113 to 125).
The characters ' ' to 'p' (ASCII codes 32 to 112) encode a run of consecutive 'q' (which, in addition to 'joy', also depicts an unused slot). The length of such a run is ord(c) - 30 (minimum = 2, maximum = 82).

We first expand the lookup string to 4048 characters by replacing /[ -p]/g with the runs of 'q' and then extract the relevant character with the following hash formula, which was found by brute-forcing some random values during a few minutes:
N % 8788 * 3672 % 4051

The final answer is the ASCII code of the character modulo 56.


Rebuild a rectangular array from a corner

Canvas, 1 byte

╬

Try it here!

Outputs as a multiline string


C#, 604 bytes

Complete program, accepts input (line-delimitated layout, no dimensions) from STDIN, outputs to STDOUT.

using C=System.Console;class P{static void Main(){int w=0,W,i,j,t,k,l,c;string D="",L;for(;(L=C.ReadLine())!=null;D+=L)w=L.Length;var R=new[]{-1,0,1,w,-w};L="X";for(W=i=D.Length;i-->0;){var M=new int[W];for(k=j=i;i>0;){M[j]=++k;t=j+R[c=D[j]%5];if(t<0|t>=W|c<3&t/w!=j/w|c>2&t%w!=j%w)break;j=t;if((l=M[j])>0){var J=new int[W+1];System.Func<int,int>B=null,A=s=>J[s]<0?0:J[k=B(s)]=k==W?k:i;B=x=>J[x]==x?x:B(J[x]);for(i=J[W]=W;i>0;)J[--i]=M[i]<l?i%w<1|i%w>w-2|i<w|i>W-w?W:i:-1;for(;i<W;)if(J[++i]<0)l=D[i]%5/2-1;else{A(i-1);if(i>w)A(i-w);}for(c=W;i-->0;L=""+(c>2?c:0)*l)c-=J[i]<0?0:B(i)/W;}}}C.WriteLine(L);}}

The program works by first reading in the layout, needless to say, and then iterating over every cell. We then run a 'snake' from each cell, which follows the arrows until it runs off the edge, or runs into itself. If it runs into itself, then we know we have found a loop (or one of those "><" things), and it also knows how much of the snake is in the loop.

Once we know we have a loop, we know which cells are on the loop, and we create a map from each cell (+1, for reasons) to either itself, -1 (means it's on the loop), or W (the whole width) if it's on the edge (or the +1 (which is at index W) to simplify things further one).

While we do this, we also find the direction that the 'last' element of the loop has (that is, the last element of the loop on the last row that has elements from the loop on it). This element must be a "<" or an "^", and this tells us the clockness (CW/CCW) of the loop (translated to -1/+1).

We then perform a disjoin set pass, which assigns all the elements that are outside the loop to the W set. We then subtract how many of these there are from W to get the number contained on and in the loop. If this number is less than 3, we replace it with 0. We multiply this by the clockness, set it as the result, and somehow escape from the for loops, where the result is output.

If, however, most of the above never happens (because no snake ever finds itself), then the result remains as "X", and that is outputted.

using C=System.Console;

class P
{
    static void Main()
    {
        int w=0, // width
        W, // full length
        i, // used for iterating over all the cells
        j, // keeps track of where the snake as got to
        t, // t is next j
        k, // how far along the snake we are, kind of
        // later on, k is used as temp for A
        l, // stores a threshold for how far along the snake the loop starts
        // later on, l stores the last seen pointer - this tells us the clockness
        c; // the translated direction
        // later on, c is a backwards-count

        string D="", // D is the map
        L; // used for reading lines, and then storing the result

        // might not be the best yay of doing this
        for(;(L=C.ReadLine())!=null; // read a line, while we can
            D+=L) // add the line to the map
            w=L.Length; // record the width

        var R=new[]{-1,0,1,w,-w}; // direction table (char%5) - might be able to replace this array with some bit bashing/ternary

        L="X"; // can't seem to fit this in anywhere... (don't strictly need to re-use L)
        for(W=i=D.Length;i-->0;) // for each cell, we send a 'snake' to try to find the loop from that cell
        {
            var M=new int[W]; // stores how far along the snake this point is

            for(k=j=i; // k's value doesn't really matter, as long as it's not stupidly big
                i>0;) // the i>0 check is just for when we return (see comment at the end of the code)
            {
                M[j]=++k; // store snake point and advance distance

                t=j+R[c=D[j]%5]; // t is position after move (translate <>v^ to 0234 (c is direction))
                //c=D[j]%5; // translate <>v^ to 0234 (c is direction)
                //t=j+R[c]; // t is position after move
                if(t<0|t>=W|c<3&t/w!=j/w|c>2&t%w!=j%w)
                    break; // hit an edge - will always happen if we don't find a loop - give up on this snake
                j=t; // move to new position

                if((l=M[j])>0) // we've been here before...
                {
                    // disjoint sets (assign all the edges to one set, assign all the ones on the line to another set, do adjacent disjoint, return size-outteredge (minus if necessary)
                    var J=new int[W+1]; // looks like we can reuse M for this

                    System.Func<int,int>B=null,
                    // whatever s points at should point to i, unless s points to W, in which case it should keep point to W
                    A=s=>J[s]<0?0:J[k=B(s)]=k==W?k:i;
                    // read the value this points to
                    B=x=>J[x]==x?x:B(J[x]);

                    for(i=J[W]=W;i>0;)
                        J[--i]=M[i]<l? // if we are not part of the loop
                            i%w<1|i%w>w-2|i<w|i>W-w? // if we are on the edge
                                W: // on the edge
                                i: // not on the edge
                             -1; // this is on the loop

                    // now fill in
                    // we don't have to worry about wrapping, the important bit being an un-wrapping closed loop
                    // i = 0
                    for(;i<W;)
                        if(J[++i]<0) // we are on the loop
                            l=D[i]%5/2-1; // last one must be ^(4) or <(0)
                        else{ // can probably crush this into an l returning l assigning term (with if above)
                            A(i-1);
                            if(i>w)
                                A(i-w);
                        }

                    // now count the number of non-edges
                    for(c=W; // assume everything is a non-edge
                        i-->0;
                        L=""+(c>2?c:0)*l) // set output to be number of non-edges * clockness (or 0 if too few)
                        c-=J[i]<0?0:B(i)/W; // subtract 1 if an edge (B(i) is W), othewise 0

                    // at this point, i is 0, so we will fall out of all the loops
                }
            }
        }

        C.WriteLine(L); // output result
    }
}


Python 2, 99 107 103 102 bytes

def f(s):S=s.split();T=zip(S,S[1:]+[s]);return' '.join(x+(' '+x+'_'+y)*(T.count((x,y))>1)for x,y in T)

Try it online!

Fixed the milk milk milk style edge cases.


Emacs Lisp, 335 bytes

Foreword. This answer and the Scheme ones are currently the only answers officially sanctioned by both the Mighty Popular Republic of LISP and the Church of Emacs. Other answers, shorter or not, are considered a threat to peace. In particular, and with a profound disdain to any libelious allegation of McCarthyism that is sporadically heard from hostile opponents of the state, we enjoin anyone who has information about the real identity of the anonymous  authors writing Nonlisp answers to contact your Local Bureau. It is reminded that everyone should take time to reflect and upvote in accordance to what he or she deeply believes will not threaten his or her future interactions with official representants of the power in place. Code is data. Data is code.

(defun p()(let(b(cpt 0)n)(goto-char 0)(while(search-forward"("()t)(setf b(point)n(number-to-string(incf cpt)))(backward-char)(forward-sexp)(backward-char)(kill-region b(point))(delete-backward-char 1)(delete-forward-char 1)(insert ""n"")(save-excursion(end-of-buffer)(newline 2)(insert ""n" ")(yank)(insert"")))))

More elegantly:

(defun parens ()
  (let (b(cpt 0)n)
    (goto-char 0)
    (while(search-forward"("()t)
      (setf b(point)n(number-to-string(incf cpt)))
      (backward-char)
      (forward-sexp)
      (backward-char)
      (kill-region b(point))
      (delete-backward-char 1)
      (delete-forward-char 1)
      (insert ""n"")
      (save-excursion
       (end-of-buffer)
       (newline 2)
       (insert ""n" ")
       (yank)
       (insert "")))))


Figure out the maximum amount of candy a child can collect

Jelly, 58 bytes

Ø+0r;U$ṗµØ1W;⁸+\Q%“.þ‘)ẎẠ$Ƈµ20Ḋ×©5Ḋ+þ14Ḋ×⁵¤⁺;"Wɼ;ŒBm0⁸œị§Ṁ

Try it online!

Very slow (brute force), TIO can handle up to 8. Test cases in \$[0,8]\$: Try it online!


Write The Shortest Program To Check If A Binary Tree Is Balanced

Jelly, 11 bytes

ḊµŒḊ€IỊ;ß€Ạ

Try it online!

The empty tree is represented by [].


Python 3: 974 chars [nb]
Further beat with the ugly stick, see notebook on GH-Gist. Python 3 has built-in ASCII-85 encoding, which helps with the zipped saus. 3's more advanced built-in compression algorithms (LZMA) don't seem to work well with such small things.
Zipping is very fickle about changing characters around, was almost tempted to write something that would randomly try different 1-letter names for variables to minimize the zipped size.
Python 2: 1420 1356 1085 1077 characters

I read the first argument passed when called, which can be a string up to 106-ish characters long. The output is always a version 5-L QR code and mask 4 which means it's 37x37 modules large and can only handle ~5% damage.
The program's only dependencies are numpy (array manipulations) and matplotlib (display only); all Reed-Solomon encoding, data packing, and module layout is handled within the provided code.  For RS, I basically robbed the Wikiversity functions...it's still kind of a black-box for me.  Learned a ton about QR in any event.
Here's the code before I beat it with the ugly stick:
import sys
import numpy as np
import matplotlib.pyplot as plt
# version 5-L ! = 108 data code words (bytes), 106 after metadata/packing

### RS code stolen from https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#RS_generator_polynomial
gf_exp = [1] + [0] * 511
gf_log = [0] * 256
x = 1
for i in range(1,255):
    x <<= 1
    if x & 0x100:
        x ^= 0x11d
    gf_exp[i] = x
    gf_log[x] = i
for i in range(255,512):
    gf_exp[i] = gf_exp[i-255]

def gf_mul(x,y):
    if x==0 or y==0:
        return 0
    return gf_exp[gf_log[x] + gf_log[y]]

def main():
    s = sys.argv[1]

    version = 5
    mode = 4 # byte mode
    dim = 17 + 4 * version
    datamatrix = 0.5 * np.ones((dim, dim))
    nsym = 26

    # PACK
    msg = [mode * 16, len(s) * 16] + [ord(c) << 4 for c in s]
    for i in range(1, len(msg)):
        msg[i-1] += msg[i] // 256
        msg[i] = msg[i] % 256

    pad = [236, 17]
    msg = (msg + pad * 54)[:108]

    # MAGIC (encoding)
    gen = [1]
    for i in range(0, nsym):
        q = [1, gf_exp[i]]
        r = [0] * (len(gen)+len(q)-1)
        for j in range(0, len(q)):
            for i in range(0, len(gen)):
                r[i+j] ^= gf_mul(gen[i], q[j])
        gen = r
    msg_enc = [0] * (len(msg) + nsym)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]
    for i in range(0, len(msg)):
        coef = msg_enc[i]
        if coef != 0:
            for j in range(0, len(gen)):
                msg_enc[i+j] ^= gf_mul(gen[j], coef)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]

    # PATTERN
    # position marks
    for _ in range(3):
        datamatrix = np.rot90(datamatrix)
        for i in range(4):
            datamatrix[max(0, i-1):8-i, max(0, i-1):8-i] = i%2
    datamatrix = np.rot90(datamatrix.T)

    # alignment
    for i in range(3):
        datamatrix[28+i:33-i, 28+i:33-i] = (i+1)%2

    # timing
    for i in range(7, dim-7):
        datamatrix[i, 6] = datamatrix[6, i] = (i+1)%2

    # the "dark module"
    datamatrix[dim-8, 8] = 1

    # FORMAT INFO
    L4 = '110011000101111' # Low/Mask4
    ptr_ul = np.array([8, -1])
    steps_ul = [0, 1] * 8 + [-1, 0] * 7
    steps_ul[13] = 2 # hop over vertical timing
    steps_ul[18] = -2 # then horizontal

    ptr_x = np.array([dim, 8])
    steps_x = [-1, 0] * 7 + [15-dim, dim-16] + [0, 1] * 7

    for bit, step_ul, step_x in zip(L4, np.array(steps_ul).reshape(-1,2), np.array(steps_x).reshape(-1,2)):
        ptr_ul += step_ul
        ptr_x += step_x
        datamatrix[tuple(ptr_ul)] = int(bit)
        datamatrix[tuple(ptr_x)] = int(bit)

    # FILL
    dmask = datamatrix == 0.5

    cols = (dim-1)/2
    cursor = np.array([dim-1, dim]) # starting off the matrix
    up_col = [-1, 1, 0, -1] * dim
    down_col = [1, 1, 0, -1] * dim
    steps = ([0, -1] + up_col[2:] + [0, -1] + down_col[2:]) * (cols/2)
    steps = np.array(steps).reshape(-1, 2)
    steps = iter(steps)

    # bit-ify everything
    msg_enc = ''.join('{:08b}'.format(x) for x in msg_enc) + '0' * 7 # 7 0's are for padding
    for bit in msg_enc:
        collision = 'maybe'
        while collision:
            cursor += steps.next()
            # skip vertical timing
            if cursor[1] == 6:
                cursor[1] = 5
            collision = not dmask[tuple(cursor)]
        datamatrix[tuple(cursor)] = int(bit)

    # COOK
    mask4 = lambda i, j: (i//2 + j//3)%2 == 0
    for i in range(dim):
        for j in range(dim):
            if dmask[i, j]:
                datamatrix[i, j] = int(datamatrix[i, j]) ^ (1 if mask4(i, j) else 0)

    # THE PRESTIGE
    plt.figure(facecolor='white')
    plt.imshow(datamatrix, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.axis('off')
    plt.show()

if __name__ == '__main__':
    main()

After:
import sys
from pylab import*
n=range
l=len
E=[1]+[0]*511
L=[0]*256
x=1
for i in n(1,255):
 x<<=1
 if x&256:x^=285
 E[i]=x;L[x]=i
for i in n(255,512):E[i]=E[i-255]
def f(x,y):
 if x*y==0:return 0
 return E[L[x]+L[y]]
m=sys.argv[1]
m=[ord(c)*16 for c in'\4'+chr(l(m))+m]
for i in n(1,l(m)):m[i-1]+=m[i]/256;m[i]=m[i]%256
m=(m+[236,17]*54)[:108]
g=[1]
for i in n(26):
 q=[1,E[i]]
 r=[0]*(l(g)+l(q)-1)
 for j in n(l(q)):
    for i in n(l(g)):r[i+j]^=f(g[i],q[j])
 g=r
e=[0]*134
for i in n(108):
 e[i]=m[i]
for i in n(108):
 c=e[i]
 if c:
    for j in n(l(g)):e[i+j]^=f(g[j],c)
for i in n(108):e[i]=m[i]
m=.1*ones((37,)*2)
for _ in n(3):
 m=rot90(m)
 for i in n(4):m[max(0,i-1):8-i,max(0,i-1):8-i]=i%2
m=rot90(m.T)
for i in n(3):m[28+i:33-i,28+i:33-i]=(i+1)%2
for i in n(7,30):m[i,6]=m[6,i]=(i+1)%2
m[29,8]=1
a=array
t=tuple
g=int
r=lambda x:iter(a(x).reshape(-1,2))
p=a([8,-1])
s=[0,1]*8+[-1,0]*7
s[13]=2
s[18]=-2
P=a([37,8])
S=[-1,0]*7+[-22,21]+[0,1]*7
for b,q,Q in zip(bin(32170)[2:],r(s),r(S)):p+=q;P+=Q;m[t(p)]=g(b);m[t(P)]=g(b)
D=m==0.1
c=a([36,37])
s=r(([0,-1]+([-1,1,0,-1]*37)[2:]+[0,-1]+([1,1,0,-1]*37)[2:])*9)
for b in ''.join('{:08b}'.format(x) for x in e):
 k=3
 while k:
    c+=s.next()
    if c[1]==6:c[1]=5
    k=not D[t(c)]
 m[t(c)]=g(b)
a=n(37)
for i in a:
 for j in a:
    if D[i,j]:m[i,j]=g(m[i,j])^(j%3==0)
imshow(m,cmap=cm.gray_r);show()

(relying on a tab to count as 4/8/whatever number of spaces >= 2., not sure how well it will copy)
Because it's so long, we can zip it (saw someone do this somewhere else, forgot who though :( ) to save some more characters, bringing the total down to 1085 1077 because pylab is filthy:
import zlib,base64
exec zlib.decompress(base64.b64decode('eJxtU0tzmzAQvvSkX6FLaglkyiM2hHRvyS2HZNobo3QwwY6IBVjQFrfT/96V3KR4Wg5I+/6+3ZXSfWdGOhwHsjWdpv1xX26oclqPtGDKdleTPezrltxCEUm/CKW3iiJyB/YWr9ZkgohsO0MVVS1tWSTi1YrnhE4fP6KFqi2d3qNfPj1CnK0IvS2UhOn6rpgkqHkkxolVFPPceeBviRpJnuot3bJJHG1Sm807AoS5qcevpqUhoX9ut4VN6d8VRymJBuQUlGb3DUGjVHTmiVXci9bUVqyw4uLdwq+eDdszzbmv5TkJp801gkDSgKf8gCSu7cVJF5a6Bqb9Ik7WIkqxLZe8yKMwk2RnW3VGbW3BH1AtLDmJoF3/sPiO+3t24MuIEwetOUVYnY3Bb5bHuvPcFMpv5CNs2Q6TiUPRSAzegSG1yxoll2dkwsxmql+h/8dWgbW69lY5favazKvWs6qNFBX/J8/fChqCyOvaemAsSQX34pPzl5NzYktqMN14FWKbyZzhpW26LicWCmw9z7OlEucibs1FTN7Cg89nQBIbH2e+ypMEQ99uEpjyI46RM+dUJKEbslhb4Gsxc8MsVyKTuMIllMaURzLC+LXf1zhd1Y7EwL7Um6eSTrkaa8NKNvHA1MNz2ddsia+Ac9JDyYpM4ApxMuBoRCS9zC/QilNKyVBEiYTYnlhoGZN7648Ny9D/E7z6YUAci9g9PpshdRQ24iAeLI0fqmcbhczjKA15EedSGDZw/H3CqfU+HK7vfXjA1R1ZzyXs2IY74f6PQG5A44sKIlK5+muRpA6wYQwr2gfALBZEYwUvSV0V/832j4l7V6ehbCzAxSJoOgS4+JmH2ebXIkCLLkfslxv8ZH1quxIvkBD6/Vnta/pyWv3KhyFo62lk3Ml2P/FpAaxzd66c9gXabqQ3SKniuMT6dDlxKwE7k85WpMxn76zMX9Pe4BI00u1CY0NPF/7ImosEm8OJ0sNz951pUemyh0oHO9yJL4ZfOzX/DQ2mdSs='))

If you replace the last line with the following (it adds 62 chars), you get nearly-perfect output, but the other still scans, so whatever.
figure(facecolor='white');imshow(m,cmap=cm.gray_r,interpolation='nearest');axis('off');show()


05AB1E, 21 20 19 18 bytes
Thanks to Kevin Cruijssen for -1 byte!
-1 byte inspired by xash's Brachylog answer!
[¼¾ƒ²L¾ÑN-K¹Qi¾N‚q

Try it online!
or
Try most test cases! (based on the test-suite by FryAmTheEggman for this answer.)
            # see below for the remainder of the code
²L          # push [1 .. b]
  ¾Ñ        # push the divisors of n
    N-      # subtract k from each
            # this is now a list of all x in [-k+1 .. n-k] with n%(x+k)==0
      K     # remove this from [1 .. b]
       ¹Q   # is this equal to S?

05AB1E, 24 23 bytes
First line of input is the set \$S\$, second one \$b\$.
[¼¾ƒ¾¹²L‚N+Ö_O¹gªËi¾N‚q

Try it online!
This iterates through all possible pairs in lexicographical order and checks for each pair:
\begin{align*}
\left|S\right| &=\left|\left\{ x \in [1 .. b] \mid x \;\text{does not divide}\; n  \right\}\right| \\&= \left|\left\{ x \in S \mid x \;\text{does not divide}\; n  \right\}\right|
\end{align*}
Commented:
[                # infinite loop
 ¼¾              # increment and push the counter (n)
   ƒ             # for N(=k) in [0 .. n]:
¾                #   push n
 ¹               #   push the first input (S)
  ²L             #   push [1 .. second input (b)]
    ‚            #   pair these two lists up
     N+          #   add current k to both lists
       Ö_        #   do they not divide n (vectorizes)
         O       #   sum both lists
          ¹g     #   push the length of S
            ª    #   append this to the list
             Ë   #   are all equal?
i                #   if this is true:
 ¾               #     push n
  N              #     push k
   ‚             #     pair n and k
    q            #     quit the program (implicit output)


Perl 5, 92 bytes

90 bytes of code + -pl flags.

sub f{($b=$h{$a=pop}//$a)!=$a?f($b):$a}s%(\d+)\+(\d+)%f($1)+f$2%e&&redo;/=/;$_=$h{f$`}=f$'

Try it online!

I use the hashtable %h to store the mapping between numbers.
The function (sub) f returns the number to which its input map (or its input if it's mapped to no number): $h{$a=pop} retrieves the number toward which the input maps. If it's none, thanks to //$a, the value of ($b=$h{$a=pop}//$a) is the input ($a). We make sure that this values isn't the input itself to not loop infinitely (!=$a). Then, we either recursively call f or return the input.
The main program consists of two steps:
  - s%(\d+)\+(\d+)%f($1)+f$2%e&&redo evaluates the first addition on the right side, while there is still an addition: it replaces x+y by the result of the evaluation of f(x)+f(y).
  - /=/;$_=$h{f$`}=f$' does the assignment: /=/ allows to access the left side with $` and the right side with $', then $h{f$`}=f$' does the assignment. And we also assign it to $_ that is implicitly printed after each line.


05AB1E, 6 bytes
Code:
>GNÞR,

Try it online!
Explanation:
>       # Increment, pushes input + 1
 G      # For N in range(1, input + 1):
  N     # Push N
   Þ    # Convert to double, which appends `.0` at the end of an integer
    R   # Reverse top of the stack
     ,  # Pop and print with a newline

Uses CP-1252 encoding.


Python, 48

lambda n:[i for i in range(2**n)if'01'in bin(i)]

I had been vastly overthinking this. We just need to check if the binary expansion contains '01'.
For there to be two runs of ones, the one on the right must be preceded by a 0. If there's only one run, there won't be any leading 0's, so that won't happen.

Old answer:
lambda n:[i for i in range(2**n)if len(set(bin(i).split('0')))>2]

The Python binary representation works very nicely here. A binary number is written like bin(9)=='0b10110'. Splitting at '0' results in a list of

Empty strings to the left of the initial 0, between any two consecutive 0's, and to the right of any final 0
The letter b followed by one or more leading ones
Runs of 1's that are not leading

The first two categories always exist, but the last one only exists if there is a run one 1's that doesn't contain the leading '1', and so only if there's more than one run of 1's. So, it suffices to check if the list contains more than 2 distinct elements.
Python 3.5 saves 2 chars by unpacking {*_} in place of set(_).


Pyth, 18
V5sOMcR\|scR\{cz\}

Try it online here
Explanation:
V5sOMcR\|scR\{cz\}                     : z = input()
V5                                     : do this 5 times
              cz\}                     : split z on the } character
          cR\{                         : split each element of the resulting list on {
         s                             : join the list of lists back into a list of strings
     cR\|                              : split these strings on the | character
   OM                                  : Choose a random element from each inner list
  s                                    : join those choices, and print them


Ruby: 52 - 10 = 42

Using a variation of that famous prime-matching regex.

puts ?_*gets.to_i=~/^(_|(__+?)\2+)$/?"Not!!":"Prime"

Just to be clear: ?_*gets.to_i is a string operation that appends "_" to itself n times, where n is the input number. As I see it no string lengths are compared, so that should satisfiy the 10 character bonus criterium.


How could I reduce the length of this code?

Python 3, 107

a,b,x,y=map(int,input().split())
A=abs(a-x);B=abs(b-y)
while 1:print('SN'[b>y][:B]+'WE'[a>x][:A]);A-=1;B-=1

A different strategy to generate the directions, tracking each coordinate's absolute displacement to the goal rather than the actual location.

For the horizontal direction, finds the absolute displacement A=abs(a-x) and direction character 'WE'[a>x]. Simulates going towards the goal by decrementing A and printing the direction character as long as we haven't already reached the goal coordinate (A>0). Does the same for vertical.


JavaScript (Node.js),  819  779 bytes
Returns 0 for undefined TIO uniqueness.
s=>(B=Buffer)('J .!> . 8 " .  . 0 L"0"c$E"~~~="8"~1 Y$^"~~~j S$x"P S$;"7 @ Z G"/$8$A :%X!T%A G M$c*h"d"L!Q$8"~F$.$>"s$@"`"E 3 1$r"U">"8 F&~Y"="z"~Q"F"E"g |"R%m!c$"~N"~?$Q  1 ~W B$k"F ="d$> U"7%"""F"X%Y%s"S$E"<-O$b _"]"?$3 <$B i"0"~A"W">$6 L `"I%2"1"?$6"M "A _$2"A ="; T"t @$:"q"N i"["V&~= z"5"1 I!N"8"Z ` ~~B 4"1 }"#"2$."e P F ;!A"W$K G">$9$K"T M*W #"8 < 0"A ]""~~J Z""m"0"V!; ~~[ h+$2$~^"1"3$1"3 A$}"D"~i"9 H%N"~3 9 K"~4"; C%C"Q"3"/ X ^"D"9$4 4 /"7 J":$$0*o"~<"Z 9"T"I"~D$5"@ 1"j ". ~c"O$4"3 O ~X 6$K"I ~8 F  d$T } 6"#"V"W";$I$0 H$R"x$"[$6 j i"U"~M L"K$~~h W$L O"0%="Z 4"F$X"6!?$;"4"M"~0$~1%r"k"6"K"^"2 5$V v"4"J"z 1"1 H$;$W"#">!i"."V"V$e"6$~~<*~C!~/"7 8!/ q$3"U /"."? t"Y"J!<$4 i"~P K"Y'.replace(/[.-~]/g,c=>'#'.repeat(B(c)[p=0]-44))[B(s).map(c=>p=(p*79^c)>>>0)|p%12635])[0]-32

Try it online! (test cases)
Try it online! (all languages)
How?
There are only \$10\$ distinct TIO uniqueness values, ranging from \$0\$ to \$13\$. Besides, more than 50% of the languages have a TIO uniqueness of \$3\$.
 uniq. | count | ratio
-------+-------+--------
   0   |   97  | 14.24%
   1   |   12  |  1.76%
   2   |  140  | 20.56%
   3   |  357  | 52.42%
   4   |   56  |  8.22%
   5   |   11  |  1.62%
   6   |    2  |  0.29%
  10   |    4  |  0.59%
  11   |    1  |  0.15%
  13   |    1  |  0.15%
We need:

a function \$H_0\$ that turns the language name \$s\$ into an integer \$H_0(s)\$
a function \$H_1\$ and a corresponding lookup table \$T\$ so that the TIO uniqueness of the language is \$T[H_1(H_0(s))]\$

It seems unlikely to find some simple functions \$H_0\$ and \$H_1\$ that would directly lead to a small lookup table. But if we use \$3\$ (the most common uniqueness) as the padding value for unused slots, the table is going to contain a lot of \$3\$'s.
So our strategy is to use:

the first 14 printable ASCII characters (32 to 45, i.e.   to -) to encode the actual uniqueness values other than \$3\$
all other printable characters (46 to 126, i.e. . to ~) to encode runs of 2 to 82 consecutive \$3\$'s

Conveniently, the single quote ' (ASCII code 39) will never appear in the table because no language has a uniqueness of 7. So we can use it as our string delimiter and safely use " and ` in the table without having to escape them.
We now need to find \$H_0\$ and \$H_1\$ so that the distribution of actual uniqueness values among the \$3\$'s leads to the smallest table with this simple compression scheme.
After some brute-forcing, it turns out that the following functions work reasonably well:

Buffer(s).reduce((p, c) => p * 79 ^ c) >>> 0 (actually implemented with a .map())
% 12635


OOP syntax in Haskell

import Prelude hiding ((.))
a . b = b a

Objects can have properties:

[1,5,3,2].length -- 4
[1,5,3,2].maximum -- 5
'a'.succ -- 'b'

...and methods:

"Hello world!".take(5) -- "Hello"
"Hello world!".splitAt(2) -- ("He","llo world!")
"Hello world!".map(toUpper) -- "HELLO WORLD!"


APL 66 51
' *'[1+(⌽⍳b)∘.≤v←+/(⍳b)∘.=⌈x[⍋x]÷(⌈/x←1↓v)÷b←↑v←⍎⍞]

Using the example I quoted in my comment on the question where the bin size is 2.25:
4 1 1 2 2 5 8 9 6 3

*
*
* **
****


Convert the Binary Champernowne Constant to Decimal

Python 119 bytes

import sys
r=i=n=0
while 1:
 i+=1
 for b in bin(i)[2:]:n+=1;r=r*10+int(b)*5**n;~n%4or sys.stdout.write(('0.'+`r`)[n/4])

Given unlimited memory, this will run indefinitely, although it does slow down quite a bit after the first few thousand digits.

Each binary bit is treated as its corresponding power of 5, i.e:
0.1 ⇒ 5, 0.01 ⇒ 25, 0.001 ⇒ 125, 0.0001 ⇒ 625, etc.

Which lends itself nicely to a decimal conversion, as:
1/2 = 0.5, 1/4 = 0.25, 1/8 = 0.125, 1/16 = 0.0625, etc.

The variable r stores a running total of all bits so far (increasing by a factor of 10 each iteration), and every four bits the next digit is output. This is mathematically correct, because log2(10) ≈ 3.321928
which means that every 3.32 or so binary bits will produce one decimal digit. 10/3 is a better upper bound, but I chose 4 for sake of brevity.

Ruby 80 bytes

r=i=n=0
$><<gsub(/./){"0.#{r=r*10+$&.to_i*5**n+=1}"[n/4,n%4/3]}while$_='%b'%i+=1

Same algorithm as above. It's been a while since I've golfed Ruby, so I may be missing a few tricks.

GolfScript 53 bytes

0:µ.{).2base{5µ):µ?*@10*+.'0.'\+µ4/<µ(4/>print\}/.}do

Once again, same algorithm. This is one of the first things I've ever written in GolfScript, so I'm fairly certain that it can be reduced further. I've chosen to use µ (char 181) as a variable name, because it saves a whitespace in the expression µ4/.


Generate n digits of Gijswijt's sequence

Pyth, 25 22 21 bytes

t_u+eSmtfxG*Td1._GGQN

OP confirmed that we only need to handle single-digit numbers. This allowed to store the list as a string of digits. -> Saved 3 bytes

Try it online: Demonstration

Explanation:

t_u+...GQN      implicit: Q = input number
         N      start with the string G = '"'
  u     Q       do the following Q times:
    ...            generate the next number
   +   G           and prepend it to G
 _              print reversed string at the end
t               remove the first char (the '"')

And here's how I generate the next number:

eSmtfxG*Td1._G
           ._G    generate all prefixes of G
  m               map each prefix d to:
    f     1          find the first number T >= 1, so that:
       *Td              d repeated T times
     xG                 occurs at the beginning of G
 S                  sort all numbers
e                   take the last one (maximum)

21 bytes with lists

_u+eSmhhrcGd8SlGGtQ]1

Try it online: Demonstration

Uses the same ideas of Martin and Peter. At each step I split the string into pieces of length 1, pieces of length 2, ... Then I range-length-encode them and use the maximal first run as next number.

20 bytes with strings

t_u+eSmhhrcGd8SlGGQN

Try it online: Demonstration

Combines the ideas of the two codes above.


MATL, 6 bytes
"@?@}x

Input is a row vector of numbers.
The final stack is shown upside down, with the most recent element below.
Try it online! Or verify all test cases.
Explanation
"         % For each element in the input (implicit)
  @       %   Push current element
  ?       %   If non-zero (this consumes the current element)
    @     %     Push current element again
  }       %   Else
    x     %     Delete most recent element
          %   End (implicit)
          % End (implicit)
          % Display (implicit)


The Partition Problem - Sorting Stacks of Boxes

Python 2, 321 317 321 319
import itertools as l
t=raw_input();e=0;g=l.permutations(int(k)for k in t[1:])
try:
 while not e:
  a=list(g.next());c=[sum(a[:i+1])for i in range(len(a))];s=c[-1];d=int(t[0]);f=s/d;assert f*d==s;r=range(f,s,f);e=set(r)<=set(c);b=[`k`for k in a]
 for k in r[::-1]:b.insert(c.index(k)+1,'\n')
 print ''.join(b)
except:''

Some examples:
echo 43 | python part.py

echo 3912743471352 | python part.py
9124
7342
7135

echo 342137586 | python part.py
426
138
75

Thanks to theonlygusti for fixing the stdin input, and shaving off some chars and to Maltysen for pointing out a typo.


def method():
    if 'a' not in vars():a=0
    a+=1
    if 'a' not in vars():a=0
    a+=1
    print(a)

Initializes the variable a to 0 only if it's not already initialized in the variables table. Then, increments it.

More briefly (thanks to histocrat for len):

def method():
    a=len(vars())+1
    a=len(vars())+1
    print(a)

If the two copies of X could be on the same line, we could do

a=0;a+=1;a

which doubles to

a=0;a+=1;aa=0;a+=1;a

with the "sacrificial lamb" aa eating up the second variable assignment.


GolfScript (2 chars)

~^

This is familiar to anyone who knows anything at all about combinatorial game theory.


Output a primitive element for each field size


Jelly,  16 14 11 10 9  8 bytes

-1 thanks to Lynn (mod-2; logical NOT; add to self: Ḃ¬+ -> bitwise OR with 1:|1)

|1×r)ẎQi

A monadic Link accepting an integer, n, which yields an integer, a(n).

Try it online! (very inefficient since it goes out to layer \$\lceil\frac n2\rceil\$)

An 11-byte version, ½‘|1×rƲ€ẎQi, completes all but the largest test case in under 30s - Try it at TIO - this limits the layers used to \$\lceil\frac{\lfloor\sqrt n\rfloor+1}2\rceil\$.

How?

The permutation is to take the natural numbers in reversed slices of lengths [1,5,3,11,5,17,7,23,9,29,11,35,13,...] - the odd positive integers interspersed with the positive integers congruent to five modulo six, i.e [1, 2*3-1, 3, 4*3-1, 5, 6*3-1, 7, 8*3-1, 9, ...].

This is the same as concatenating and then deduplicating reversed ranges [1..x] of where x is the cumulative sums of these slice lengths (i.e. the maximum of each slice) - [1,6,9,20,25,42,49,72,81,110,121,156,169,...], which is the odd integers squared interspersed with even numbers multiplied by themselves incremented, i.e. [1*1, 2*3, 3*3, 4*5, 5*5, 6*7, 7*7,...].

Since the differences are all greater than 1 we can save a byte (the reversal) by building ranges [x..k] directly, where k is the 1-indexed index of the slice.

Due to this structure the permutation is a self-conjugate permutation, i.e. we know that \$P(n) = v \iff P(v) = n\$, so rather than finding the value at (1-indexed) index n (|1×r)ẎQị@) we can actually get the (1-indexed) index of the first occurrence of n (|1×r)ẎQi).

|1×r)ẎQi - Link: integer, n       e.g. 10
    )    - for each k in [1..n]:  vs = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
|1       -   bitwise-OR (k) with 1     [ 1, 3, 3, 5, 5, 7, 7, 9, 9,11]
  ×      -   multiply (by k)           [ 1, 6, 9,20,25,42,49,72,81,110]
   r     -   inclusive range (to k)    [[1],[6..2],[9..3],[20..4],...,[110..10]]
     Ẏ   - tighten                     [1,6,5,4,3,2,9,8,7,6,5,4,3,20,...,4,......,110,...,10]
      Q  - de-duplicate                [1,6,5,4,3,2,9,8,7,20,...,10,......,110,...82]
       i - first index with value (n)  20


Python 2, 153

u=[1]*999;i=60;exec"u[i]=i%30*u[i-30]+u[i-29];i+=1;"*900
def x(l,n,a=0):m=u[30*l+a];c=n>=a*m;return'.'*l and chr(65+min(n/m,a))+x(l-1,[n%m,n-m*a][c],a+c)

It uses alphabetical order and 0-based indexing.
Let l denote the length of a suffix of the letters and a denote the number of distinct letters that were used in the preceding part. Then a function p(l,a) that calculates the number of ways to select the remaining letters could be 40 bytes:
p=lambda l,a:l<1or a*p(l-1,a)+p(l-1,a+1)

However, this is too slow for the challenge, so instead the necessary values are precalculated and stored in the u array. At each stage of the calculation, if the next letter is the one of the a already used, the n = k * p(l - 1, a) + n' where k is the 0-indexed letter of the alphabet and n' is the value of n for the next function call, which contains the information about the remaining letters. If a new letter is used, then n = a * p(l - 1, a) + n'.


Triangular Lattice Points close to the Origin

Python 2, 43 bytes

f=lambda n,a=1:n*n<a/3or n*n/a*6-f(n,a+a%3)

Try it online!

This is black magic.

Offering 250 rep for a written-up proof. See Lynn's answer for a proof and explanation.


Counting from 1 to n without any consecutive numbers

Mathematica, 58 bytes, polynomial(n) time

Abs[Sum[(k-1)Hypergeometric2F1[k,k-#,2,2](#-k)!,{k,#}]-1]&

How it works

Rather than iterating over permutations with brute force, we use the inclusion–exclusion principle to count them combinatorially.

Let S be the set of all permutations of [1, …, n] with σ1 = 1, σn = n, and let Si be the set of permutations σ ∈ S such that |σi − σi + 1| = 1.  Then the count we are looking for is

|S| − |S1 ∪ ⋯ ∪ Sn − 1| = ∑2 ≤ k ≤ n + 1; 1 ≤ i2 < ⋯ < ik − 1 < n (−1)k − 2|Si2 ∩ ⋯ ∩ Sik − 1|.

Now, |Si2 ∩ ⋯ ∩ Sik − 1| only depends on k and on the number j of runs of consecutive indices in [i1, i2, …, ik − 1, ik] where for convenience we fix i1 = 0 and ik = n. Specifically,

|Si2 ∩ ⋯ ∩ Sik − 1| = 2j − 2(n − k)!, for 2 ≤ j ≤ k ≤ n,
|Si2 ∩ ⋯ ∩ Sik − 1| = 1, for j = 1, k = n + 1.

The number of such index sets [i1, i2, …, ik − 1, ik] with j runs is

(k − 1Cj − 1)(n − kCj − 2), for 2 ≤ j ≤ k ≤ n,
1, for j = 1, k = n + 1.

The result is then

(−1)n − 1 + ∑2 ≤ k ≤ n ∑2 ≤ j ≤ k  (−1)k − 2(k − 1Cj − 1)(n − kCj − 2)2j − 2(n − k)!

The inner sum over j can be written using the hypergeometric 2F1 function:

(−1)n − 1 + ∑2 ≤ k ≤ n (−1)k(k − 1)2F1(2 − k, k − n; 2; 2)(n − k)!

to which we apply a Pfaff transformation that lets us golf away the powers of −1 using an absolute value:

(−1)n − 1 + ∑2 ≤ k ≤ n (−1)n(k − 1)2F1(k, k − n; 2; 2)(n − k)!
= |−1 + ∑1 ≤ k ≤ n (k − 1)2F1(k, k − n; 2; 2)(n − k)!|.

Demo

In[1]:= Table[Abs[Sum[(k-1)Hypergeometric2F1[k,k-#,2,2](#-k)!,{k,#}]-1]&[n],{n,50}]

Out[1]= {1, 0, 0, 0, 0, 2, 10, 68, 500, 4174, 38774, 397584, 4462848,

>    54455754, 717909202, 10171232060, 154142811052, 2488421201446,

>    42636471916622, 772807552752712, 14774586965277816, 297138592463202402,

>    6271277634164008170, 138596853553771517492, 3200958202120445923684,

>    77114612783976599209598, 1934583996316791634828454,

>    50460687385591722097602304, 1366482059862153751146376304,

>    38366771565392871446940748410, 1115482364570332601576605376898,

>    33544252621178275692411892779180, 1042188051349139920383738392594332,

>    33419576037745472521641814354312790,

>    1105004411146009553865786545464526206,

>    37639281863619947475378460886135133496,

>    1319658179153254337635342434408766065896,

>    47585390139805782930448514259179162696722,

>    1763380871412273296449902785237054760438426,

>    67106516021125545469475040472412706780911268,

>    2620784212531087457316728120883870079549134420,

>    104969402113244439880057492782663678669089779118,

>    4309132147486627708154774750891684285077633835734,

>    181199144276064794296827392186304334716629346180848,

>    7800407552443042507640613928796820288452902805286368,

>    343589595090843265591418718266306051705639884996218154,

>    15477521503994968035062094274002250590013877419466108978,

>    712669883315580566495978374316773450341097231239406211100,

>    33527174671849317156037438120623503416356879769273672584588,

>    1610762789255012501855846297689494046193178343355755998487686}


Python 2 + sequtils, 101 bytes

from sequtils import*;_='from sequtils import*;_=%r;print edit(_%%_,input())';print edit(_%_,input())


Shortest code to determine if a string is a palindrome

K, 25
{x~|x:_x@&x in,/.Q`a`A`n}

.
k){x~|x:_x@&x in,/.Q`a`A`n}"Eva, can I stab bats in a cave?"
1b


How to improve Ruby code under some restrictions

105

You can save three bytes by declaring n as a local variable (instead of a global) before f:

n=?~.ord
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:n}
h=[],n,[]
h=f[h]until h==p(n+=n)-n


Decompose binary into alternating subsequences

Pyth, 17 16 bytes

1 byte thanks to Jakube

iR2cJ.BQx1qVJ+dJ

Demonstration

A nice, clever solution. Uses some lesser known features of Pyth, like x<int><list> and c<str><list>.

iR2cJ.BQx1qVJ+dJ
                    Q = eval(input())
    J.BQ            Store in J the input in binary.
          qV        Vectorize equality function over
            J+dJ    J and J with a leading dummy char, to get the offset right.
                    This calculates whether each element matches its successor.
        x1          Find all of the indexes of 1 (True) in this list.
   cJ                Chop J at those locations.
iR2                  Convert from binary back to base ten and output.


J, 18 bytes

5 bytes thanks to Dennis.

+/e.[:,/2*+/\-/+/\

@HelkaHomba: Nope.

Usage

>> f =: +/e.[:,/2*+/\-/+/\
>> f 6 6 12 12 12 11 1 12
<< 4
>> f 10 20 10 1
<< 0

Ungolfed

black_magic  =: +/\-/+/\
doubled_bm   =: 2 * black_magic
flatten      =: ,/
sum          =: +/
is_member_of =: e.
f =: sum is_member_of monadic flatten doubled_bm

Previous 23-byte version:

[:+/[:+/+/=+:@-/~@(+/\)

Usage

>> f =: [:+/[:+/+/=+:@-/~@(+/\)
>> f 6 6 12 12 12 11 1 12
<< 4
>> f 10 20 10 1
<< 0

Ungolfed

black_magic =: -/~@(+/\)
double      =: +:
equals      =: =
sum         =: +/
monadic     =: [:
of          =: @
f =: monadic sum monadic sum (sum equals double of black_magic)

Explanation

The sum of all substrings is calculated by the black_magic. The +/\ calculate the partial sums.

For example, a b c d becomes a a+b a+b+c a+b+c+d.

The -/~ then constructs a subtraction table based on the input, so x y z becomes:

x-x x-y x-z
y-x y-y y-z
z-x z-y z-z

When applied to a a+b a+b+c a+b+c+d, the result would be:

    0  -b -b-c -b-c-d
    b   0   -c   -c-d
  b+c   c    0     -d
b+c+d c+d    d      0

This calculated the sums of all the substrings which does not contain a.

This guarantees to be enough, since if one bisection contains a, the other bisection will not contain a and also will not wrap around.


Check whether letters of word are in alphabetical order

CJam, 8 bytes

lel_$_&=

Here is a test harness for all examples in the challenge. This returns 0 or 1 (which are falsy and truthy, respectively, in CJam).

And here is a script to filter the word list in the question (takes a few seconds to run). You'll have to copy the word list into the input field manually, because it's too long for a permalink.

Explanation

l        "Read input.";
 el      "Convert to lower case.";
   _$    "Get a copy and sort it.";
     _&  "Remove duplicates (by computing the set intersection with itself).";
       = "Check for equality with original (lower case) word.";


Find out if this a valid Stack Cats program, in Stack Cats style!

JavaScript (ES6), 487 467 378 298 292 280 266 264 bytes

Saved 14 bytes thanks to @Bubbler

I=>(V=v=>!I[v]||((T=o=>[[]][+!!A[o]]||[(I[v]!=A[o]||A)[o^o<88/8]]+T(++o))(8-8)==I.pop())*V(++v))(V|(A='(){}[]<>\\/ !*+-:=ITX^_|'))//\\(('|_^XTI=:-+*! \//<>[]{}()'=A)|V)((v++)V*(()qoq.I==(8-8)((o++)T+[[8\88>o^o](A||[o]A=![v]I)]||[[o]A!!+][[]]<=o=T))||[v]I!<=v=V)<=I

Defines an anonymous function that takes an array of chars and returns the desired output. Output is truthy/falsy; usually 1/0, but the empty string gives true.

How?

The most obvious trick is to use //\\ as a center point to comment out the mirrored version of the code. After that, it becomes a game of figuring out the shortest way to solve the problem using only the charset given.

The first issue we run into is the lack of keywords and built-ins. We miraculously still have .pop(), but everything else will have to be done via the allowed operators (which includes a[b] and f(c)), with recursion to emulate loops.

The second issue is the lack of logical operators. Neither & and ? are allowed, which means the only decision-making operator we can use is ||. Therefore, we have to carefully structure our logic to account for this.

The first thing I did was to define a function T that mirrors an individual character. The basic idea is to loop through each character in a string of mirror-able chars, testing each for equality with the given char. If it is equal, we return its mirror—the char at index^1 for (){}[]<>\/, or the char itself for the rest.

The first problem I ran into here was getting either the mirrored char or a falsy value on each iteration. The solution I eventually came up with was (x!=A[o]||A)[o^o<88/8], where x is the input character, A is the mirroring alphabet, and o is the current index. If x is not the same as A[o], this gives true, and the index expression evaluates to undefined; otherwise, the ||A is activated, and we end up getting A[o^(o<11)].

The second problem is how to terminate the recursion. I found that the best way to do this is to simply concatenate the results of every iteration, returning the empty string when the end of A is reached. This presents us with two further problems: converting the undefineds to empty strings, and returning the empty string || something. These can be solved with array abuse: [a]+"" gives the string representation of a, or the empty string if a is undefined. As a bonus, [] is truthy but stringifies to the empty string, so we can conveniently use this as a "truthy empty string".

Now we can use the T function to mirror any single character. We do this recursively, comparing the mirror of I[v++] to I.pop() until the end of the array of chars is reached. We can't use && or & to check if all of the comparisons are truthy, but so use * instead. Multiplying all of these results together gives 1 if every character is the mirror of the one opposite, or 0 if any comparison fails.

And that is basically how this answer works. I probably didn't explain it very clearly, so please ask any questions you may have and point out any mistakes I have made.


APL (Dyalog Unicode), 59 57 bytesSBCS

{v⍳+\v[⍺],↓⍉↑(|⍴¨×)⊃⍵⍺-.⊃⊂v←9 11∘○¨+\0,0j1*{⍵/⍨⌈⍵÷2}⍳⍺⌈⍵}

Try it online!

-2 bytes thanks to @ngn.

Anonymous function that accepts two endpoints as left and right arguments.

Ungolfed & how it works

The queen moves diagonally first, so it is sufficient to pre-compute the coordinates of each number up to max(start,end).

The coordinate-generating algorithm is inspired from several answers on the related challenge, but is slightly different from any of the existing answers:

Given the necessary bound of 10
Generate the 1-based range r=1 2 3 4 5 6 7 8 9 10
Take the ceiling of half of each number n=1 1 2 2 3 3 4 4 5 5
Replicate each item of r by n. 1 2 3 3 4 4 5 5 5 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 9 10 10 10 10 10
Take the cumulative sum of power of imaginary unit, with starting point of 0. (this part is common to various Python solutions to the linked challenge)

Then, once the vector of coordinates v is ready, we can easily convert between the spiral index and coordinates using v[i] and v⍳coord (finding the first index of coord in v).

⍝ Define a function; ⍺=start, ⍵=end
f←{
  ⍝ Construct a vector of spiral coordinates v
  v←9 11∘○¨+\0,0j1*{⍵/⍨⌈⍵÷2}⍳⍺⌈⍵
                             ⍺⌈⍵  ⍝ max of start, end
                            ⍳     ⍝ range of 1 to that number
                   {⍵/⍨⌈⍵÷2}  ⍝ for each number n of above, copy itself ceil(n/2) times
               0j1*  ⍝ raise imaginary unit to the power of above
           +\0,      ⍝ prepend 0 and cumulative sum
                     ⍝ (gives vector of coordinates as complex numbers)
    9 11∘○¨  ⍝ convert each complex number into (real, imag) pair
  v←         ⍝ assign it to v

  ⍝ Extract start and end coordinates
  a w←(⍺⊃v)(⍵⊃v)

  ⍝ Compute the path the Queen will take
  v⍳+\(⊂a),↓⍉↑(|⍴¨×)w-a
                    w-a  ⍝ coordinate difference (end-start)
              (|⍴¨×)     ⍝ generate abs(x) copies of signum(x) for both x- and y-coords
                         ⍝ e.g. 4 -> (1 1 1 1), ¯3 -> (¯1 ¯1 ¯1)
           ↓⍉↑  ⍝ promote to matrix (with 0 padding), transpose and split again
                ⍝ (gives list of steps the Queen will take)
    +\(⊂a),     ⍝ prepend the starting point and cumulative sum
                ⍝ (gives the path as coordinates)
  v⍳  ⍝ index into the spiral vector (gives the spiral numbers at those coordinates)
}


Python 2, 41 bytes
lambda s:s==s-{a+b for a in s for b in s}

s should be a Python set.
Fun fact: sum-free is an anagram of my name.