text:
N-gram histogram
Given a text and a number N, output, in a human readable format, the set of the character N-grams with their respective percentages.
The smallprint

The text can be read from a file, stdin, passed as string parameter to a function or any other common way i forgot to mention
The number N can be hardcoded, but only if it needs to be changed in one single place to change the functionality, the number counts as one byte regardless of the number of digits (T=input();N=100;f(T,N) would count as 20 bytes, not 22)
No case sensitivity and all non-letter characters are treated the same. Inputs Abra Cadabra! and aBRa#caDAbrA5 should produce the same output. The character for non-letter can be any printable non-letter, not necessarily contained in the input
You may assume N < text.length
Output can be written to a file or displayed on screen. If you use a function you can return the result instead of printing as long as it is human readable (a JSON object or array like in the examples below is fine, a custom class or a sparse matrix with 27^N entries - not so much)

Examples with text = 'Abra Kadabra!'
N = 1
a 0.385
b 0.154
r 0.154
_ 0.154
k 0.076923
d 0.076923

N = 12
abra_kababra 0.5
bra_kadabra_ 0.5

N = 2 (dont worry about number format or rounding as long as it sums up to 0.99 < x < 1.01)
ab 0.1666666
br 0.16666
ra 0.1666
a. 0.166667
.k 0.0833333
ka 0.0833333
ad 8.33333e-2
da 0.0833333

a tree structure is fine too
{'a':{'b':0.166, '.':0.166, 'd': 0.0833},
 'b':{'r':0.166},
 'r':{'a':0.166},
 '.':{'k':0.0833},
 'k':{'a':0.0833},
 'd':{'a':0.0833}}

or a list of lists
[['A', 'B', 0.166], ['B', 'R', 0.166], ...]

I'd suggest explaining exactly what N-grams are instead of just linking.

If we hardcode N how do we count the bytes? Without the value of N? Or for a single-digit N?

Another question: can the character representing non-letters be anything? Including a space?

And more interestingly, can it be a letter?

@FUZxxl If your language can only print letters, then you can use an uppercase letter while all "real" letters are lowercase or the other way round

I don't think abra_kababra is a 12-gram of 'Abra Kadabra!' (kababra instead of kadabra)

Pyth, 40 35 27 character
KCm>m?k}kGNrz0dQ{m,bc/KblKK

Try it online: Pyth Compiler/Executor
For the input Abra Kadabra!, 2 it prints something like (the order is each time different, because of the behavior of set):
{(('d', 'a'), 0.08333333333333333), (('r', 'a'), 0.16666666666666666), (('b', 'r'), 0.16666666666666666), (('"', 'k'), 0.08333333333333333), (('a', 'b'), 0.16666666666666666), (('k', 'a'), 0.08333333333333333), (('a', '"'), 0.16666666666666666), (('a', 'd'), 0.08333333333333333)}

I use " as special character.
Explanation
m?k}kGNrz0         implicit: z = raw_input() # input_string
m      rz0         map each character k of z.lower() to:
  k   N                k                     '"'
 ? }kG                    if k in "a-z" else
We call the result X.

KCm>XdQ             implicit: Q = input() # number N
  m   Q             map each d in [0, 1, 2, ..., Q - 1] to:
   >Xd                  X[d:] # all characters of X starting at position d
 C                  zip - creates all N-grams
K                   store the results in variable K

{m,bc/KblKK
 m        K         map each b in K to:
  ,b                    the pair (b,                    )
     /Kb                             K.count(b)
    c   lK                                      / len(K)
{             set - remove duplicates

Printing in a 'human readable format': 35 character
KCm>m?k}kG\_rz0dQjbo_eN{m,sbc/KblKK

Try it online: Pyth Compiler/Executor
For the input: Abra Kadabra!, 2 it prints:
('a_', 0.16666666666666666)
('ab', 0.16666666666666666)
('ra', 0.16666666666666666)
('br', 0.16666666666666666)
('ka', 0.08333333333333333)
('da', 0.08333333333333333)
('_k', 0.08333333333333333)
('ad', 0.08333333333333333)

Explanation (differences)
\_ instead of N in m?k}kGNrz0
Uses '_' instead of '"'

s in {m,sbc/KblKK
This combines the individual characters

jbo_eN
  o                 order the elements N by:
   _eN                  the value -N[-1] (by the negative percentage)
jb                  join by newlines - prints each pair in row

all three versions are valid, and it does not need to be sorted

@DenDenDo O.k. thanks. I shortened it a lot.

J, 57 55 48 characters.
As a dyadic verb, N goes left, text goes right.
[:((a.{~97+~.);"#:#/.~%#)((u:97+i.26)i.tolower)\

Example
2 ([:((a.{~97+~.);"#:#/.~%#)((u:97+i.26)i.tolower)\) 'Abra Kadabra!'

yields:
┌──┬─────────┐
│ab│0.166667 │
├──┼─────────┤
│br│0.166667 │
├──┼─────────┤
│ra│0.166667 │
├──┼─────────┤
│a{│0.166667 │
├──┼─────────┤
│{k│0.0833333│
├──┼─────────┤
│ka│0.0833333│
├──┼─────────┤
│ad│0.0833333│
├──┼─────────┤
│da│0.0833333│
└──┴─────────┘

Thanks to randomra for a nine character improvement.
Explanation
This is the solution with spaces inserted in the appropriate places:
[: ((a. {~ 97 + ~.) ;"#: #/.~ % #) ((u: 97 + i. 26) i. tolower)\

First, observe that "#: is shorthand for "1 0 and that u: 97 + i. 26 is just 'abcdefghijklmnopqrstuvwxyz', so without these two tricks we get
[: ((a. {~ 97 + ~.) ;"1 0 #/.~ % #) ('abcdefghijklmnopqrstuvwxyz' i. tolower)\

And this is how this works. In the following explanation, x and y are the left and right arguments, u and v are verbs, and m and n are nouns.

[: u v—a capped fork, x ([: u v) y is equal to u (x v y). This is used instead of u@v because v is an adverbial phrase and parentheses were needed. In this code, u is (a. {~ 97 + ~.) ;"#: #/.~ % # and v is ((u: 97 + i. 26) i. tolower)\.
x u\ y—apply u to each infix of y of length x. For example, 3 ]\ 'abcdefg' where ] is the identity function yields
abc
bcd
cde
def
efg

n u v—a fork with a noun as the left argument. (n u v) y is equal to n u (v y). This is used multiple times in the code.
tolower y–convert all upper case letters in y to lower case.
x i. y–find the index of y, which is in this case for each item in y the lowest index into x at which that item can be found or the number of items in x if such an item does not exist. In our use case, x is the lower case alphabet. ('abcdefghijklmnopqrstuvwxyz' i. tolower) y translated each (upper case or lower case) letter in y into a number from 0 to 25. Non-letters are translated into 26. Notice that the character immediately following z in ASCII is {.
x u/. y–applies u to y keyed by x. That is, u is applied to groups of items of y with the same key in x. Noticeably, if x and y are equal, y u/. y applies u to groups of equal items of y and can be used to generate frequency statistics.
# y–the tally of y, that is, the number of items in y.
u~–the reflexive of u, that is, u~ y is equal to y u y.
u v w–a fork, (u v w) y is equal to (u y) v (w y). This, too, is used multiple times in the code.
x % y–x divided by y.
#/.~ % #–the frequency count we want sans what we count.
~. y–the nub of y, that is, each distinct item of y. For instance, ~. 1 2 3 3 4 6 6 6 yields 1 2 3 4 6.
(a. {~ 97 + ~.) y–the nub of y converted from indices into the alphabet back to letters; 26 is converted into { implicitly.
x ; y–x linked to y, that is, both put into boxes and the boxes concatenated. For instance, 'abc' ; 1 2 3 4 yields
┌───┬───────┐
│abc│1 2 3 4│
└───┴───────┘

This is needed because in J, arrays are homogeneous; all items in an array need to have same type. A box hides what is in it and turns heterogeneous arrays into arrays of boxes.
u"n–u ranked n. Rank is a slightly complex concept so I won't explain it here, but in this case, x ;"1 0 y (for which x ;"#: y is just a shorthand) applies ; to each string in x and the corresponding number in y as opposed to the entire of x and the entire of y. This is the difference between
┌──┬───────────────────────────────────────────────────────────────────────────┐
│ab│0.166667 0.166667 0.166667 0.166667 0.0833333 0.0833333 0.0833333 0.0833333│
│br│                                                                           │
│ra│                                                                           │
│a{│                                                                           │
│{k│                                                                           │
│ka│                                                                           │
│ad│                                                                           │
│da│                                                                           │
└──┴───────────────────────────────────────────────────────────────────────────┘

and the correct output shown above.

[]\(u:97+i.26)i.tolower@] => ((u:97+i.26)i.tolower)\  for 2 bytes.

Getting rid of the adverse (::) and boxing/unboxing (&.>) saves 7 more bytes! [:((a.{~97+~.);"#:#/.~%#)((u:97+i.26)i.tolower)\

This is really cool.

CJam, 53 bytes
q~el_'{,97>-'_er_,,\f>1$(W*<f<:L__&_@f{\a/,(}L,df/]z`

Without having a look at the other CJam answer, here is a shorter one.
Input goes like:
2 "Abra Kadabra!"

Output is like:

[["ab" 0.16666666666666666] ["br" 0.16666666666666666] ["ra" 0.16666666666666666] ["a_" 0.16666666666666666] ["_k" 0.08333333333333333] ["ka" 0.08333333333333333] ["ad" 0.08333333333333333] ["da" 0.08333333333333333]]

Explanation soon.
Try it online here

BQN, 56 bytes
"A[a{"⊸⍋⊸({2|?+16×¬;'_'}¨)⊸{u⋈˘(≠s)÷˜+´˘⍷⟜˘u←⍷s←↕}

Anonymous function that takes a string on the left and the number N on the right. It returns a 2-D array, in which each row contains a length-N substring and a 0-D array containing the substring's frequency. Try it at BQN online!
Explanation
Wow this is ugly--and not just because of BQN's total lack of character/string primitives.
The first half normalizes the string argument by converting lowercase letters to uppercase and non-letters to underscores:
"A[a{"⊸⍋⊸({2|?+16×¬;'_'}¨)
"A[a{"⊸⍋                        Classify the characters: 0 if < 'A', 1 if >= A but
                                 < '[', and so forth (meaning, in particular, 1 for
                                 uppercase letters and 3 for lowercase letters)
        ⊸(                   )  With that as the left argument and the original
                                string as the right argument,
          {                }¨   call this function on each number-character pair:
           2|?                  If the number is odd (1 or 3):
                    ¬            1 minus the number
                 16×              times 16
               +                 plus the character
                       ;'_'      Else, underscore

Now the actual meat of the function:
⊸{u⋈˘(≠s)÷˜+´˘⍷⟜˘u←⍷s←↕}
⊸{                          }  Pass the left argument through the above function
                               before calling this function:
                        ↕    Get all length-(right arg) substrings of (left arg)
                      s←       Save that 2D array of characters as s
                     ⍷         Deduplicate
                   u←          Save that 2D array of characters as u
              ⍷⟜˘            For each row of u, find all occurrences of that
                               substring in the left arg; mark the beginning of
                               an occurrence with a 1, all other positions with a 0
           +´˘                 Sum each row, giving a list of occurrence counts
         ÷˜                    Divide each by
     (≠s)                      the length of s
   ⋈˘                          Pair each with
  u                            the corresponding unique substring

Haskell, 164 bytes
import Data.Char
import Data.List
l=genericLength
c c|isAlpha c=toLower c|1<2='_'
n%i=[(s!!0,l s/l p)|s<-group p]where p=sort[take n s|s<-tails$map c i,length s>=n]

Usage: 12 % "Abra Kadabra!" -> [("abra_kadabra",0.5),("bra_kadabra_",0.5)]
This is longer than I thought. Does anyone know a shorter version of a "split list into sublists of length n" function (my attempt: [take n s|s<-tails$     i,length s>=n])?
How it works:

map all characters in the input list to lowercase or '_' if not a letter
split into a list of substrings of length n
sort, name the list p
group equal elements (e.g. for n=2 -> [["_k"],["a_","a_"],["ab","ab"],["ad"],["br","br"],["da"],["ka"],["ra","ra"]]
for each sublist take one of it's elements and pair it with the length divided by the length of p

Mathematica, 124 119 bytes
Could probably golf further.
#[[1]]->#[[2]]&/@#/Length@#&@Tally@Partition[Characters@StringReplace[ToLowerCase@#,Except@LetterCharacter->"_"],#2,1]&

The doesn't ask for percent so you don't need the 100. It also doesn't even specify that the results should be floating point ("dont worry about number format or rounding as long as it sums up to 0.99 < x < 1.01") so I think you can actually report the results as rationals and skip the N@. Also, I think what you're trying to do with GroupBy and Length is what Tally is for.

@MartinBüttner Thanks! The spec wasn't exactly clear... EDIT: Dangit my Mathematica trial expired... guess I'll have to try to read my own mess D:

107 bytes and I'm sure it can be golfed even more

Clip 10, 53
\[tm[b{(b/)b)mlxt`}q[bm[juj+jtb}R)mlbt]a[!cA}m.U`xS]n

Example:
C:\Users\~~~~~\Documents>java -jar Clip10.jar ngram.clip
Abra Kadabra!
2
{{"AB", 0.166666666666666}, {"A ", 0.166666666666666}, {"RA", 0.166666666666666}, {"BR", 0.166666666666666}, {"DA", 0.083333333333333}, {" K", 0.083333333333333}, {"KA", 0.083333333333333}, {"AD", 0.083333333333333}}

Explanation
 [t                                               ]n .- Assign the second input to t -.
                                            m.U`x    .- Convert the input to upper case -.
                                      a[!cA}     S   .- Replace all non-alphabetic characters with spaces -.
                   [b                ]               .- Assign the modified string to b -.
                     m[juj+jtb}R)mlbt                .- All substrings of length t -.
                  q                                  .- Frequencies (in the form {"A", 1} )-.
   m[b{(b/)bmlxt`}                                   .- Use proportional frequencies
\                                                    .- Make the array pretty -.

CJam, 61 59 bytes
I think the input transformation is quite nifty, but the actual tallying needs work.
l~qeu'~),_el&'_er_,,2$f{2$@><\}\W*<:L__&\f{1$a/,(L,d/][};]`

Reads N on the first line and then treats the remainder of STDIN as the text:
2
Abra Kadabra!

The result is printed as a nested CJam-style array with upper case letters and _ for non-letters:
[["AB" 0.16666666666666666] ["BR" 0.16666666666666666] ["RA" 0.16666666666666666] ["A_" 0.16666666666666666] ["_K" 0.08333333333333333] ["KA" 0.08333333333333333] ["AD" 0.08333333333333333] ["DA" 0.08333333333333333]]

Test it here.

APL (Dyalog Classic) with MiServer's Strings.lc, 30 bytes
Prompts for text, then for N. Prints N-grams and frequencies.
(∪,⊢∘≢⎕U2338÷≢)⎕,/'\W'⎕R'_'lc⍞

Try it online!
Only 25 characters (but 44 bytes) in Dyalog Unicode:
(∪,⊢∘≢⌸÷≢)⎕,/'\W'⎕R'_'lc⍞

… because ⌸ ⇔ ⎕U2338, but is not included in the Classic character set.
Explanation
⍞ get text input
lc lowercase
'\W'⎕R'_' PCRE Replace non-word characters with underscores
,/ concatenate the characters in each possible position of a sliding window of size
⎕ number-input
(…) apply the following anonymous tacit function on that (the N-grams):
 ∪ the unique (N-grams)
 , followed by
 ⊢∘≢⌸ the number occurrences for each unique element (of the N-grams)
 ÷ divided by
 ≢ the tally (of N-grams)

Ruby, 86 bytes
->s,n{s.upcase.gsub(/[^A-Z]/,?_).chars.each_cons(n).tally.map{[_1,_2/(s.size-n+1.0)]}}

Attempt This Online!

Python, 92 bytes
lambda s,k:(b:=1+len(s)-k)//b*(a:=[s[i:i+k]for i in range(b)])and{t:a.count(t)/b for t in a}

Attempt This Online!

05AB1E, 24 bytes
„üÿUáмS¡'_ýlDX.VÙDŠ¢DO/ø

Inputs in the order N, text. Outputs as a list of [string, decimal] pairs. A trailing » (+1 byte) could be added to pretty-print them to STDOUT.
Try it online or verify all test cases.
Explanation:
„üÿ       # Push string "üÿ", where `ÿ` is automatically replaced with the first
          # (implicit) input-integer
   U      # Pop and store this string in variable `X`
á         # Only keep all letters of the second (implicit) input-string
 м        # Remove all those letters from the second (implicit) input-string
  S       # Convert the remaining string of characters to a list
   ¡      # Split the second (implicit) input-string on those characters
    '_ý  '# Join it with "_" delimiter
       l  # Convert this string to lowercase
D         # Duplicate the string
 X        # Push string `X` we created earlier
  .V      # Evaluate and execute it as 05AB1E code,
          # creating overlapping substrings of size `N`
    Ù     # Uniquify this list
D         # Duplicate the unique substrings
 Š        # Triple-swap from a,b,b to b,a,b
  ¢       # Pop the string and list, and count how many times each string occurs
   D      # Duplicate the list of counts
    O     # Sum it together
     /    # Divide the individual counts by the sum
      ø   # And pair it with the substrings we've duplicated
»         # (Optional) join each pair by spaces, and then each string by newlines
          # (after which the result is output implicitly)


text:
Print the Longest Sentence
I've searched around, and cannot find a challenge too similar to this one--however, it would not surprise me if this is not the first of its kind. My apologies if I've overlooked something.
The Challenge
This challenge is intended to amuse those of every skill level and users of every language. Your task, in itself, is very simple. Write a program (or function) that prints the longest sentence in 140 bytes.
The Input
Your code should not receive input from anywhere. You may not take any arguments, any values from STDIN, or any word lists. Additionally, built-ins or libraries that generate word lists or manipulate word lists are also banned. Output should be generated by the program itself.
The Output
Your output should abide by the following rules:

For simplicity, the output must be in English, and must not contain any characters other than a-z A-Z .,:;()!?-. (Tabs and newlines should not be present in your sentence, and exactly one space should exist between words)
Your output may include trailing or leading whitespace, but these do not count toward your final score.
Your output must be a singular, valid, punctuated, grammatically correct sentence.
As long as the sentence is syntactically valid, meaning is unimportant. Please refrain from vulgarity.
Your output should only include words recognized by dictionary.com.
Your output must not repeat any singular word more than 3 times. Conjunctions and articles are an exception to this rule and may be repeated any number of times.
Your output must be finite.
Any output method is acceptable--whether it be to STDOUT, a file, a returned string, whatever.

The Rules

Your score is the length, in bytes, of the sentence your program generates.
Program source code should not exceed 140 bytes. Insert witty comment about how my only method of communication is Twitter here.
Your program should terminate within a minute on any modern machine.
Sufficiently clever code or valid output larger than the code itself may be eligible for a bounty!
Standard loopholes apply.

Questions, comments, concerns? Let me know!

Do I have to print just 1 sentence ?

The problem is that sentences like 1 and 2 and 3 and 4 and 5 and ... and 999 are all numbers. would be valid and could be infinitely long.

@Calvin'sHobbies Ahhhhh... Dang it. Outlawing numbers...

I know it's borderline but something like I want to go but but but ... but I'm too nervous! may be considered grammatical.

@Calvin'sHobbies I believe, with some certainty, that that is not grammatical. A writer could use such phrases in the context of dialog to convey an emotion, but I don't think that it is grammatical. I will likely delete this question soon anyway.

Are we allowed to read web content?

@mbomb007 "Your code should not receive input from anywhere."

How about: That text contains none of the following word sequences: "the the", "the the the", "the the the the" ... up to arbitrary many but finite thes?

@nimi " is not one of a-z A-Z .,:;()!?-, and thus cannot be used in output.

You should post a new challenge in the sandbox on the meta site first. We wouldn't have to ask so many questions here, that way.

@mbomb007 Note that I have made exactly one edit since I've asked this question, and it was to remove numbers (which, admittedly, was an oversight). Every single question asked has been easily answered by quoting the spec above. What am I to do if people don't read it?

What is your reference for checking whether something is a "grammatically correct sentence"? When you say that no word may be repeated more than thrice, does that mean consecutively (to eliminate things like Fred, where Jim had had "had", had had "had had"; ...) or does that count all occurrences in the sentence?

Note that the question has down-votes, so you still should use the sandbox.

Buffalo buffalo buffalo buffalo buffalo buffalo buffalo buffalo would have been a good contender if not for the repeat rule.

CJam, 140 bytes → 2301 characters
Try it online.
Code
"I'm ""jdÇÉÛ7ª%ùÞtÛù    ±çV(exç3å$Z±³RÌÊ
D»l°ØEøv¸x¡·ðQà\+ÜµjR¡2>ãq§Sã¾iPLÛ"252b27b'`f+'`/2/{~"ing, "+f+~}/"and "\7<]]3*" while "*'.

Output
I'm bagging, fagging, gagging, lagging, nagging, ragging, sagging, tagging, wagging, bailing, failing, hailing, jailing, mailing, nailing, railing, sailing, tailing, wailing, capping, lapping, mapping, napping, rapping, sapping, tapping, yapping, zapping, bearing, fearing, gearing, hearing, nearing, rearing, searing, tearing, wearing, bending, fending, lending, mending, pending, rending, sending, tending, vending, wending, betting, getting, jetting, letting, netting, petting, setting, vetting, wetting, dipping, hipping, kipping, nipping, pipping, ripping, sipping, tipping, yipping, zipping, bobbing, dobbing, fobbing, gobbing, jobbing, lobbing, mobbing, robbing, sobbing, bulling, culling, dulling, fulling, gulling, hulling, lulling, mulling, and pulling while I'm bagging, fagging, gagging, lagging, nagging, ragging, sagging, tagging, wagging, bailing, failing, hailing, jailing, mailing, nailing, railing, sailing, tailing, wailing, capping, lapping, mapping, napping, rapping, sapping, tapping, yapping, zapping, bearing, fearing, gearing, hearing, nearing, rearing, searing, tearing, wearing, bending, fending, lending, mending, pending, rending, sending, tending, vending, wending, betting, getting, jetting, letting, netting, petting, setting, vetting, wetting, dipping, hipping, kipping, nipping, pipping, ripping, sipping, tipping, yipping, zipping, bobbing, dobbing, fobbing, gobbing, jobbing, lobbing, mobbing, robbing, sobbing, bulling, culling, dulling, fulling, gulling, hulling, lulling, mulling, and pulling while I'm bagging, fagging, gagging, lagging, nagging, ragging, sagging, tagging, wagging, bailing, failing, hailing, jailing, mailing, nailing, railing, sailing, tailing, wailing, capping, lapping, mapping, napping, rapping, sapping, tapping, yapping, zapping, bearing, fearing, gearing, hearing, nearing, rearing, searing, tearing, wearing, bending, fending, lending, mending, pending, rending, sending, tending, vending, wending, betting, getting, jetting, letting, netting, petting, setting, vetting, wetting, dipping, hipping, kipping, nipping, pipping, ripping, sipping, tipping, yipping, zipping, bobbing, dobbing, fobbing, gobbing, jobbing, lobbing, mobbing, robbing, sobbing, bulling, culling, dulling, fulling, gulling, hulling, lulling, mulling, and pulling.

Explanation
As I'm sure you can tell, my main tactic was to generate a large number of very similar words. My plan was to find groups of words that all had the same spelling after the first letter with a large number of possible first letters, as these could be heavily compressed. To find the best candidates, I grabbed the whole dictionary, grouped words by their spelling after the first letter, and sorted these groups in descending order by the sum of the lengths of all words in the group.
Upon doing this, I discovered that many of the top entries were the present tense of verbs, in the form "___ing." This was great, because it meant that not only could I abstract the "ing" out of every group, but also every word could simply be thrown in a big list in the sentence because they were all of a form of speech that allowed it. The big mess of characters in the middle of the code encodes as much of this data as I could fit, using multiple compression methods.
As for the sentence structure generated, it's fairly simple. It's certainly a bit redundant, repeating the main phrase 3 times for maximal length, but I believe it's grammatically correct. With the innards of the verb lists cut out, the sentence looks like this:
I'm bagging, ... , and pulling while I'm bagging, ... and pulling while I'm bagging, ... and pulling.

Python - Code: 140, Output: 476
NOTE: Currently needs to be modified. Any help on replacing a couple words within the byte limit?
I made use of the built-in documentation for the integer type, and so far I am confident that this is one of the most unique, if not the most creative, approach(es).
Most of the code was overhead used to remove newlines and combine the documentation into a single sentence. Annoyingly, I also had to replace a couple of occurrences of the word "string".
import re;print'Cattle, c'+re.sub('a string','a key',re.sub('  ',', but ',re.sub(r'\. ',', and',re.sub(r'\n',' ',int.__doc__.lower()))[28:]))

Output:
Cattle, convert a key or number to an integer, if possible, and a floating point argument will be truncated towards zero (this does not include a key representation of a floating point number!), but when converting a key, use the optional base, and it is an error to supply a base when converting a non-string, and if base is zero, the proper base is guessed based on the string content, and if the argument is outside the integer range a long object will be returned instead.

Run it here: http://repl.it/fsM

This is really cool. However, the words "base" and "is" both appear four times, so it needs some tweaking.

Ah, my bad. I don't know if I can fix that with fewer than 140 bytes...

Would this be considered against Output should be generated by the program itself.? Just curious.

@tfizger I don't think there's anything wrong since it's built-in, and I certainly had to modify it to generate this single sentence.

@Runer112, The question is unclear to me whether is means it cannot "contain" the same word that many times, or if it cannot "repeat" it, which is what it says. My program uses it in a different context each time, with a different verb, so idk.

@mbomb007 I interpreted the question such that using the same word in a different context still counts as repeating the word, but this is definitely a question for the question author rather than me.

@Runer112 The question is already there in the comments. It hasn't been answered yet.

JAVA - Code: 122, length: 153 words, 464 bytes
Java, yep, java. Ok, so I had to make it a function instead of a program. The boilerplate was just too much.
Golfed code:
void p(){int i=0;char c=1;while(i++<3){for(c=65;c<90;System.out.print(c+++" and "));}System.out.print(c+" are letters.");}

Readable version:
void p(){
    int i=0;
    char c=1;
    while(i++<3){
        for(c=65;c<90;System.out.print(c+++" and "));
    }
    System.out.print(c+" are letters.");
}

Output:
A and B and C and D and E and F and G and H and I and J and K and L and M and N and O and P and Q and R and S and T and U and V and W and X and Y and A and B and C and D and E and F and G and H and I and J and K and L and M and N and O and P and Q and R and S and T and U and V and W and X and Y and A and B and C and D and E and F and G and H and I and J and K and L and M and N and O and P and Q and R and S and T and U and V and W and X and Y and Z are letters.
Each letter is defined under dictionary.com as a valid word in response to its ordinal position in the alphabet. Each word is used at most three times.

Whoops, grabbed the wrong code for the One issue. Also, I must have missed that requirement. Back to the drawing board!

Haskell, code: around 104 bytes, output: as many as your computer can produce within the 1min limit
f = let n=4 in putStr $ "Corollary: "++ (replicate n '(') ++ "a-b" ++ (replicate n ')') ++ " equals c."

Output example:
Corollary: ((((a-b)))) equals c.

Of course you can change n to any number you want (including expressions like 100^100 to stay within the 140 byte limit) to increase the number of parentheses.

Excel (because ... :) ): Code: 135 Output: 211
[edit] corrected beginning of sentence, the previous one really wasn't correct, this version is slightly better. Still a bit of a grammar "hack", but still valid by the rules in any case :) [/edit]
=CONCATENATE("Where ",REPT("someone thinks that ",3),rept("everyone understands when ",3),rept("they believe what ",3),"nobody cares.")

Output:
Where someone thinks that someone thinks that someone thinks that everyone understands when everyone understands when everyone understands when they believe what they believe what they believe what nobody cares.

source: Stack Exchange

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

sort: votes


text:
Simulate a Game of Quagmire
Background
Many moons ago, in a galaxy much like our own, a young BrainSteel attempted to invent a board game. He believed that he, too, could find an amazingly simple set of rules that would generate wonderfully strategic gameplay. He drew up the first set of rules--it looked promising. He played with his thoughts, and noticed a minor inconsistency here, or a slight balance issue there. One by one, the rules started piling up, until they were at best arbitrary. Try as he might, the beautiful simplicity of Checkers or Go failed to shine through. His final creation, one bad enough he would only refer to it when speaking in the 3rd person, was given the temporary name "Quagmire." While perhaps not a brilliant board game, it ought to be a fun code golf!
The Rules of Quagmire
The game is played on an 8x8 board, and each player has 10 identical pieces. If player one has O pieces, and player 2 has X pieces, here is a portrayal of the game at the start (where . indicates a blank space):
 a b c d e f g h
+-+-+-+-+-+-+-+-+
|.|.|.|.|X|X|X|X| 8
+-+-+-+-+-+-+-+-+
|.|.|.|.|.|X|X|X| 7
+-+-+-+-+-+-+-+-+
|.|.|.|.|.|.|X|X| 6
+-+-+-+-+-+-+-+-+
|.|.|.|.|.|.|.|X| 5
+-+-+-+-+-+-+-+-+
|O|.|.|.|.|.|.|.| 4
+-+-+-+-+-+-+-+-+
|O|O|.|.|.|.|.|.| 3
+-+-+-+-+-+-+-+-+
|O|O|O|.|.|.|.|.| 2
+-+-+-+-+-+-+-+-+
|O|O|O|O|.|.|.|.| 1
+-+-+-+-+-+-+-+-+

Note that every space on the grid can be named with a letter and number, e.g. there is an O character on c2.
Players take turns in an alternating fashion.
On a player's turn, they may move in two ways:

The player may move any piece in a straight line vertically, horizontally, or diagonally at most until they meet either another wall or piece.
e.g. |X|.|.|O|.| => |.|.|X|O|.| for one move of length 2 horizontally. Note that the X piece cannot move any farther right, because there is a piece in the way.

The player may use a piece to jump over a single, adjacent, and friendly piece. Jumps, like ordinary moves, may be horizontal, vertical, or diagonal. Under normal circumstances an enemy piece may not be jumped. e.g. |X|X|.| => |.|X|X|

If a piece cannot move to any of its surrounding spaces, and at least one of those adjacent spaces is occupied by an enemy piece, that piece is said to be in a state of Quagmire. If a player ends his turn with a piece in Quagmire, they lose the game.
Now for the more arbitrary rules:

The bottom left player goes first.

Each player must make exactly one move per turn. (No pass!)

A piece may not be moved twice in a row, ever. e.g. if, on the first turn, player one moves the piece on c2, he may not move the same piece on his following turn.

If the player to move has one or more pieces in Quagmire which may move, they must move one of those pieces.

A piece may jump an enemy piece in the same way that it jumps a friendly piece if and only if that enemy piece is part of a closed loop (which may or may not start and end at a wall) of pieces of one color, and that loop is impenetrable by normal moves. If a piece jumps in this way, it must jump from inside the loop to the outside, or vice versa. Since this rule is weird, here is an example board:

     a b c d e f g h
    +-+-+-+-+-+-+-+-+
    |.|.|.|O|X|.|.|X| 8
    +-+-+-+-+-+-+-+-+
    |.|.|.|.|X|.|.|X| 7
    +-+-+-+-+-+-+-+-+
    |.|.|.|.|X|.|.|.| 6
    +-+-+-+-+-+-+-+-+
    |X|.|.|.|.|X|X|X| 5
    +-+-+-+-+-+-+-+-+
    |O|O|O|O|.|.|.|.| 4
    +-+-+-+-+-+-+-+-+
    |.|.|.|O|X|.|.|.| 3
    +-+-+-+-+-+-+-+-+
    |.|.|.|O|.|.|O|.| 2
    +-+-+-+-+-+-+-+-+
    |O|O|O|O|.|.|.|.| 1
    +-+-+-+-+-+-+-+-+

In this position, the X on a5 may legally jump to a3. In contrast, the O on d8 may NOT jump to f8, since the loop of X pieces is not fully closed -- the inside is accessible through the e5 - g7 diagonal. Also, note that the 'X' on e3 may not jump to c5 because this jump does not cross from outside the loop to the inside.
The Challenge
Your challenge is to allow two players at the same computer to play a game of Quagmire, adhering perfectly to the rules, against each other.
At every point in the game, your program should output the board as shown in the first example board, reflecting the current positions of all pieces on the board. You may choose any characters for the O, X, and . values, but the rest of the characters must be exactly as shown. You should also display, in a reasonable manner, whose turn it is!
Input
On a players' turn, you should accept a string of at least 5 bytes in the form X#<seperator>Y#. You may make reasonable adjustment to this format to suit your programming language. You may also assume that the input, while not necessarily a legal move, will be formatted correctly (no numbers greater than 8, etc). Your program should evaluate whether or not a move from X# on the board to Y# is legal for this player. If it is legal, your program should make the move and output the next board accordingly. If it is not legal, your program should output some falsy value (0 is perfectly reasonable--you do not need an explanation) and receive another input.
Winning
A player wins when the other player fails to relieve one of his pieces from Quagmire. Alternatively, a player wins when it is their opponent's turn and their opponent has no legal moves. Note that the first win condition takes precedence over the second. If I leave a piece in Quagmire at the end of the turn and simultaneously leave my opponent with no legal moves, I still lose the game. If the game is over after a player's move, you should output the winning board, the winning player's piece character (e.g. 'X') and some truthy value (Again, 1 is sufficient). At this point, your program may either terminate or restart the game.
Challenge Rules

This is code-golf. Smallest code, in bytes, wins.

Standard loopholes are disallowed.

Ruby 2.7, 695...618 610 bytes
i=*0..7
t,*b={}
"?>=<765/.'".bytes{b[_1],b[~_1]=A=?X,E=?O}
loop{puts'
 '+[*?a..?h]*' ',a='+-'*8+?+,i.map{|j|"|#{b[8*~j,8].map{_1||?.}*?|}| #{8-j}
"+a}
eval"M,*m=->u,w=p,*s{Q=(0..8).map{c,r=u;z=c+8*r
#{$f='(v=c+=_1/3-1,r+=_1%3-1)-i==[]&&'}(k=#{$g='b[c+8*r]'}
w ?b[z]==A&&(t[A]!=z&&(#$f!#$g&&(k==A||k&&N[u]&N[v]==[])&&s<<u+v
c,r=u;s<<u+v while#$f!#$g);k):k!=E&&s<<v)};s}
N,*q=->o,n=M[o]{n==n|=n.flat_map{M[_1]}||redo;n}
i.product(i){#{h='M[_1,1];A,E=E,A;([p,A]&Q)[0]&&'}(p A;Z);m+=e=#{h}q+=e}
A,E=E,A
($><<A+?>;c,r,_,x,y=gets.bytes.map{~-_1%8})until[[c,r,x,y]]-(m[0]?q[0]?q:m:(p E;Z))==[]
#$g,b[t[A]=x+8*y]=p,A"}

Try it online! (620 bytes because the older Ruby on TIO doesn't support numbered block parameters.) A simple example game is included that illustrates most of Quagmire's rules. Just for clarity, the input is commented and invalid moves are indented.
Input is in the format x# y#, terminated either by newline or EOF. Any single byte is accepted as the separator. The input prompt is O> for player 1 and X> for player 2. (In an interactive terminal the input appears as it is typed, after the prompt.) The prompt is repeated until a valid move is entered, then the updated board is printed. When the game ends, the winning player's symbol is printed in double quotes; I like to imagine it is raising its arms in victory.
Explanation

While perhaps not a brilliant board game, it ought to be a fun code golf!

Steel your Brain
The first 3 lines perform initialisation. i is a fixed list of row/column numbers. The value of each square on the board (O, X, or nil) is stored in the (1D) array b. Empty squares, stored as nil, are replaced by . on output. The starting configuration is encoded by the 10-byte string ?>=<765/.', whose codepoints give the indices of squares containing X's. t is a hash that stores the index of the piece moved on each player's previous turn (this piece cannot be moved on the next turn). A and E store the 'active' and 'enemy' piece symbols and are interchanged each turn.
Being constants (uppercase names), A and E have global scope. Constants are abused throughout the program to avoid scoping issues that would arise with ordinary local variables. A side effect is that whenever a constant is reassigned, warnings are emitted to STDERR. (These warnings may be suppressed by calling Ruby with the -W0 option.)
Now the main loop begins, running until one player wins. Following the 3 lines that display the board, the remainder of the program is enclosed in an eval string, which allows a few chunks of code (stored in the strings $f, $g, and h) to be recycled. The first 5 lines of this string contain the real meat of the program: the lambdas M and N.
Mary had a little lambda
Let's start with N. N finds the set of all squares that are connected to the square at co-ordinates o (co-ordinates are pairs of 0-indexed column and row numbers). Here, connected means that there is a path between all the squares that is not blocked by enemy pieces. Source and destination squares must be unconnected as a prerequisite for jumping an enemy piece. N fans out from the current square, adding its non-enemy neighbours (n=M[o]) and their neighbours (n|=n.flat_map{M[_1]) to the set n by calling M (see below). We redo this process, adding more neighbours of neighbours, until n no longer changes (i.e. until all connected squares have been found).
M probes the board around the square at co-ordinates u. Its exact behaviour is determined by the switch w, which takes a value of either nil (a.k.a. p) or 1:

When w is nil, M returns an array s of the co-ordinates of all neighbours (8-neighbourhood) of the square at u that do not contain enemy pieces (k!=E). Lambda N uses this information to find the set of all squares that are connected to the current square, as described above. The co-ordinates of each neighbour (column c and row r, stored as the pair v) are obtained by independently advancing c and r by -1, 0, or 1 ((0..8).map...(v=c+=_1/3-1,r+=_1%3-1)), ensuring that c and r both lie within the board ((v=...)-i==[]). This code for finding adjacent squares is required again later, so to save bytes it is stored as a string in $f and interpolated into the eval string. Similarly, the code that returns the value of the square at v is saved in $g ($g='b[c+8*r]').

When w equals 1 and the square at u contains one of the active player's pieces (b[z]==A), M does two things:

It returns an array s containing all possible moves for the active player originating from this square.

It saves the values of all neighbouring squares in Q, which is used later to test for quagmire.

Moves are only allowed if the piece was not moved on the previous turn (t[A]!=z). For jumps, the destination square is found by advancing c and r in the same directions a second time (by interpolating $f) and testing whether this square is empty (!#$g). For a jump to be possible, there must either be an active piece to jump over (k==A) or, if an enemy piece is being jumped, the source and destination squares must be unconnected (k&&N[u]&N[v]==[]). For ordinary moves, c and r are reset (c,r=u) and then both variables are advanced in the same directions as before, one square at a time, until no further move along that path is possible (while#$f!#$g). Moves are saved (s<<u+v) in the format [c,r,x,y], that is, the column and row numbers of the source square followed by the column and row numbers of the destination.

Into the quagmire
The last four lines of the program run the game according to the following steps:

Loop over all squares of the board by forming pairs of column and row numbers (i.product(i)).

For the current square, complete the following steps, all saved in h:

Call M in move-finding mode (M[_1,1]). If the square contains an enemy piece, update Q with the values of the neighbouring squares. (Any possible moves for that piece are also returned, but we immediately discard them: it's not the opponent's turn to move, after all!)

Interchange the active and enemy pieces (A,E=E,A). The reason for interchanging players is that quagmire checks are performed twice per square, once (here in step 2) to find whether the opponent has left a piece in quagmire and again (in step 4) to find whether the active player has been quagmired by the opponent's previous move.

Test whether the current square contains a quagmired enemy piece (([p,A]&Q)[0]). ([p,A]&Q)[0] is truthy only if there are no empty neighbours and at least one neighbour is an active piece.

If the current square contains a quagmired enemy piece then the game is won. Print the active player's symbol (p A) and terminate by throwing a tantrum (Z is not defined).

Repeat step 2, reading 'active' for 'enemy' and vice versa, but this time add all possible moves (neglecting quagmire for the moment) for the active player to m and keep a copy in e (m+=e=#{h}). If the current square contains a quagmired active piece then add e to q as well (q+=e).

Outside the loop, interchange the active/enemy pieces to advance the turn (A,E=E,A).

Finally it's time for some input!

We now have two lists of moves for the active player: m contains all possible moves (neglecting quagmire) whereas q (a subset of m) contains possible moves by any quagmired pieces. (m[0]?q[0]?q:m:(p E;Z)) decides which move list should be used. If m is empty (i.e. the active player has no possible moves) then the game is lost; print the opponent's symbol and terminate (m[0]?...:(p E;Z)). If q is nonempty it takes precedence over m (q[0]?q:m).

Until a valid move is entered correctly (until[[c,r,x,y]]-(...)==[]), display the prompt ($><<A+?>) and convert the input to 0-indexed column/row numbers (gets.bytes.map{~-_1%8}).

Update the source and destination squares, saving the destination index in t (#$g,b[t[A]=x+8*y]=p,A).

Wow, it took 6 years for someone to come along and solve this

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

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


text:
Write the shortest game of alak

Alak was invented by the mathematician A. K.  Dewdney, and described in his 1984 book Planiverse. The rules of Alak are simple:
Alak is a two-player game played on a one-dimensional board with eleven slots on it.  Each slot can hold at most one piece at a
  time.  There's two kinds of pieces, "x" and "o". x's belong to one player, o's to the other.
  The initial configuration of the board is:

      xxxx___oooo

The players take turns moving.  At each turn, each player can move only one piece, once.  A player cannot pass up on his turn.  A player
  can move any one of his pieces to the next unoccupied slot to its right or left, which may involve jumping over occupied slots.  A
  player cannot move a piece off the side of the board.
If a move creates a pattern where the opponent's pieces are surrounded, on both sides, by two pieces of the mover's color (with no
  intervening unoccupied blank slot), then those surrounded pieces are removed from the board.
The goal of the game is to remove all of your opponent's pieces, at which point the game ends.  Removing all-but-one ends the game
  as well, since the opponent can't surround you with one piece, and so will always lose within a few moves anyway.

I found this game online and was wondering: can it be golfed?
Rules of the golf

Your code must follow all the rules in the game, handling captures, proper moving, etc. (only exception is you don't have to add a bot, but you must have both players controlled somehow, and one player must be human).
Input must be move piece at tile X to tile Y, or quit. For example, you can use 1 4 to say 'move this piece at tile 1 to tile 4'. quit would end the program, although using Control-C would be acceptable. You also have to check if a move is invalid (by going outside the board or moving somewhere that you would have to cross over unoccupied spaces to get to or sending a message that is not a pair of tiles or quit).
Outputs for players winning and invalid must be P1 WINS, P2 WINS, and INVALID, respectively. (All of these are 7 characters.)
Output must show the board. That's all that's required.
It doesn't matter if you use any aids like numbered tiles or other pieces.
The challenge ends if:

One answer gets 50 votes
One answer remains the top-voted for 3 weeks, and no other answers were posted in that time

and the challenge has at least 3 answers (so there's some real competition).

Rules of the game

The player on the left must start first.
Only one piece occupies a square at a time. You move the piece left or right until it hits an unoccupied space. The board does not wrap, and you can't move through unoccupied areas. For example:

xoo__o. Here, the x moving right would change the board to _oox_o.
xxooo_. Here, the farthest-left x could move to yield _xooox, which captures the os, leaving _x___x.
x__oox. Here, the os are not captured (there is still a gap). Capture is not possible because you can't move through unoccupied spaces. The x on the left could only move one space, because there are no other pieces in between (leaving _x_oox).

Multiple adjacent pieces can be captured at once if the group is surrounded by the opponent's pieces. E.g. from x_oox to _xoox will capture both os and result in _x__x.
If after a move, you first capture the opponent's pieces, before checking if your own piece should be remove. Take two examples:

o_oxx to oxox_. First, the second o is captured, ox_x_, so the first x remains on the board.
o_oox to oxoo_. This time, none of the os are captured, so the x is captured instead.
If you have only one piece, the game ends, because you can't capture with just one piece.

Let the games begin! I look forward to seeing what you come up with.

Comments purged, as they were obsolete. Please notify me of any comments that should be undeleted.

C, 617 592 bytes
#define O(x)(x-'x'?'x':'o')
q,f,t,k,i,x=4,o=4,*d;main(){char*A,Q[9],c='x',b[]="xxxx___oooo";printf(b);while(!q){scanf(" %8[^\n]%*[^\n]",Q);if(!strcmp(Q,"quit"))break;f=*Q>47&&*Q<58?atoi(Q):-1;A=f>9?Q+2:Q+1;t=*A==32&&A[1]>47&&A[1]<58?atoi(A+1):-1;i=t==f&&t<0&&f<0?1:0;for(k=f;k!=t;k+=(t-f)/abs(t-f))if(b[k]==95||b[t]-95||b[f]-c)i=1;if(i){printf("INVALID");continue;}b[t]=c;b[f]=95;for(t=0;t<2;t++){d=c-'x'?&o:&x;for(k=1;k<11;k++)if(b[k]==O(c)){for(i=k+1;b[i]==O(c)&&b[i];i++);if(b[i]==c&&b[k-1]==c)while(k<i)b[k++]=95,(*d)--;}c=t?c:O(c);}printf(b);if(o<2||x<2)printf("P%d WINS",(x>1)+1),q=1;}}

Unraveled:
#define O(x)(x-'x'?'x':'o')
q,f,t,k,i,x=4,o=4,*d;
main(){
    char*A,Q[9],c='x',b[]="xxxx___oooo";
    printf(b);
    while(!q){
        scanf(" %8[^\n]%*[^\n]",Q);
        if(!strcmp(Q,"quit"))break;
        f=*Q>47&&*Q<58?atoi(Q):-1;
        A=f>9?Q+2:Q+1;
        t=*A==32&&A[1]>47&&A[1]<58?atoi(A+1):-1;
        i=t==f&&t<0&&f<0?1:0;
        for(k=f;k!=t;k+=(t-f)/abs(t-f))
            if(b[k]==95||b[t]-95||b[f]-c)
                i=1;
        if(i){
            printf("INVALID");
            continue;
        }
        b[t]=c;
        b[f]=95;
        for(t=0;t<2;t++){
            d=c-'x'?&o:&x;
            for(k=1;k<11;k++)
                if(b[k]==O(c)){
                    for(i=k+1;b[i]==O(c)&&b[i];i++);
                    if(b[i]==c&&b[k-1]==c)
                        while(k<i)b[k++]=95,(*d)--;
                }
            c=t?c:O(c);
        }
        printf(b);
        if(o<2||x<2)printf("P%d WINS",(x>1)+1),q=1;
    }
}

I really wanted to get this one in ~400 bytes, but there are a lot of little rules here and the input processing ended up pretty obnoxious. I'm definitely not done with this. Here's a set of sample runs that covers just about everything:
xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo4 5
_xxx_xo_ooo8 6
INVALID8 7
_xxx_xoo_oo3 4
_xx_xxoo_oo7 3
_xxo__o__oo1 4
__x_x_o__oo10 9
INVALID10 8
__x_x_o_oo_2 3
___xx_o_oo_6 5
___xxo__oo_6 6
INVALID5 5
INVALID3 6
____x_x_oo_8 7
____x_xo_o_6 8
____x__o_o_P2 WINS

xxxx___oooo0 4
_xxxx__oooo10 6
_xxxx_oooo_1 5
__xxxxoooo_9 1
_o____ooo__P2 WINS

xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo1 5
__xxxxo_ooo10 7
__xxxxoooo_2 10
___xxx____xP1 WINS

xxxx___oooo3 4
xxx_x__ooooquits
INVALIDtestme
INVALID3*4
INVALID3 four
INVALIDthree four
INVALIDthisstringislongerthanmybuffer
INVALID10 0
INVALID4 5
INVALID7 6
xxx_x_o_oooquit

If I've misinterpreted something, please let me know!

I tested it, it works well, and nothing was left out. Good job!

You can save a few bytes by replacing printf("INVALID"); with puts("INVALID");, o<2||x<2 with o<2|x<2 and printf(b);while(!q){ with for(printf(b);!q;){

494 bytes

PHP - 505
<?php
$s="xxxx___ooo".$y=o;$x=x;$c=function($m)use(&$x){return$x.str_repeat('_',strlen($m[1])).$x;};$e='$s=preg_replace_callback("~$x($y+)$x~",$c,$s);';$_=substr_count;while(true){echo$s;if($_($s,x)<2)die("P2 WINS");if($_($s,o)<2)die("P1 WINS");$i=trim(fgets(STDIN));if($i=='quit')die;if(!preg_match('!^(\d+) (\d+)$!',$i,$m)||$s[$f=$m[1]]!=$x||$s[$t=$m[2]]!="_"||(0&($a=min($f,$t))&$b=max($f,$t))||$_($s,"_",$a,($b-$a)+1)>1)echo"INVALID\n";else{$s[$f]='_';$s[$t]=$x;eval($e);$z=$x;$x=$y;$y=$z;eval($e);}}

Notices must be suppressed by redirecting STDERR to /dev/null.
With sane whitespace:
<?php
@$s = "xxxx___ooo".($y = o);
@$x = x;
$c = function($m)usea(&$x){
    return$x.str_repeat('_',strlen($m[1])).$x;
};
$e = '$s=preg_replace_callback("~$x($y+)$x~",$c,$s);';
@$_ = substr_count;
while (true){
    echo $s;

    if (@$_($s,x) < 2) die("P2 WINS");
    if (@$_($s,o) < 2) die("P1 WINS");

    $i = trim(fgets(STDIN));
    if($i == 'quit') die;

    if( !preg_match('!^(\d+) (\d+)$!',$i,$m)
    ||   $s[$f = $m[1]] != $x
    ||  @$s[$t = $m[2]] != "_"
    ||  (0 & ($a = min($f, $t)) & $b = max($f, $t))
    ||  $_($s, "_", $a, ($b - $a) + 1) > 1
    ) echo "INVALID\n";
    else {
        $s[$f] = '_';
        $s[$t] = $x;
        eval($e);
        $z = $x;
        $x = $y;
        $y = $z;
        eval($e);
    }
}

With the test cases of BrainSteel:
xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo4 5
_xxx_xo_ooo8 6
INVALID
_xxx_xo_ooo8 7
_xxx_xoo_oo3 4
_xx_xxoo_oo7 3
_xxo__o__oo1 4
__x_x_o__oo10 9
INVALID
__x_x_o__oo10 8
__x_x_o_oo_2 3
___xx_o_oo_6 5
___xxo__oo_6 6
INVALID
___xxo__oo_5 5
INVALID
___xxo__oo_3 6
____x_x_oo_8 7
____x_xo_o_6 8
____x__o_o_P2 WINS

xxxx___oooo0 4
_xxxx__oooo10 6
_xxxx_oooo_1 5
__xxxxoooo_9 1
_o____ooo__P2 WINS

xxxx___oooo0 4
_xxxx__oooo7 6
_xxxx_o_ooo1 5
__xxxxo_ooo10 7
__xxxxoooo_2 10
___xxx____xP1 WINS

xxxx___oooo3 4
xxx_x__ooooquits
INVALID
xxx_x__ooootestme
INVALID
xxx_x__oooo3*4
INVALID
xxx_x__oooo3 four
INVALID
xxx_x__oooothree four
INVALID
xxx_x__oooothisstringislongerthanmybuffer
INVALID
xxx_x__oooo10 0
INVALID
xxx_x__oooo4 5
INVALID
xxx_x__oooo7 6
xxx_x_o_oooquit

What do you mean by 'notices/warnings'?

@ASCIIThenANSI Warnings because of unquoted character literals: PHP Notice:  Use of undefined constant o - assumed 'o' in /tmp/pcg-48388.php on line 2. One can redirect them to /dev/null.

Does that break the program?

@ASCIIThenANSI No, it does work fine is they are redirected to /dev/null.

Then it's OK to have it as long as the program continues to function properly, and they are redirected to /dev/null.

@ASCIIThenANSI I updated my answer.

Python 2, 536 509 448 441 bytes
Call via a(); moves are to be entered in the form piece,destination (i.e., 1,4); quit with Ctrl-C. If anyone can see more golfing potential, I'm all ears.
b,r,x='_',lambda p:''.join([p[i]for i in x]),range(11)
def a(m='xo'):
 t=w=0;p=dict(zip(x,'xxxx___oooo'))
 while w<1:
    print r(p);y=m[t%2]
    try:
     s,v=input();1/all([y==p[s],{v}<{r(p).rfind(b,0,s),r(p).find(b,s)},v-s]);p[s],p[v],h,c=b,y,0,{}
     for _ in y,m[-~t%2]:
        for i in p:exec{_:"h=1;p.update(c)",b:"h,c=0,{}"}.get(p[i],h*"c[i]=b")
     w=min(map(r(p).count,m))<2;t+=1
    except:print"INVALID"
 print"P%d WINS"%-~(r(p).count('o')<2)

SpecBAS - 718 bytes
SpecBAS is an updated version of Sinclair/ZX BASIC that can run outside of an emulator. (Still interpreted).
Have used some of the new features to get the size down as much as I could.
Line 12 sets up a regex to search for "sandwiched" pieces using inline IF and line 18 uses the wrap around nature of INC (rather than saying INC p: IF p=3 THEN LET p=1)
1 LET b$="xxxx---oooo": LET p=1: LET c$="xo": DIM s=4,4
2 LET v=0: PRINT b$'"[";p;"] ";
3 INPUT m$: IF m$(1)="Q" THEN PRINT "QUIT": STOP
4 LET f=VAL(ITEM$(m$,1," ")): LET t=VAL(ITEM$(m$,2," ")): PRINT f;" ";t
5 IF (f<1 OR f>11) OR (t<1 OR t>11) THEN LET v=1: GO TO 10
6 IF (b$(f)<>c$(p)) OR b$(t)<>"-" THEN LET v=1: GO TO 10
7 FOR i=f TO t STEP SGN(t-f)
8 IF b$(i)="-" THEN IF i<>t THEN LET v=1
9 NEXT i
10 IF v=1 THEN PRINT "INVALID": GO TO 2
11 LET b$(t)=b$(f): LET b$(f)="-"
12 LET r$=IIF$(p=1,"xo+x","ox+o")
13 LET m=MATCH(r$,b$): IF m=0 THEN GO TO 18
14 FOR i=m+1 TO POS(c$(p),b$,m+2)
15 IF b$(i)=c$(3-p) THEN LET b$(i)="-": DEC s(3-p): END IF
16 NEXT i
17 IF s(3-p)<2 THEN PRINT b$'"P";p;" WINS": STOP
18 INC p,1 TO 2
19 GO TO 2

Output (can't copy from the output widow, so screen shot)

C#, 730 bytes
using System;using System.Linq;class P{static void Main(string[]z){int p=1,d,e,g,x,y;var b=new[]{3,1,1,1,1,0,0,0,2,2,2,2};var o=new[]{"_","x","o"};Action<string>h=s=>{Console.Write(s,p);Environment.Exit(0);};Action i=()=>h("INVALID");Func<int,int,bool>j=(q,r)=>b.Select((v,w)=>w<=q||w>=r||v>0?0:w).Any(w=>w>0);Action<int>k=m=>{e=0;for(d=1;d<12;d++){if(b[d]==m){if(e>0&&!j(e,d))for(g=e+1;g<d;g++)b[g]=0;e=d;}}if(b.Count(w=>w>0&&w!=m)<3)h("P{0} WINS");};try{for(;;){for(g=1;g<12;g++)Console.Write(o[b[g]]);var n=Console.ReadLine();if(n=="quit")h("");var c=n.Split(' ');x=int.Parse(c[0]);y=int.Parse(c[1]);if(c.Length>2||b[x]!=p||b[y]!=0||(p>1?y:x)>=(p>1?x:y)||j(x<y?x:y,x<y?y:x))i();b[x]=0;b[y]=p;k(p);p=p>1?1:2;k(p);}}catch{i();}}}

I imagine that further improvements are possible.  On the other hand, I interpreted the INVALID output as ending execution, so I may need to fix that issue to be in parity with other answers.


text:
Unwise bit operations
I like to golf in dc, but I'm sometimes frustrated because dc doesn't have bitwise operations.
Challenge
Provide four named functions which implement the equivalent of the c bitwise operations &, |, ~ and ^ (bitwise AND, OR, NOT and XOR).  Each function will take two operands (~ takes only one) which are at least 32-bit unsigned integers.  Each function will return an unsigned integer of the same bit-width as the operands.
Restriction
You may only use operations that are supported by dc.  These are:

+ - * / Arithmetic addition, subtraction, multiplication and division
~ modulo (or divmod if your language supports it)
^ exponentiation
| modular exponentiation
v square root
> >= == != <= < standard equality/inequality operators
>> << bit shift operators.  dc doesn't have these, but since they are trivially implemented in terms of division/multiplication by powers of 2, then I will allow these.

Control structures in dc my be clumsily built using (recursive) macros and (in)equality operations.  You may use whatever built-in control structures your language has.
You may also use logical operators && || !, even though these aren't directly available in dc.
You must not use the bitwise operators &, |, ~ and ^ or any functions that trivially implement them.
In addition you must not use built-in base-conversion-of-string operators or functions.

Please also consider providing a test program or online compiler snippet (not included in the golf score) to help verify your answer.

Can we implement one function that takes the desired operation as a parameter? Also, can we integer-divide by 2 as a stand-in for bit-shift?

@xnor You must provide 4 public functions that implement each of the four operators.  You may also have common/helper private methods/functions that are called by all four public functions, but these will all need to be included in the golf score.

@xnor You and you only must also implement the xnor operator ;-)

Can I produce a list of four anonymous functions?

@MariaTidalTug What's the effective difference between returning a list of four functions and manually selecting and applying one (as xnor suggested) versus having one function that accepts the selection parameter and performs the selection itself (as wolfhammer answered)? They both seem to similarly undermine the point of having four named functions, as they offload code size onto the user code. I'd even argue that the former undermines it more, as the user code is probably more complex in that case than in the latter case.

@Runer112 good point.

@xnor.  Runer has a good point.  Sorry for the rule change.  I'm banning anonymous functions.

Are there any restrictions on the names of the functions? How about a dictionary of four functions, so you can invoke a function by a letter?

@xnor 4 named functions.  Call them what you like as long as they are named. a, o, n and x will do just fine :)

C, 134
The C preprocessor is pretty fun to abuse. Basically this macro defines the 3 functions, a, o, and x, for and, or, and xor respectively. The only difference in the algorithm for these operations is the criteria for setting the bit in the result.
not is the function n.
#define f(n,c)n(a,b){for(r=0,i=31;i+1;--i)if(((a>>i)%2+(b>>i)%2)c)r+=1<<i;return r;}
i,r;n(a){return 0xffffffff-a;}f(a,/2)f(o,)f(x,%2)

Tester program (takes a long time, I didn't spend any time optimizing it at all, but it does test every test case possible, beside MAX_INT related ones):
#define m_assert(expected, condition, actual)\
    if(!((expected) condition (actual)))\
        printf("assert fail @ line %i, expected: %x, actual %x, condition "#condition"\n", __LINE__, expected, actual);

int main()  {
    unsigned int j,k;
    for(j=0; j<0xffff; ++j)    {
        m_assert(~j, ==, n(j));
        for(k=0; k<0xffff; ++k)    {
            m_assert(j & k, ==, a(j,k));
            m_assert(j | k, ==, o(j,k));
            m_assert(j ^ k, ==, x(j,k));
        }
    }

oops. forgot about that. fixed that now.

ised 76 bytes
ised also doesn't have bitwise operations - usually annoying, but now welcome, because we really need to implement them.
Functions will be stored in numbered memory slots (no verbose names).
Conversion to and from binary:
@5{:x/2^[32]%2:};
@6{:x@:2^[32]:};

NOT could be @1{:$6::{1-$5::x}:} but it's obviously easier to just subtract:
@1{:2^32-x-1:};

OR:
@2{:$6::{$5::{x_0}:+$5::{x_1}>0}:};

AND:
@3{:$6::{$5::{x_0}:*$5::{x_1}}:};

XOR:
@4{:$6::{$5::{x_0}:<>$5::{x_1}}:};

This would bring us to 156 bytes (with newlines and semicolons). A test code would just be (NOT, OR, AND, XOR in succession, found under names $1,$2,$3,$4):
> $1::{6}
4294967289
> $2::{12 11}
15
> $3::{12 11}
8
> $4::{12 11}
7

But of course OR and NOT are all we really need and things can be simplified:
@1{:2^32-x-1:};
@2{:@+{2^U{?{$5::x}%32}}:};
@3{:${1 2 1}::x:};
@4{:$3::{$2::x${1 2}::x}:};
@5{:x/2^[32]%2:};

That's 109 characters. When newlines and semicolons are skipped, and with a bit more golfing, we have 76 characters:
@3{@1{:2^32-x-1:}@2{:@+{2^U{?{x/2^[32]%2}%32}}:}$1}@4{{:$2::x${1 2}::x:}$3};

Nim (537)(490)
Nim Compiler 0.10.2
I've been looking for a reason to learn nim so here we go.
For code golf, I have leveraged variable parameters and implicit returns. The variable parameters, per the documentation are less stack efficient. Personally, I find the implicit returns harder to read and would probably only use them in trivial procedures.
As for the algorithms, they are simple enough. For all operations except NOT, we compare each bit and manually compare them to our expected truth table. Set each bit as needed along the way in our output variable. In Nim, result is the implicit return value.
I wasn't sure if we were allowed to use built-in OR and AND for asserting two boolean conditions so the notZero procedure was put in their place.
proc s(x, y, b: var int)=
  x = x div 2
  y = y div 2
  b *= 2

proc n(x: var int): int =
  return -(x+1)

proc a(x, y: var int): int =
  var b = 1
  while x > 0 and y > 0:
    if (x mod 2  + y mod 2) == 2:
      result += b

    s(x,y,b)

proc o(x, y: var int): int =
  var b = 1
  while x + y > 0:
    if (x mod 2 + y mod 2) >= 1:
      result += b

    s(x,y,b)

proc r(x, y: var int): int =
  var b = 1
  while x + y > 0:
    if (x mod 2 + y mod 2) == 1:
      result += b

    s(x,y,b)

Still looking for a better method...
Here is the non-squished version plus full test harness to run on your own machine.
If you just want to run a couple of inputs, here is test case lite.

@MariaTidalTug thanks for clarifying!

I can't reproduce that. Is your calculator in base-16 mode?

I added a test harness similar to pseudonym117's.

CJam, 71 bytes
{:F;0{:R;2md@2md@+F~!2I#*R+}64fI\;\;}:B{"2-"B}:A{'!B}:O{0SB}:N{'(B}:X];

Explanation
"B : UInt64 UInt64 String -> UInt64
 Computes a bitwise operation on the two given unsigned integers. The operation
 is defined by the logical inverse of the result of evaluating the given string
 given the sum of two input bits.";
{
  :F;             "Save the operation string.";
  0               "Initialize the result to 0.";
  {               "For I from 0 through 63:";
    :R;             "Save the result.";
    2md@2md@        "Divide each input by 2 and collect the remainders as the
                     next pair of bits to process.";
    +F~!            "Compute the logical inverse of the result of evaluating
                     the operation string given the sum of the two bits.";
    2I#*            "Adjust the resulting bit to be in the correct output
                     position by multiplying it by 2^I.";
    R+              "Add the location-adjusted bit to the result.";
  }64fI
  \;\;            "Clean up.";
}:B

"A : UInt64 UInt64 -> UInt64
 Computes the bitwise AND of the two given unsigned integers.
 This is done by passing the inputs along to B with an operation such that:
   bit_out = !((bit_in_1 + bit_in_2) - 2)";
{"2-"B}:A

"O : UInt64 UInt64 -> UInt64
 Computes the bitwise OR of the two given unsigned integers.
 This is done by passing the inputs along to B with an operation such that:
   bit_out = !(!(bit_in_1 + bit_in_2))";
{'!B}:O

"N : UInt64 -> UInt64
 Computes the bitwise NOT of the given unsigned integer.
 This is done by passing the input and 0 along to B with an operation such that:
   bit_out = !((bit_in + 0))";
{0SB}:N

"X : UInt64 UInt64 -> UInt64
 Computes the bitwise XOR of the two given unsigned integers.
 This is done by passing the inputs along to B with an operation such that:
   bit_out = !((bit_in_1 + bit_in_2) - 1)";
{'(B}:X

];              "Clean up.";

Test suite
This code tests runs of each of my and, or, not, and xor functions 100 times with uniformly-distributed 64-bit unsigned inputs and compares the result with that produced by the built-in operator. Due to gratuitous use of the eval operator, it's quite slow and may take up to about a minute with the online interpreter. But if all goes well, execution should end with no output, because any discrepancies found are printed.
N:L;
{:F;0{:R;2md@2md@+F~!2I#*R+}64fI\;\;}:B{"2-"B}:A{'!B}:O{0SB}:N{'(B}:X];
{;Y32#__mr*\mr+}2e2%2/{~:U;:V;"A&O|X^"2/{[{US@SV" = "UV5$~L}/9$2$={];}{]oLo}?}/"N~"[{U" = "U3$~Y64#(&L}/6$2$={];}{]oLo}?}/

JavaScript 294 267
Was able to shave off a few more bytes with @AlexA.'s and @kennytm's suggestions.
Functions:
B=(n,m,t)=>{for(var p=4294967296,y=0;p>=1;p/=2)y+=t=='x'&&(n>=p||m>=p)&& !(n>=p&&m>=p)?p:0,y+=t=='a'&&n>=p&&m>=p?p:0,y+=t=='o'&&(n>=p||m>=p)?p:0,n-=n>=p?p:0,m-=m>=p?p:0
return y}
N=(n)=>{return 4294967295-n}
A=(n,m)=>B(n,m,'a')
O=(n,m)=>B(n,m,'o')
X=(n,m)=>B(n,m,'x')

example:
var n = 300;
var m = 256;
console.log(X(n,m) + ", " + (n ^ m));
console.log(O(n,m) + ", " + (n | m));
console.log(A(n,m) + ", " + (n & m));
console.log(N(n) + ", " + (~n>>>0));
console.log(N(m) + ", " + (~m>>>0));

output:
44, 44
300, 300
256, 256
4294966995, 4294966995
4294967039, 4294967039

You need to provide four public functions - one each for AND, OR. NOT and XOR. (You may also have common/helper private methods/functions that are called by all four public functions).  Also, you are missing the NOT - probably the easiest of all of these to do

Thanks @AlexA.  I've added the bytes and golfed it some more.

You can lose the space after for and replace function B(n,m,t) with B=(n,m,t)=>. Likewise for the other functions.

① You could use 4*(1<<30) for 4294967296 and -1>>>0 for 4294967295. ② is the var truly necessary here? ③ you could write (n,m)=>B(n,m,'a') instead of (n,m)=>{return B(n,m,'a')}


text:
Row, Column, Diagonal, Block
Write a square block of code that is N characters wide and N characters tall, for some positive integer N.
For instance, your N may be 5 and the block look like this:
ThisI
sMy5B
y5Cod
eBloc
kOkay

This block needs to behave as follows:

When the top row is extracted and run as a program, the exact text row needs to be printed to stdout.
For example, ThisI would print row.
When the left column is extracted and run as a program, the exact text col needs to be printed to stdout.
For example, Tsyek would print col.
When the main diagonal from the top left to the bottom right corners is extracted and run as a program, the exact text dia needs to be printed to stdout.
For example, TMCoy would print dia.
When the entire block is run as a program, including the newlines (with an optional trailing newline), the exact text blk needs to be printed to stdout.
For example,
ThisI
sMy5B
y5Cod
eBloc
kOkay

would print blk.

Details

All four programs are run in the same programming language.
The N2 characters in the original block may be anything but line terminators.
If your language does not have an stdout, you may use another common output method. It must be the same method across all four programs.

The submission whose original block contains the fewest distinct characters (not counting newlines) wins. Tiebreaker goes to the submission with the smaller N.

Given that there's surely a solution in some two-symbol esoteric language, I think this will become a solution to squeeze that into the smallest N.

@xnor Probably. Though a 1-distinct Lenguage answer is not out of the realm of possibility. Still, this scoring method is more interesting than having smallest N win first.

How can Lenguage work given that the row and column programs have the same length?

@xnor Ah, you're right. It wouldn't work.

Can non-block programs also end with a trailing newline?

><> (Fish), 3 unique characters (N = 2000)
The code uses 1 and - to put arbitrary numbers on the stack and p to (self-)modify the code based on the top 3 numbers on the stack.
E.g Putting a ! at position 0 0 would look like 003b*p in normal ><> and with p1- it becomes 111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-11-p.
After the modification the instruction pointer (IP) wraps around the code and runs the modified part. In the "block" case the IP is redirected for further modification (then reredirected back) to differ from the "row" case. In the "row" case the same two redirection happens but there is no code in between them so they have no effect.
The final generated codes for the 4 cases (omitting the unchanged p1- parts):
row:      "wor"\ooo;

column:   "loc"ooo;

diagonal: "dia"ooo;

block:    "wor"\"klb"ooo;

The code size is 4 MB and the code is accessible here. (There is no difficulty running it.)
The generator python3 program is accessible here.

CJam, 13 12 unique characters, N = 5
"row"
cd;"a
oaiaa
l"aa;
"blk"

As straight forward as it gets
UPDATE : Converted space to a (no-op in this case) as pointed out by Runner112
Try it online here

Every space can be turned into a character like a to bring the unique character count down to 12, right?

@Runer112 Damn! Thanks for the tip!

Bash, 19 unique characters, N = 19
trap echo\ row exit
t=t trap exit
t=t echo blk
exit
=
t    e
      c
e      h
c       o
h
o         d
           i
c           a
o
l

The first row is trap echo\ row exit.  This causes echo row to be executed when the script exits (just the first line)
The first column is ttt=t echo col
The diagonal is t=tt echo dia
The full block works by canceling the EXIT handler set up in the first line, then echo blk then exits.

You can use lowercase exit to reduce unique characters by 4. You can also move the exit command to the next line and replace all the semicolons with spaces.

><>, 14 unique characters, N = 10
"wor"\ooo;
     "
l a  k
o  i l
c   db
"    "
o    oo
o    o o
o    o  o
;    ;   ;

Pretty straightforward in a 2D language. The only tricky part is that we need the \ to distinguish between row and blk.

randomra notes that p1- would give a three char solution, but it would be really annoying to generate (and probably won't win).

Brainfuck, 2 unique characters, N = 378
With possible slight bending of rules.
The program is a tad large, so here's a link to it on Pastebin.
The row, col and dia programs are straightforward. They simply increment the byte cell until the right ASCII code is reached and then outputs. If the letter has already passed, it increments until the cell overflows so it can start again at 0.
The blk program is where the slight rule bending occurs. In order to print the "exact text blk" as asked in the challenge, backspaces are used (ASCII code 8), which requires the displaying console/terminal to support it. Whenever errant values from the row/col/dia programs are printed, I ensure they are removed by outputting a few backspace control codes. To simplify things, I've ensured that all errant values outputted at one point are part of the printable ASCII range.

C (gcc), 26 unique chars, N = 29
*w;main(){printf(w?w:"row");}
ww;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;/*;;;;;;;;;;;;;;;;;;;;;;;;
m;;m;;;;;;;;;;;;;;;;;;;;;;;;;
a;;;a;;;;;;;;;;;;;;;;;;;;;;;;
i;;;;i;;;;;;;;;;;;;;;;;;;;;;;
n;;;;;n;;;;;;;;;;;;;;;;;;;;;;
(;;;;;;(;;;;;;;;;;;;;;;;;;;;;
);;;;;;;);;;;;;;;;;;;;;;;;;;;
{;;;;;;;;{;;;;;;;;;;;;;;;;;;;
p;;;;;;;;;p;;;;;;;;;;;;;;;;;;
r;;;;;;;;;;r;;;;;;;;;;;;;;;;;
i;;;;;;;;;;;i;;;;;;;;;;;;;;;;
n;;;;;;;;;;;;n;;;;;;;;;;;;;;;
t;;;;;;;;;;;;;t;;;;;;;;;;;;;;
f;;;;;;;;;;;;;;f;;;;;;;;;;;;;
(;;;;;;;;;;;;;;;(;;;;;;;;;;;;
";;;;;;;;;;;;;;;;";;;;;;;;;;;
c;;;;;;;;;;;;;;;;;d;;;;;;;;;;
o;;;;;;;;;;;;;;;;;;i;;;;;;;;;
l;;;;;;;;;;;;;;;;;;;a;;;;;;;;
";;;;;;;;;;;;;;;;;;;;";;;;;;;
);;;;;;;;;;;;;;;;;;;;;);;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
};;;;;;;;;;;;;;;;;;;;;;;};;*/
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;*w="blk";

Try it online!

V (vim), 11 unique characters, N=6
irow␛␛
cdddd␛
o␛i␛␛␛
l␛␛a␛␛
␛kdd␛␛
␛iblk␛

Try it online!
lot of escapes here. N=5 might be achievable, but I can't see a way to do it without increasing the unique characters.

Ruby, 24 unique chars, N=17
trap(0){$><<:row}
rr=a=:blk;%;00000
a0a00000000000000
p00p0000000000000
(000(000000000000
00000000000000000
)00000)0000000000
{000000{000000000
$0000000$00000000
>00000000>0000000
<000000000<000000
<0000000000<00000
:00000000000:0000
c000000000000d000
o0000000000000i00
l;;trap(0){$><<a;
};000000000000;{}

Try it online!


text:
Programs to build a rat maze
You have been hired as a research assistant, and asked to create a small program
that will build rat mazes. The rat box is always 62x22 and has an entrance (a)
and exit (A) for the rat, like this (input 1):
#######a######################################################
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#################################################A############

Your program must fill the box with blocks (#) leaving a path for the rat, like
this (output 1):
#######a######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
#######                                           ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
################################################# ############
#################################################A############

This is easy you think! You start writing a small program, full of confidence.
However, the Principle Scientist has had a new idea -- he wants two rats to
navigate the maze at the same time. Dr Rattanshnorter explains that they have
different doors and different exits (input 2):
#b#####a######################################################
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            B
#                                                            #
#################################################A############

The rats have been trained to move straight through cross intersections but
T-intersections leave them hopelessly confused and will invalidate the
experiment. You start on your new more complex task when the good Doctor explains
one final requirement: the rats are savage to each other so if they see each
other at any point, a rat fight will break out and you will both be before the
ethics board. You now realise your program should output a maze something like
this (output 2):
#b#####a######################################################
# ##### ######################################################
# ##### ######################################################
# ##### #######################################           ####
# ##### ####################################### ######### ####
# #####                                           ####### ####
# ############################################# # ####### ####
# ############################################# # ####### ####
# ############################################# # ####### ####
# ############################################# # ####### ####
#                                               # ####### ####
################################################# ####### ####
################################################# ####### ####
################################################# ####### ####
################################################# ####### ####
################################################# ####### ####
################################################# ####### ####
################################################# ####### ####
################################################# ####### ####
################################################# #######    B
################################################# ############
#################################################A############

By the time rat B reaches the intersection, rat A will be travelling down the
corridor to exit A and the rat fight will be avoided.
Rules:

Your program should read in (STDIN or file) an input like those above, and
output (STDOUT or file) the same data except many spaces will now be hashes (#). You may substitute any single character (such as ;) instead of \n in the input string but the output string still requires \n characters. UPDATED
A rat pathway must be one character width wide, except for cross intersections (every space must have zero or two orthogonally adjacent # characters). Each rat must have a clear single path, except for cross intersections. No T-intersections are allowed.
Rats are released simultaneously and move at a constant rate. At no time should
two or more rats see each other (be in the same column or row without one of
more # characters in between).
If no solution is possible (such as adjacent entrance points), print
Impossible\n and exit.
Entrances and exits can be on any sides, however they will never be on the corners.
If a matched entrance and exit are adjacent (eg: ##aA##), the rat cannot go directly from a to A. There must be a small 2 space corridor section inside the maze area.
On the turn where a rat reaches its exit point (or any time after that), it is no longer visible to other rats.
Your program may be designed to compute mazes for 1, 2, up to 26 rats.
Standard loopholes are disallowed.

Score:
With your solution, nominate how many rats per maze (N) your program can solve. Your
score is your code length in bytes divided by this number N.
Please include a sample output in your answer so we can see what your program produces.

Is the only difference in the possible inputs the locations of a,A,b,B?

For the 2 rat version, yes. If your program is designed for up to 3 rats, you would need to cope with all possible locations of a,b,c,A,B,C.

Are T intersections allowed if the rat will only walk alongside the horizontal part of the T?

No, these rats are easily confused. Only straight paths, elbow bends, and cross roads are allowed.

@CarpetPython Can an entrance/exit be anywhere along the edge of the maze? Can they be adjacent?

As mentioned in the rules above, they may be adjacent and therefore that input is not solvable. Entrance/exits will never be on the corners though.

I meant adjacent entrance and exit, like this: https://gist.github.com/orlp/f986056d28eb0a4a3a9e

Oh, I get it. It is a valid input to have 'aA' adjacent like that, and is trivial to solve. An input with 'ab' together is valid but impossible to solve (so output Impossible).

@CarpetPython Can open space be seen a series of cross intersections? Example: https://gist.github.com/orlp/f986056d28eb0a4a3a9e

Please note the updated rule 2 above. Rat paths must be single character width.

@CarpetPython It doesn't say that. It says there must be zero or 2 orthogonal characters - a cross intersection for example is an invalidation of 'single character width'.

Mmmm. I will try to make that rule more clear.

@CarpetPython Can rats move along other rats' exits and ignore them? Example. Or are those unsolvable? What about cases where there are 3 adjacent exits?

Yes, rats will only use their own exit, and ignore others. Your example solution looks ok. Three adjacent exits should be ok in principle, but I can't see how it could still follow the  2 or 0 # per space rule.

Can I output a maze with sparse walls? http://pastebin.com/hRxud3cX for example, no rat ever encounters a three-way junction; its just that most of the spaces they pass through are four-way junctions.

@AJMansfield, please rule 2 above: "A rat pathway must be one character width wide, except for cross intersections (every space must have zero or two orthogonally adjacent # characters). Each rat must have a clear single path, except for cross intersections.". This would mean that sparse layouts are not valid solutions.

@CarpetPython I would interpret that wording to mean that they are valid, because every rat's path is one character wide, except at cross intersections, because most of the rat's path is through cross intersections. If that is your intent, you need to reword it to express that idea. Something like "any space that is not used by a rat as a path must have a wall in it", although that is a but cumbersome.

@CarpetPython But I strongly disagree that such solutions should be invalid anyway. I think that sparse solutions should be allowed. Deriving a non-sparse solution from a sparse one would be a trivial operation, but would mean that programs that arrive at their solutions by placing things in a sparse arrangement would need to include additional code to thicken the solution.

I can see your point AJ, but I decided on the corridor requirement early when I designed this challenge. There are several good reasons to limit paths to corridors, not the least of which is visual validation. May I suggest a statement at the end like for xy in grid: cell[xy]='#' if xy not in paths to fill in non-path cells? I hope this limitation will not put you off this challenge. I look forward to seeing your solution.

@CarpetPython If the algorithm I'm playing with pans out the way I think it will, although it might not work at all...

@CarpetPython If the entrance is adjacent to the exit, do you need any path at all, or can the rat go straight from the entrance to the exit? ##aA##

@Hjulle, good question. The rat will need some corridor. They cannot go from a to A directly.

@CarpetPython Would ##aA##\n##  ##\n###### be a valid solution then, or is it unsolveable?

The only valid solution would be ##aA##\n##..##\n###### (note the 2 space corridor shown as .. here) as the "zero or 2 # per space" rule would block any other option.

@CarpetPython Can rats see other rats that have already exited from the maze?

No. Once a rat has reached its exit place, no other rats can see it (maybe it drops down a chute into its own cage).

For javascript in a browser, stdin equivalent is usually 'prompt()', but it does not work for multiline strings. May I write a function with a string (multiline) parameter?

If I add "you may substitute any single character (such as ;) instead of \n in the input string.", would this solve the problem?

Are you sure that this can be solved in polynomial time in general? My strategy is probably not the best, but just going 2 steps with 6 rats leads to    46656 possibilities.

I have made no promises or predictions on the algorithmic complexity of this puzzle. I tend to make my challenges complex enough (see questions in my profile) that brute force search is not practical. You usually need clever optimisations to make a good answer.

Haskell, 26 rats?, ~5000 bytes
Theoretically, this code should work for any number of rats, but I offer no warranty that it will terminate before the heat death of the universe. It is based on a backtracking algorithm which tries to go the straight path first, and then switch path if the path doesn't work. The number of alternatives is exponential with respect to the length of the path and the number of rats.
I haven't bothered to golf it yet, since it's so large, and since I want to make it faster first.
{-# LANGUAGE FlexibleContexts #-}
module Main (main) where

import Control.Lens
import Control.Monad
import Data.Char
import Data.Function
import Data.List
import Data.Maybe

type Pos = (Int,Int)
type Path = [Pos]
type Maze = String
type Input = [(Pos,Char)]
type MazeState = [(Path,Path)]

type ChoiceMonad a = [a]

instance (Num a, Num b) => Num (a,b) where
  (x,y)+(x',y')=(x+x',y+y')
  (x,y)-(x',y')=(x-x',y-y')
  fromInteger n = (fromInteger n,fromInteger n)

parseMaze :: Maze -> Input
parseMaze maze = maze ^@.. inner . filtered (`notElem` "# ")

inner :: IndexedTraversal' Pos Maze Char
inner = lined <.> traversed

main :: IO ()
main = do
    maze <- readFile "Sample2.in"
    putStrLn $ solveAndShow maze

fillMaze :: Maze -> Maze
fillMaze = inner.filtered(==' ').~'#'

updateMaze :: Path -> Maze -> Maze
updateMaze path = inner.indices (`elem` path).filtered(=='#') .~ ' '

isDone :: MazeState -> Bool
isDone = all (null . snd)

showMaze :: Maze -> MazeState -> Maze
showMaze maze path = updateMaze (fst =<< path) $ fillMaze maze

showSolution :: Maze -> ChoiceMonad MazeState -> String
showSolution _    []    = "Impossible"
showSolution maze (x:_) = showMaze maze x

stopCondition :: ChoiceMonad MazeState ->  Bool
stopCondition x = not $ null x || isDone (head x)

solveAndShow :: Maze -> String
solveAndShow maze = showSolution maze . solve $ mazeToState maze

solve :: ChoiceMonad MazeState -> ChoiceMonad MazeState
solve = fromJust . find (not.stopCondition) . iterate fullStep

mazeToState :: Maze -> ChoiceMonad MazeState
mazeToState maze = do
    let startsEnds = paths $ parseMaze maze
        return $ startsEnds & traverse.both %~ (:[])

fullStep :: ChoiceMonad MazeState -> ChoiceMonad MazeState
fullStep = (>>= stepAll)

stepAll :: MazeState -> ChoiceMonad MazeState
stepAll input = do
    pths <- mapM goStep input
    guard $ iall (checkVisible pths) $ map fst pths
    return $ pths
  where
    goStep :: (Path,Path) -> ChoiceMonad (Path,Path)
    goStep (curr:rest,[]) = return (curr:curr:rest,[])
    goStep (curr:these,end:ends)
       | distance curr end == 1 = return (end:curr:these,ends)

       | curr == end = goStep (curr:these,ends)
    goStep (path,end) = do
      next <- twoSteps (head end) path
      prev <- twoSteps next end
      return $ (next:path,prev:end)
    inMaze = inMazeWith input

    twoSteps :: Pos -> Path -> ChoiceMonad Pos
    twoSteps goal path = do
      next <- oneStep goal path inMaze
      guard $ not.null $ oneStep goal (next:path) (\x -> x==next || inMaze x)
      return next

checkVisible :: MazeState -> Int -> Path -> Bool
checkVisible _    _ [] = True
checkVisible pths i xs@(x:_) = checkBack && checkNow
  where
    nBack = 1 + visibleBackwards xs
    --checkBack = none (any (==x).take nBack .fst) pths
    checkBack = hasn't (folded.indices (/=i)._1.taking nBack folded.filtered (==x)) pths
    checkNow  = inone (\i' (x':_,_) -> (i/=i') && (==x') `any` take nBack xs ) pths

-- How long have you stayed on a line
visibleBackwards :: Path -> Int
visibleBackwards as = length . takeWhile ((==headDiff as) .headDiff). filter ((>=2).length) $ tails as
      where headDiff (a:a1:_) = a-a1
            headDiff x        = error $ "Bug: Too short list " ++ show x

inMazeWith :: [(Path, Path)] -> Pos -> Bool
inMazeWith = flip elem . concatMap (\x->snd x ++ fst x)

oneStep :: MonadPlus m => Pos -> Path -> (Pos -> Bool)  -> m Pos
oneStep end (curr:prev:_) inMaze =
  if distance curr end <= 1
     then return end
     else do
    let distance' :: Pos -> Double
        distance' x = fromIntegral (distance x end) + if curr - prev == x - curr then 0 else 0.4
    next <- msum . map return $ sortBy (compare`on`distance') $ neighbors curr

    -- Don't go back
    guard $ next /= prev

    -- Stay in bounds
    guard $ isInBounds next

    let dir = (next - curr)
    let lr = neighbors next \\ [curr,next+dir,end]

    -- If next is blocked, check that the one after that is free
    if inMaze next
      then do
        guard $ not . (\x->(x/=end)&&inMaze x) $ next + dir
        -- Both sides should be blocked as well
        guard $ (==2). length . filter inMaze $ lr
      else do
        -- No neighbors if empty
        guard $ null . filter inMaze $ lr

    -- All neighbors of 'curr', including 'next'
    let neigh' = filter (\i -> inMaze i || i == next) $ neighbors curr
        -- should be an even number
        guard $ even $ length neigh'

    return next
oneStep _ [start] _ = return $ inBounds start
oneStep _ _ _ = error "Too short path given"

toBounds :: (Num a, Eq a) => (a,a) -> a -> a
toBounds (low, high) x
    | x == low  = x + 1
    | x == high = x - 1
    | otherwise = x

distance :: Pos -> Pos -> Int
distance (x1,y1) (x2,y2) = abs(x1-x2)+abs(y1-y2)

-- Moves a pos to the closest one inside the bounds
inBounds :: Pos -> Pos
inBounds = bimap (toBounds (0,21)) (toBounds (0,61))

isInBounds :: Pos -> Bool
isInBounds x = x == inBounds x

neighbors :: Pos -> [Pos]
neighbors pos = [ pos & l %~ p| l <- [_1,_2], p <- [succ,pred]]

paths :: Input -> [(Pos,Pos)]
paths pos = flip unfoldr 'a' $ \x ->
  do (y,_) <- find ((==x).snd) pos
     (z,_) <- find ((==toUpper x).snd) pos
     return ((y,z),succ x)

Sample output, 6 rats:

##c###B#####b#######C#######F######################f##########
##   #       #       #######                        ##########
####  ######## ###############################################
#####          ###############################################
##############################################################
##############################################################
##############################################################
##############################################################
##############################################################
##############################################################
##############################################################
##############################################################
##############################################################
##############################################################
#############       ##########################################
############# #####  #########################################
D             #    #     #####################################
##############  ## ##### #####################################
#########      #                 #############################
######### ###### # ##### ####### #############################
####      #      #     # #######                        ######
####E######a##########e#d##############################A######

When b gets to the intersection of e and b, is he not seen by e? b seems to get there at t = 11, which would put e still in that corridor. Am I missing something?

@BrainSteel Yes, that is correct. My answer is invalid. I noted to myself previously that I needed to check for collisions "backwards in time" as well (after crossing other rats paths), but for some reason I decided that it wasn't needed. :P

@BrainSteel I believe I have fixed that bug now.

Haskell, 1 rat, 681 Characters
The problem can be trivially solved for all mazes with just one rat. This code also "works" for any number of rats, but doesn't follow any of the constraints on the interactions between multiple rats and paths.
module Main where
import Control.Lens
import Data.List(unfoldr,find)
import Data.Char(toUpper)
parse=(^@..lined<.>folded.filtered(`notElem`"# "))
main=interact$do i<-(naive=<<).rats.parse;(lined<.>traversed).filtered(==' ').indices (`notElem`i).~'#'
    naive(start,(ex,ey))=start':unfoldr go start' where
     start'=bnds start
     (ex',ey')=bnds(ex,ey)
     go(x,y)
      |(x,y)==(ex',ey')=Nothing
      |x== ex'=ok(x,y`t`ey')
      |otherwise=ok(x`t`ex',y)
     ok z=Just(z,z)
     t x y=if x>y then x-1 else x+1
    bnd(l,h)x |x==l=x+1 |x==h=x-1 |True=x
    bnds=bimap(bnd(0,21))(bnd(0,61))
    rats pos=(`unfoldr`'a')$ \x->
  do (y,_)<-find((==x).snd)pos
     (z,_)<-find((==toUpper x).snd)pos
     return((y,z),succ x)

Sample output:
#######a######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
####### ######################################################
#######                                           ############
#################################################A############

I'm planning to support many rats, so I wrote generic code, but I haven't found a good algorithm for that yet.

parse extracts a list of all entrances and exits, with their coordinates
rats takes that list and converts it to pairs of coordinates for each rat.
bnds takes a coordinate on an edge and moves it to the nearest coordinate inside the maze.
naive takes a start and end positions and returns a simple path between them.
main then replaces all the white space not in a path with '#'

@edc65 "... constraints between multiple rats". This is an answer for just 1 rat, which is allowed according to the question.

OK my fault. Just thinking that for 1 rat it's a different challenge. I'm going to delete my previous comments