text:
Golf a transcendental number
Definitions

An algebraic number is a number that is a zero of a non-zero polynomial with integer coefficients. For example, the square root of 2 is algebraic, because it is a zero of x^2 - 2.
A transcendental number is a real number which is not algebraic.

Task
You are to choose a transcendental number.
Then, write a program/function that takes a positive integer n and output the n-th decimal digit after the decimal point of your chosen transcendental number. You must state clearly in your submission, which transcendental number is used.
You can use 0-indexing or 1-indexing.
Example
e^2=7.389056098... is a transcendental number. For this number:
n output
1 3
2 8
3 9
4 0
5 5
6 6
7 0
8 9
9 8
...

Note that the initial 7 is ignored.
As I mentioned above, you can choose other transcendental numbers.
Scoring
This is code-golf. Lowest score in bytes wins.

How do the different answers handle the fact that there is a finite number of integers that can be used as an argument? 0 would be an acceptable answer since a transcendental number exists whose first maxInteger digits are 0

@WNG Languages have arbitrary precision. There is no maxinteger.

@WNG You can think of the input index as a string, not an integer, in languages that don't have arbitrarily large number types.

Python, 3 bytes
min

Try it online!
Takes a number string, outputs its smallest digit as a smallest character. For example, 254 gives 2. The decimal with these digits starts
0.0123456789011111111101222222220123333333012344444401234555550123456666012345678801234567

This is OEIS A054054.
Claim: This number c is transcendental
Proof:  Note that c is very sparse: almost all of its digits are zero. That's because large n, there's high probability n has a zero digit, giving a digit min of zero. Moreover, c has long runs of consecutive zeroes. We use an existing result that states this means c is transcendental.
Following this math.SE question, let Z(k) represent the position of the k'th nonzero digit of c, and let c_k be that nonzero digit, a whole number between 1 and 9. Then, we express the decimal expansion of c, but only taking the nonzero digits, as as the sum over k=1,2,3,... of c_k/10^Z(k).
We use the result of point 4 of this answer by George Lowther: that c is transcendental if there are infinitely many runs of zeroes that are at least a constant fraction of the number of digits so far. Formally, there must be an ε>0 so that Z(k+1)/Z(k) > 1+ε for infinitely many k. We'll use ε=1/9
For any number of digits d, take k with Z(k) = 99...99 with d nines.  Such a k exists because this digit in c is a 9, and so nonzero. Counting up from 99...99, these numbers all contain a zero digit, so it marks the start of a long run of zeroes in c. The next nonzero digit isn't until Z(k+1) = 1111...11 with d+1 ones. The ratio Z(k+1)/Z(k) slightly exceeds 1+1/9.
This satisfies the condition for every d, implying the result.

I would be quite excited to see the proof.

Is this allowed? min itself doesn't take any input and doesn't provide any output, something that seems to be a requirement by the question. Sure, it's the key function in the whole, but it doesn't do anything without the generator and print statement apparent in the 'Try it online'.

@Mast Yes, the problem is to output the n'th digit given n, not to generate the decimal. The test code is to show the sequence of digits. And an expression that evaluates to a function, including a function literal, is a valid function submission.

delightful :)))

Holy sh1t, this is clever!

Pyth, 1 byte
h

Input and output are strings. The function takes the first digit of the index. The resulting transcendental number looks like:
0.0123456789111111111122222222223 ...
This is transcendental because it is 1/9 plus a number which has stretches of zeroes of length at least a constant fraction of the number. Based on this math.stackexchange answer, that means that the number is transcendental.
There are stretches of zeroes are from digit 100 ... 000 to 199 ... 999, so ratio of Z(k+1) to Z(k) is 2 infinitely often.
Thus, the above number minus 1/9 is transcendental, and so the above number is transcendental.

Note that the question asked in the linked M.SE post does not apply to this number, but point 4 of the answer by George Lowther does.

Python 2, 19 bytes
lambda n:1>>(n&~-n)

The nth digit is 1 if n is a power of 2 and 0 otherwise.
Try it online!

I was going to answer this, but I found no proof of its transcendence. What makes you believe this number is transcendent? n&~-n>0 is shorter by the way.

@orlp All sufficiently sparse numbers are transcendental.

@orlp Fredholm's number

@orlp I'd have to ask the OP if Booleans are fine.

@Dennis I would prefer not.

@Dennis What booleans?

@Scrooble These Booleans.

@orlp You could submit for gcc/g++: -Df(n)=n&~-n>0

brainfuck, 2 bytes
,.

Similarly to some other answers, returns the first decimal digit and ignores the rest.

Jelly, 3 bytes
e!€

Uses Liouville's constant.
Try it online!

Retina, 4 bytes
1!`.

Returns the first digit of the input number. Because that port was so boring, here are some more ports:
O`.
1!`.

(8 bytes) Returns the minimum digit of the input number.
.+
$*
+`^(11)+$
$#1$*
^1$

(25 bytes) Returns 1 if the input number is a power of 2.
.+
$*_

$.`
+1`.(\d*)_
$1
1!`.

(30 bytes) Champernowne's constant.

Brachylog 2, 7 bytes
⟦₁c;?∋₎

Try it online!
Calculates digits of the Champernowne constant (possibly times a power of ten due to indexing issues, which clearly don't matter here). Basically, this just concatenates together integers, and then takes the nth digit.

Why do you need ⟦₁?

@LeakyNun: Because otherwise we'd start concatenating numbers with 0, and you can't do that because 0123 is not a number (it has a leading zero, which doesn't fit within Brachylog's concept of what a number is).

Python 2, 13 bytes
Input and output are strings.
lambda n:n[0]

The number's nth digit is the most significant digit of n when it is written in decimal.

You should include why this number is transcendental.

@orlp Looks like xnor's reference can easily be applied here too -- subtract 1/9 from the number and then Z(n+1) / Z(n) ~= 2 infinitely often (between 10^x and 2 * 10^x).

MATL, 7 bytes
4YA50<A

This uses the first of the two numbers given here divided by 3 (which maintains transcendence):

1.100110000000000110011...

Input is 1-based.
Try it online! Or see the first 20 decimals.
Explanation
4YA     % Convert to base 4 using chars '0', '1', '2', '3' as digits
50<A    % Are all digits less than '2'? Gives 0 (false) or 1 (true)

Python 2, 43 bytes
Champernowne's constant.
lambda n:"".join(`i`for i in range(n+1))[n]

Why do you need n+1?

@LeakyNun Because else I get indexing errors for n <= 1.

You can use 1-indexing.

@LeakyNun n <= 1.

I think you need to specify Python 2 for this one.

JavaScript, 51 bytes
This function computes nth digit of Champernowne's Constant. Add f= at the beginning and invoke like f(arg). Note that n is 1-indexed.
n=>[..."1".repeat(n)].map((c,i)=>c*++i).join``[n-1]

Explanation
This function takes in a single argument n. It, then, creates an n-characters long String of repetitive 1s. Then, it splits that String into an Array of 1s . After that, it iterates over every element of the Array and multiplies them with their index in the Array incremented by 1. Then, it joins the Array together over "" (empty String) to form a String. At last, it returns the nth element of the obtained String.
Note: The type of the returned value is always String.
Test Snippet

let f =

n=>[..."1".repeat(n)].map((c,i)=>c*++i).join``[n-1]

i.oninput = e => o.innerHTML = f(parseInt(e.target.value,10));
<input id=i>

APL (Dyalog), 3 bytes
2|⍴

Try it online! (the test suite generates a range of numbers from 1 to 10000, converts them to a string, and then applies the train 2|⍴ on them).
Takes the input number as a string and returns its length mod 2. So 123 => 3 mod 2 => 1.
The sequence starts off like so:
1  1  1  1  1  1  1  1  1  0  0  0  0  0  0  ...

so this can be generalised like so: 9 1s 90 0s 900 1s ...
Multiplying this number by 9 gives us a Liouville number, which is proven to be transcendental.

I don't think this is necessarily a Liouville number - it's not obvious to me that you can get n>10. It does fit the stronger theorem other people here have been using, though.

@ØrjanJohansen You can express it as 1 - 10^-9 + 10^-99 - 10^-999 + 10^-9999 - 10^-99999 + ..., so it is a Liouville number.

@LeakyNun The fraction of consecutive exponents is approximately 10, but to fit the definition on Wikipedia it needs to be unbounded - that's why the original Liouville's constant's 1-indices use a factorial, and not an exponential.

Haskell, 25 bytes 17 bytes
(!!)$concat$map show[1..]

Champernowne's Constant can be 0 or 1 indexed as C10*.01 is still transcendental.
Edit:
as per nimis comment you can use the list monad to reduce this to
(!!)$show=<<[1..]

=<< from the list monad is concat.map: (!!)$show=<<[1..].

JavaScript, 73 bytes
This is a program which computes the nth digit of the Liouville Constant, where n is the input number given by invoking the function g as g(arg) (and n is 1-indexed). Note that the newline in the code is necessary.
f=n=>n<1?1:n*f(n-1);g=(n,r=0)=>{for(i=0;i<=n;i++)if(f(i)==n)r=1
return r}

Explanation
The program consists of two functions, f and g. f is a recursive factorial-computing function, and g is the main function of the program. g assumes to have a single argument n. It defines a default argument r with a value of 0. It, then, iterates over all the Integers from 0 to n, and, in each iteration, checks whether the function f applied over i (the current index) equals n, i.e. whether n is a factorial of i. If that happens to be the case, r's value is set to 1. At the end of the function, r is returned.
Snippet for Testing

f=n=>n<1?1:n*f(n-1);g=(n,r=0)=>{for(i=0;i<=n;i++)if(f(i)==n)r=1
return r}

i.oninput = e => o.innerHTML = g(parseInt(e.target.value,10))
<input id=i>

Warning: Don't put a very large value in the Snippet's input box! Otherwise, your device may freeze!

Jelly, 1 byte
Ḣ

Try it online!
1st digit of quoted 0-indexed input.1
1See isaacg's answer for proof of validity.

Japt, 3 1+1= 2 1 byte
Another port of feersum's solution.
Takes input as a string.
g

Try it online

Explanation
   :Implicit input of string U
g  :The first character of the string

The input can be a string, so you can do g for 1 byte :)

The challenge doesn't make mention of string input, @obarakon, so I used integers in my JS ports and then, in turn, here.

Ah, gotcha. A lot of the other answers used string inputs. But you're right, the OP didn't mention it in the challenge.

Pyth, 7 5 4 bytes
@jkS

Try it online!
Uses Champernowne's constant.
Saved 2 3 bytes thanks to Leaky Nun.

you can use jk to replace sm\d`, I believe.

Can you use S instead of Uh?

I think they are functionally identical, so yes. I totally read through the docs >.>

They aren't functional identical. S starts with 1 and U starts with 0.

Why did you revert your edit? The resulting number is still transcendental.

Yeah, turns out I have to do that for my answer to be valid actually lol

@LeakyNun it's not the Champernowne constant though

But it's still transcendental, right? It is essentially a shifted Champernowne constant.

Yeah, it's transcendental, but using S is shorter anyway

Java 8, 18 bytes
Same as Dennis' answer for Python 2, the Fredholm number
n->(n&(n-1))>0?0:1

(n-1) can be ~-n or --n to save 2 bytes. Or you can have the exact same as Dennis' answer: n->1>>(n&~-n) or 1>>(n&--n).

Charcoal, 24 bytes (noncompeting)
ＮαＡＩＵＶN⟦ＵＧPi⁺α¹⟧β§β⁺α›α⁰

Try it online!
Note: As of post time, does not work for n where  n is a positive multiple of 14.
Explanation
Ｎα                             Input number to a
   Ａ                  β        Assign to b
     Ｉ                         Cast
       ＵＶN                    Evaluate variable N
            ⟦ＵＧPi⁺α¹⟧         With arguments GetVariable(Pi) and a+1
                        §β⁺α›α⁰ Print b[a+(a>0)]

GetVariable(Pi)? So, there's no π predefined variable?

@Neil Not yet, and I'm not intending to make π equal to pi because this is an ASCII-art oriented language, not a math-oriented one

05AB1E, 3 1 byte
EDIT: Using the proof from the other answers, returns the first digit of input
¬

1-indexed for π (only up to 100000 digits)
žs¤

How it works
žs  # Implicit input. Gets n digits of pi (including 3 before decimal)
  ¤ # Get last digit

Or, if you prefer e (still 1-indexed) (only up to 10000 digits)
žt¤

Try it online!

TI-BASIC, 16 bytes
Basically tests if the input N (1-indexed) is a triangular number.  This is the same as returning the Nth digit of 0.1010010001…, which is proven to be transcendental.  The sequence of digits is OEIS A010054.
Input N
int(√(2N
2N=Ans(Ans+1

Duocentehexaquinquagesimal, 1 byte
Ties isaacg's Pyth answer, Erik the Outgolfer's Jelly answer, Neil A.'s 05AB1E answer, and Shaggy's Japt answer for #1.
.

Try it online!

Pyt, 5 bytes
Đř!∈Ɩ

Try it online!
Liouville Constant
Đ           implicit input (n); duplicate
 ř!         get [1!,2!,...,n!]
   ∈        is n in that list?
    Ɩ       coerce to integer; implicit print

Regex (ECMAScript), 13 bytes
((xx|)x*)\1+$

Try it online!
Takes its input in unary, as a string of x characters whose length represents the number. The output is returned as the length of capture group \2.
Returns the \$n\$th digit of \$0.00020202220202220202220222220202222202220202220222220...\$, where the \$n\$th digit is \$2\$ if \$n\$ is a composite number, and \$0\$ otherwise.
           # tail = N = input number
((xx|)x*)  # \1 = the largest proper divisor of N;
           # \2 = 2 if \1 >= 2, or 0 otherwise;
           # tail -= \1
\1+$       # Assert that \1 divides tail

If the return value of \2 is defined to be \$0\$ when it is unset, then this can be reduced to 12 bytes, with \$0.00010101110101110101110111110101111101110101110111110...\$ as the transcendental number:
(x?(x)*)\1+$

Try it online!
Regex (ECMAScript), 14 bytes
((x*)(?=\2)x)*

Try it online!
The output of this one is also returned as the length of capture group \2.
Returns the \$n\$th digit of \$0.01001100001111000000001111111100000000000000001...\$ (with 1-indexing). The \$n\$th digit of this transcendental number is the 2nd digit of the binary expansion of \$n+1\$, OEIS A079944.
                # tail = N = input number
(
    (x*)(?=\2)  # \2 = floor(tail / 2); tail -= \2
    x           # tail -= 1
)*              # Iterate the above as many times as possible

Fourier, 16 bytes
I~NL~S10PS~XN/Xo

Try it online!
As other answers have done, outputs the first digit of the input.
An explanation of the code:
N = User Input
S = log(N)
X = 10 ^ S
Print (N/X)

JavaScript (ES6)
Just a few ports of some other solutions

feersum's Python solution, 12 bytes
n=>(""+n)[0]

f=
n=>(""+n)[0]
o.innerText=f(i.value=1)
i.oninput=_=>o.innerText=f(+i.value)
<input id=i type=number>

Dennis' Python solution, 13 bytes
n=>1>>(n&--n)

f=
n=>1>>(n&--n)
o.innerText=f(i.value=1)
i.oninput=_=>o.innerText=f(+i.value)
<input id=i type=number>

xnor's Python solution, 20 bytes
n=>Math.min(...""+n)

Brain-Flak, 6 + 3 ( -c) = 9 bytes
({}<>)

Try it online!
1st digit of 0-index string input (hence the -c flag).

C#, 13 bytes
n=>(n+"")[0];

From feersum's solution. Almost same solution than the js port.
Try it online

J, 2 Bytes
The same solution everyone else is using:
{.

Returns the first digit of n. IO is on strings
Liouville's Constant, 9 Bytes
(=<.)!inv

Returns 1 if input is the factorial of an integer.
Pi, 13 Bytes
{:":<.@o.10x^

The last non-decimal digit of pi times 10^n.

Jelly, 2 bytes
LḂ

Try it online!
Take the length of the input number modulo 2. Equivalent to this APL answer.

Dreaderef, 5 bytes
7 3 6

Try it online!
Returns the first digit of the input.

Momema, 5 bytes
-9*-9

Try it online!
Returns the first digit of the input.

Shakespeare Programming Language, 76 bytes
,.Ajax,.Ford,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Open mind.Speak thy.

Try it online!

You've got an extra character there

Whoops, that must have been a leftover from something else. Thanks for spotting it.

Thunno 2 M, 0 bytes

Try it online!
or see the start of the number
Port of xnor's Python answer. The M flag takes the minimum of the top of stack.


text:
Squaring Off (fit to smallest possible square)
Intro
More complex than A square of text since this requires padding and input has unknown data type.
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. This is a language agnostic code-golf edition of this year's tenth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.
Problem
Write a program/function that will reshape a given string or numeric list into the smallest square that will contain all the elements of the input, padding with additional elements if necessary. The pad element should be the default fill element for the given data type, or any one element of your choice. The elements of the square should be in such order that flattening it will give the original order of input data (with trailing padding elements, if any).
Test cases
[1,2,3,4] →
[[1,2],
 [3,4]]

[1,2,3,4,5] →
[[1,2,3],
 [4,5,0],
 [0,0,0]]

"Dyalog APL" →
[["Dyal"],       [["D","y","a","l"],
 ["og A"],   or   ["o","g"," ","A"],
 ["PL  "],        ["P","L"," "," "],
 ["    "]]        [" "," "," "," "]]

[100] →
[[100]]

[] →
your language's closest equivalent to an empty matrix, e.g. [] or [[]]

Do we have to be able to handle both strings and arrays as input or only one? Can output be a string containing newlines? Should the output for [100] not be [[1,0],[0,0]]? If not, is [[100,1],[2,0]] the expected output for input [100,1,2]?

@Shaggy Yes, numeric lists and strings/lists of characters (whatever your language uses). Output per default rules. "100" gives [["1",0"],["0"," "]] (or whatever the fill element is. Yes, [100,1,2] → [[100,1],[2,0]].

Hi Adám, I have three questions... 1. What does "The pad element should be the default fill element for the given data type, or any one element of your choice." mean, - is it restricted or free (it seems contradictory or redundant)? 2. What should the output be for an input like [1,2,3,4,'O'], or is it guaranteed not to occur? 3. Is the required order after flattening requirement ignoring the pad elements (e.g. could an input of [1,2,3,4,5] yield [[0,0,0],[0,1,2],[3,4,5]] or even [[0,1,0],[2,0,3],[0,4,5]])?

@JonathanAllan 1. Some languages will automatically pad. Whatever they pad with is fine. If your's don't, choose an element. 2. string or numeric list. 3. The padding elements must be trailing.

MATL, 12 9 bytes
Saved three bytes thanks to Luis. he instead of UGwewe, but adding a t in the beginning.
tnX^Xkthe

Try it online!
This returns the results, but transposed compared to the result in OPs post (which is OK).
Explanation:
This works the same way for both numeric and string input, as MATL treats them the same way.
Assume the input is 'Dyalog APL'
                % Implicit: Take string or numeric array as input
                % Stack: 'Dyalog APL'
t               % Duplicate
                % Stack: 'Dyalog APL'
                %        'Dyalog APL'
 n              % Number of elements in last element.
                % Stack: 'Dyalog APL'
                %        10
  X^            % Take the square root of the number of elements
                % Stack: 'Dyalog APL'
                % Stack: 3.16...
    Xk          % Ceil last number
                % Stack: 'Dyalog APL'
                %        4
      t         % Duplicate element
                % Stack: 'Dyalog APL'
                %        4
                %        4
       h        % Concatenate the last to elements horizontally
                % Stack: 'Dyalog APL'
                %        4  4
        e       % reshape into 4 rows, and 4 columns. Pads the input with zeros or spaces
                % if necessary.
                % Stack: (Note that there's a trailing column not shown below)
                %        DoP
                %        ygL
                %        a
                %        lA

This outputs nothing for empty input, which happens to be way MATL outputs empty matrices / strings.

What does it output for empty input?

This outputs nothing for empty input, which happens to be way MATL outputs empty matrices / strings.

I think tnX^Xkt3$e does the job too

Or, better, tnX^Xkthe

@LuisMendo I looked for a way to pass three inputs to reshape and didn't notice the very obvious: $: Specified inputs. And I didn't know you could pass the dimensions as a vector. I knew there had to be a way without having to go through two reshapes. Thanks! :)

JavaScript (ES7), 70 bytes
a=>[...Array((a.length-1)**.5+1|0)].map((_,$,b)=>b.map(_=>a[i++]),i=0)

Returns [] for an empty array/string. Uses undefined as the fill value. For ES6 replace (...)**.5 with Math.sqrt(...) (+5 bytes).

R, 91 bytes
function(x){if(!is.double(x))x=strsplit(x,'')[[1]];matrix(x,r<-ceiling(sqrt(length(x))),r)}

By default, R pads matrices by recycling elements of the input vector and encodes matrices in column-major order. Will return a 0x0 matrix for an input of double(0) (an empty double array) or ''.
The first line (the if statement) splits a string into a vector of its constituent characters; if I can take that vector in instead, that line can be removed.
Try it online!

Brachylog, 10 bytes
;Ac~c.\l~l

Try it online!
Takes strings as lists of characters (the asker has confirmed that this is OK).
This is very inefficient on longer inputs, because it brute-forces all possible reshapings of the input, trying progressively more padding, until it finds one that happens to be square.
Explanation
;Ac~c.\l~l
;Ac         Append {the shortest list possible}.
   ~c       Split into a list of lists
      \l    such that it's rectangular, and the number of columns
     .  ~l  equals the number of rows

The padding elements used are Prolog's "any value" value _, which is normally rendered as _G plus some random digits on output (to make it possible for the Prolog engine to express relationships between those general-purpose values).
Incidentally, there was a bug fix to SWI-Prolog only a few days ago that makes this program possible (although it still appears to work on older, buggy versions); the "it's rectangular" constraint implied by \ was previously broken, but it got fixed in time for the challenge.

Can nowadays be written with 5 bytes as ~s~cṁ. TIO.

J, 18 bytes
,~@>.@%:@#$]{.~#*#

Try it online!

Python 2, 105 bytes
def f(a):b=len(a)and int((len(a)-1)**.5)+1;return[(a+[[0],' ']["'"in`a`]*b*b)[b*i:][:b]for i in range(b)]

Try it online!

What does it output for empty input?

@Adám The correct answer.

You can now simplify by using just one fill element.

Haskell, 87 bytes
import Data.Lists
f x|c:_<-[n|n<-[1..],n^2>=length x]=take c$chunksOf c$x++(error[]<$x)

Try it online!
The fill element is error[], the shortest value that is of any type (undefined is a little bit longer).
Notes on the TIO link:

you cannot print error, so I concatenate matrices with fill elements back to a list and print its length
TIO doesn't have Data.Lists, only Data.List.Split so it shows 5 more bytes.

How it works: calculate the length c of the c-by-c matrix. Take the first c elements of the list of chunks of length c of the input list followed by a list of fill elements which has the same length as the input list. E.g. :
[1,2,3,4,5]                                        -- Input
[1,2,3,4,5,error,error,error,error,error]          -- fill elements appended
[[1,2,3],[4,5,error],[error,error,error],[error]]  -- chunks of length 3
[[1,2,3],[4,5,error],[error,error,error]]          -- take 3

PHP, 139 Bytes
Output string as 2D char array
works with [] as empty array

$r=[];for($z=ceil(sqrt($n=(($b=is_array($g=$_GET[0]))?count:strlen)($g)));$c<$z*$z;$c++)$r[$c/$z^0][]=$c<$n?$g[+$c]:($b?0:" ");print_r($r);

Try it online!
PHP, 143 Bytes
needs [[]] as empty array
Output string as 1D string array

$z=ceil(sqrt((($b=is_array($g=$_GET[0]))?count:strlen)($g)));print_r($b?array_chunk(array_pad($g,$z**2,0),$z):str_split(str_pad($g,$z**2),$z));

Try it online!

Jelly, 13 bytes
L½Ċẋ€`
0ṁ;@ṁÇ

A monadic link taking a flat list and returning a list of lists.
Test suite at Try it online!
How?
Appends as many zeros (the padding element) as there are elements in the input and then reshapes to a square, dropping any zeros excess to requirements in the process.
L½Ċẋ€` - Link 1, create a square list of lists of the required size: list a
L      - length of a
 ½     - square root
  Ċ    - ceiling (the required side length, S)
     ` - repeat argument (S) for the dyadic operation:
   ẋ€  -   repeat list for €ach (implicit range [1,2,...,S] on both its left and right)
       -   note: if the input list has no length then an empty list is yielded here

0ṁ;@ṁÇ - Main link: list a (strings are lists of characters in Jelly)
0      - literal zero
 ṁ     - mould like a (makes a list of zeros of the same length as the flat list a)
  ;@   - concatenate a with that
     Ç - call the last link (1) as a monad with argument a
    ṁ  - mould the (possibly oversized) flat array with extra zeros like the square array

Bash, 91 77 69 67 bytes
L=`dc -e${#1}\ 1-v1+p`
[ -z "$1"]||printf %-$[$L*$L]s "$1"|fold -$L

Try it online!
Formats text, pads with spaces. Outputs nothing to stdout on empty input.
Update: stole some tricks from answers here.

Dyalog APL, 20 19 bytes
{(,⍨⍴⍵↑⍨×⍨)⌈.5*⍨≢⍵}

-1 Byte thanks to @Adám!
Try it online!

Save one: {(,⍨⍴⍵↑⍨×⍨)⌈.5*⍨≢⍵}

This was my answer for the student competition, it was naturally golfy so I put it here, and thanks for the byte!

source: Stack Exchange

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

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

sort: votes


text:
Tell me, how many squares are there?
Given a non-empty 2D array consisting of 0 and 1, find the number of squares whose 4 corners are all 1. The squares do not need to be "upright". All the rows are guaranteed to have the same length.
Reasonable input/output methods are allowed.
Testcases:
0001000
1000000
0000000
0000100
0100000

This returns 1.
10101
00000
10100
00000
10001

This returns 2.
1111
1111
1111
1111

This returns 20.
This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Another interpretation, if I'm understanding the intent: 4 1s on a square, such that each 1 is equidistant along the perimeter from its two neighbors.

@feersum The latter condition is true for every square, isn't it?

JavaScript (ES6), 127 124 119 bytes
Saved 3 bytes thanks to nderscore
m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

How?
This function iterates on all pairs of cells (x, y), (X, Y) of the input matrix m such that:

m[ x, y ] = m[ X, Y ] = 1
x < X
y ≤ Y

Each matching pair describes the coordinates of a potential edge of a square. The inequations guarantee that each edge is tested only once.
We use the vector [ dx, dy ] = [ X - x, Y - y ] rotated 90° clockwise to test the cells located at [ x - dy, y + dx ] and [ X - dy, Y + dx ]. If they both contain a 1, we've found a valid square.

Test cases

let f =

m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

console.log(f([
  [0,0,0,1,0,0,0],
  [1,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,1,0,0],
  [0,1,0,0,0,0,0]
]));

console.log(f([
  [1,0,1,0,1],
  [0,0,0,0,0],
  [1,0,1,0,0],
  [0,0,0,0,0],
  [1,0,0,0,1]
]));

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

-2 bytes: g=(a,b)=>(m[b+X-x]||0)[a-Y+y]
-1 byte: use |n instead of &&n

MATL, 20 bytes
&fJ*+4XN!"@&-|un3=vs

Input is a matrix.
Try it online!
How it works
This finds all coordinates of nonzero entries in the input grid, and represents them as complex numbers, such that row and column indices correspond to real and imaginary parts respectively.
The code then generates an array of all combinations (order doesn't matter) of these numbers taken 4 at a time. Each combination represents a candidate square. For each combination, the 4×4 matrix of pair-wise absolute differences (i.e. distances in the complex plane) is computed. This is a symmetric matrix with zeros along its main diagonal. The current combination forms a square if and only if the matrix contains exactly 3 distinct values (these will be the square side, the square diagonal, and zero):

On the other hand, for example, a non-square rectangle would give rise to 4 distinct values (two sides, one diagonal value, and zero);

and a general quadrilateral can have up to 7 values (four sides, two diagonals, and zero):

&f      % Input (implicit). Push vectors of row and column indices of nonzero entries
J*      % Multiply by imaginary unit
+       % Add the two vectors. Gives a vector of complex coordinates
4XN     % Matrix of combinations of these complex numbers, taken 4 at a time. Each
        % row is a combination
!       % Transpose
"       % For each column
  @     %   Push current column: candidate set of four points
  &-    %   All pair-wise differences
  |     %   Absolute value
  u     %   Unique entries
  n3=   %   Does the number of elements equal 3? Gives true (1) or false (0)
  vs    %   Concatenate vertically with previous accumulated result, and sum
        % End (implicit). Display (implicit)

How does it work?

@LeakyNun Explanation added

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


text:
Further golfing this C# code from Scramble words while preserving their outlines

I'll start off by saying I checked and checked again that this question should be on topic.
I will also clearly state that this is a tips question about further golfing a certain set of code not a challenge.

I recently answered the following challenge:  Scramble words while preserving their outlines:

It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules:

Scrambling must be (pseudo) random.
A word is a sequence of the Latin characters, A through Z.
Only initial letters will ever be uppercase.
The first and last letters must stay untouched.
When scrambling, only letters within one of the following groups may exchange places:

acemnorsuvwxz
bdfhkl
gpqy
it
j (stays in place)

My answer is in C# and coming in, currently, at 394 bytes:
namespace System{using Text.RegularExpressions;using Linq;s=>Regex.Replace(s,@"[A-Za-z](([acemnorsu-xz])|([bdfhkl])|([gpqy])|([it]))*?[a-z]?\b",m=>{var a=m.Value.ToCharArray();for(int i=1,j;++i<6;){var c=m.Groups[i].Captures;var n=c.Cast<Capture>().Select(p=>p.Index-m.Index).ToList();foreach(Capture p in c){a[j=n[new Random().Next(n.Count)]]=p.Value[0];n.Remove(j);}}return new string(a);});}

I think there's room for golfing in the Linq statement and foreach loop at least.
Can this code be further golfed down?

Off the bat, (i|t) is shorter than ([it]). And if you order your character classes differently, you can probably replace the really long one with [a-z] because all the other letters will have already been covered by earlier groups. I'm also not sure your code works correctly for words containing j. As far as I can tell those words wouldn't be matched (instead of just leaving the j untouched).

@MartinEnder It wouldn't have handled the j correctly, good spot on that and with the re-ordering the regex is a bit shorter so that helps too! I'm not the best with regex if you hadn't realised...

Since the input is limited to ASCII, you can also use \p{L} for [A-Za-z].

@MartinEnder I'd seen that suggestion on other answers and forgotten about it! Regex is now \p{L}(([bdfhkl])|([gpqy])|(i|t)|(j)|([a-z]))*?[a-z]?\b

If you put the first group before the last one, it can be shortened to [bdf-l], because gij have already been taken care of.

@MartinEnder All that has saved 10 bytes so far: \p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b. Can you add an answer with the improvements so far?

As I am using linq in my program, I can change ToCharArray to ToArray to save 4 bytes.
I can also change the namespace around to be either System.Linq or System.Text.RegularExpressions to save a further 6 bytes by removing the using for it:
namespace System.Text.RegularExpressions

As @MartinEnder♦ points out in the comments I can save 10 bytes by re-ordering the groups in the regex and changing [A-Za-z] to \p{L}:
\p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b

Oh god that second person really messes with me. Talking about yourself as you? Do you mind if i change it?

@cairdcoinheringaahing Can if you want yeah. It's because I've done a few on SO where it makes more sense to use second person in a self answer. I don't suppose it matters either way though.


text:
KOTH: Hit and Sunk
Introduction
For my 5th KOTH, I present to you a challenge based on the well-known game Battleship with a few twists. You'll only command one ship, whose type you'll be able to select between the 5 "traditionnal" classes, but you'll be able to undertake multiple actions each turn, including moving! This is played as a FFA (Free For All) and your goal will be to be the last ship standing.
Principle
The game is turn-based. At the start of the game, you'll have to choose the class of your ship. Then each turn, players will be able to execute several actions depending on their ship.
The game takes place on a 2D grid (X, Y) whose side is defined this way :
X = 30 + numberOfPlayer
Y = 30 + numberOfPlayer
The starting position of each ship is random.
Play order is randomized each turn, and you won't know your position in the "queue" nor the number of players. The game lasts for 100 turns or until there's only one ship left alive.
Each time you hit an enemy ship or get hit, you'll earn or lose points. The player with the highest score wins. A bounty will be awarded to the winner (value depending on the number of participants).
The controller provides you with input via command arguments, and your program has to output via stdout.
Syntax
First Turn
Your program will be called once without any argument. You'll have to ouput an integer between 1 and 5 (inclusive) to select your ship :
1 : Destroyer [length: 2, moves/turn: 3, shots/turn: 1, range: 9, mines: 4]
Skill : Free ship rotations (no cooldown)
2 : Submarine [length: 3, moves/turn: 2, shots/turn: 1, range: 5, mines: 4]
Skill : Can Plunge/Surface (see outputs). While underwater, you can only use "Movement" actions and can be seen only with a scan. You can't be hit by a shot, but can take damage from mines.
3 : Cruiser [length: 3, moves/turn: 1, shots/turn: 2, range: 9, mines: 2]
Skill : Can Repair (see outputs)
4 : Battleship [length: 4, moves/turn: 1, shots/turn: 3, range: 7, mines: 1]
Skill : Can Shield (see outputs)
5 : Carrier [length: 5, moves/turn: 1, shots/turn: 1, range: 7, mines: 3]
Skill : Shots deal AOE (Area Of Effect) damage to target (1 range splash damage). If the target is hit with the shot, up to 2 cells of this ship will also be damaged.
Turns
Input
Each time your program is called, it will receive arguments in this format:
Round;YourPlayerId;X,Y,Direction;Hull;Moves,Shots,Mines,Cooldown;Hits,Sunken,Damage;Underwater,Shield,Scan;Map
Rounds are 1-indexed.
Example input
1;8;1,12,0;111;1,2,2,0;0,0,0;0,0,0;UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.O.....UUUUUUUUXXXX.O.....UUUUUUUUXXXX.O.....UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUXXXX.......UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU

Here, it's the 1st round, you're player 8.
Your ship is positioned on (X = 1, Y = 12) and your direction is toward the top (0 = Top, 1 = Right, 2 = Bottom, 3 = Left).
Your hull is not damaged (your ship has a length of 3, and each bit is true [1 = OK, 0 = Damaged]).
You can move 1 time, shoot 2 times, have 2 mines left and your "skill" is available (cooldown = 0).
You didn't hit anything, nor have sunken any ship and you didn't get hit either.
You're not underwater, your shields (if any) are not activated and your scan isn't either.
More on the map later...
Output
You have to output a String describing what actions you'll execute this turn. The order of the characters in your output String will define the orders of the actions. You can output the same actions multiple times if it doesn't exceed the limits of your ship. If one or multiple actions is invalid, each one will separately be considered as W. Here's the list of available actions :
M : Move 1 cell in the direction you're facing (consume 1 move)
B : Back 1 cell from the direction you're facing (consume 1 move)
C : Rotate your ship clockwise (consume 1 move / free for Destroyers)
K : Rotate your ship counterclockwise (consume 1 move / free for Destroyers)
A : Ram your ship in the direction you're facing (works only if another ship is occupying the cell in the direction you're facing / doesn't move your ship / consume all moves)
F : Fire 1 shot to a cell in range (consume 1 shot). Must be followed by the targetted cell in this format ([+-]X[+-])Y / example : F+2-3)
N : Place 1 mine to a cell adjacent to your ship (consume all shots and 1 mine). Must be followed by the targetted cell in this format ([+-]X[+-])Y / example : N+0+1)
S : Activate your scan for the next turn (consume all shots)
R : Repair the damaged hull the closest to the "head" of your ship (consume all shots, cooldown = 3 turns / Cruiser only)
P : Plunge/Surface (consume all shots, cooldown = 3 turns, max duration = 5 turns / Submarine only)
D : Activate your shield preventing the next damage during your next turn (consume all shots, cooldown = 3 / Battleship only)
W : Wait (does nothing)
Clarification: "Consume all moves/shots" means you can only use this action if you have not used any of your moves/shots before during this turn.
Example output
MF+9-8CM : Moves 1 cell, then fires on the cell whose relative position to the "head" of your ship is (targetX = X + 9, targetY = Y - 8), turns clockwise and finally moves 1 cell again.
Gameplay
The Grid
Here's an example grid (33 x 13) where 3 players are placed :
███████████████████████████████████
█                                 █
█       00                        █
█   2                             █
█   2                             █
█   2                             █
█                                 █
█       11111                     █
█        M                        █
█                                 █
█                                 █
█                                 █
█                                 █
█                                 █
███████████████████████████████████

As we can see, there's also a Mine M right next to the player 1.
Let's take player 2 to understand positioning and direction :
Player 2's position is X = 3, Y = 4, Direction = 3. Since its direction is "Bottom", the rest of his "ship cells" are positioned "over" its "head" (X = 3, Y = 3) & (X = 3, Y = 2)
Player's map
The last argument each players receive is their "own" map. By default a ship detects everything in a range of 5 cells, but it can activate a Scan to increase this range to 9.
The argument is always 361 (19 x 19) characters long. It represents the square centered around the "head" of your ship, where each character corresponds to an element defined this way :
. : Empty cell
O : Your ship
M : Mines
X : Wall (cells out of the map)
U : Unknown (will be revealed by a scan)
A : Enemy ship undamaged cell
B : Enemy ship damaged cell
C : Enemy ship underwater undamaged cell (only seen with a scan)
D : Enemy ship underwater damaged cell (only seen with a scan)
W : Wreckage (dead ship)
The string is composed of 19 characters of the first line, followed by 19 charcters of the second lines ... until the 19th line.
Lets take a look at what player 2 receives with and without a scan (line breaks for better understanding, but not send to players) :
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXX.............
XXXXXX.......AA....
XXXXXX...O.........
XXXXXX...O.........
XXXXXX...O.........
XXXXXX.............
XXXXXX.......AAAAA.
XXXXXX........M....
XXXXXX.............
XXXXXX.............
XXXXXX.............
XXXXXX.............
XXXXXX.............
XXXXXXXXXXXXXXXXXXX

UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUXXXXXXXXXXXUUUU
UUUUXX.........UUUU
UUUUXX.......AAUUUU
UUUUXX...O.....UUUU
UUUUXX...O.....UUUU
UUUUXX...O.....UUUU
UUUUXX.........UUUU
UUUUXX.......AAUUUU
UUUUXX........MUUUU
UUUUXX.........UUUU
UUUUXX.........UUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUU

Mines
The mines are triggered when a ship moves to a cell occupied by a mine or when a shot is fired on the mine. Mines can't be triggered with the action "Ram".
Mines deal AOE damage (1 range splash damage) to everyone, even to the person who placed the mine. Mines can trigger "chain" explosions if another mine is in the radius of the explosion.
Rotations
The rotations are central symmetries centered on the ship's "head". Rotations will only trigger a mine if it is placed on the "destination position" (you won't trigger mines in an arc.
Area of effect
1 range splash damage (for mines and Carrier's shots) is defined by a 3x3 (9 cells) square centered on the initial shot/explosion (x, y). It hits those coordinates : [x - 1; y - 1],[x - 1; y],[x - 1; y + 1],[x; y - 1],[x; y],[x; y + 1],[x + 1; y - 1],[x + 1; y],[x + 1; y + 1]
Scoring
The scoring is defined by this formula :
Score = Hits + (Sunken x 5) - Damage taken - (Alive ? 0 : 10)
where :
hits : number of hits on enemy ship, either by Ram, Shot or Mine explosion (1 hit by enemy ship cell damaged, including chain explosions)
sunken : number of "last hit" on an enemy ship which caused it to sink
damage : number of hits received (not decreased by Repair, but prevented by Shield)
alive : checks wether your ship is alive at the end (at least 1 hull cell undamaged)
Controller
You can find the controller on GitHub. It also contains two samplebots, written in Java. To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.
To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.
Rules

Bots should not be written to beat or support specific other bots.
Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.
Your submission has 1 second to respond.
Provide commands to compile and run your submissions.
You can write multiple submissions

Supported Languages
I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.
As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

Interesting KotH, I just have a few questions : can we write multiple submissions (one for each type of ship for instance)? When you're talking about AoE, it's a square around the position right (it hits [x+1;y+1])?

@Katenkyo Yes, you can write multiple submissions. Yes, it hits 9 cells : [x - 1; y - 1],[x - 1; y],[x - 1; y + 1],[x; y - 1],[x; y],[x; y + 1],[x + 1; y - 1],[x + 1; y],[x + 1; y + 1]

so, does the submarine automatically surface? on which turn?

also are turns taken simultaneously?

also what is useful about the ram ability? (why not just shoot?)

@DestructibleLemon The submarines auto-surfaces after 5 turns (the "max duration" of its ability). Turns are taken sequentially and play ordered is randomized each turn. Ram is not useful ATM, but will be modified to consume all moves instead of all shots.

does consume all moves mean all remaining moves or you can only use it if you have used no moves? also shield seems op kind of? can't you just shield continuously?

@DestructibleLemon "Consume all" means you can only use if you have used none (i'll clarify in question). Shield works only for 1 attack during the next turn and has a 3 turn cooldown.

RandomBot
This is an example bot. It chooses a ship, an action and a target cell (if needed) randomly.
import java.util.Random;

public class RandomBot {

    int round;
    int playerID;

    public static void main(String[] args) {

        if (args.length == 0) {
            Random random = new Random();
            int ship = random.nextInt(5);
            String[] ships = { "1", "2", "3", "4", "5" };
            System.out.println(ships[ship]);
        } else {
            new RandomBot().play(args[0].split(";"));
        }
    }

    private void play(String[] args) {

        round = Integer.parseInt(args[0]);
        playerID = Integer.parseInt(args[1]);

        String[] actions = { "M", "B", "C", "K", "F", "S", "N", "A" };
        Random random = new Random();
        int action = random.nextInt(8);

        int rangeX = random.nextInt(5);
        int rangeY = random.nextInt(5);
        int mineX = random.nextInt(1);
        int mineY = random.nextInt(1);

        String signX = random.nextInt(1) == 1 ? "+" : "-";
        String signY = random.nextInt(1) == 1 ? "+" : "-";

        System.out.println(actions[action] + (action == 4 ? signX + rangeX + signY + rangeY : "") + (action == 6 ? signX + mineX + signY + mineY : ""));
    }

}

PassiveBot
This is an example bot. It does nothing.
public class PassiveBot {

    int round;
    int playerID;

    public static void main(String[] args) {

        if (args.length == 0) {
            System.out.println("5");
        } else {
            new PassiveBot().play(args[0].split(";"));
        }
    }

    private void play(String[] args) {

        round = Integer.parseInt(args[0]);
        playerID = Integer.parseInt(args[1]);

        System.out.println("W");
    }

}

PeaceMaker, Python 2 (Battleship)
PeaceMaker shoots 3 times on the nearest enemies (spiral distance) and moves back and forth in a line while staying at least 2 cells away from mines.
from os import sys

def reversedSpiralOrder(length):

    #Initialize our four indexes
    top = 0
    down = length - 1
    left = 0
    right = length - 1
    result = ""

    while 1:

        # Print top row
        for j in range(left, right + 1):
            result += str(top * length + j) + ";"
        top += 1
        if top > down or left > right:
            break

        # Print the rightmost column
        for i in range(top, down + 1):
            result += str(i * length + right) + ";"
        right -= 1
        if top > down or left > right:
            break

        # Print the bottom row
        for j in range(right, left + 1, -1):
            result += str(down * length + j) + ";"
        down -= 1
        if top > down or left > right:
            break

        # Print the leftmost column
        for i in range(down, top + 1, -1):
            result += str(i * length + left) + ";"
        left += 1
        if top > down or left > right:
            break

    result = result.split(";")
    del result[-1]
    return result[::-1]

def canMove(x, y, direction, hull, map):

    # M = 1, B = 2
    moves = 0

    if direction == 0:
        y1 = -1
        y2 = -2
        hx1 = hx2 = x1 = x2 = 0
        hy1 = -y1 + hull
        hy2 = -y2 + hull
    elif direction == 1:
        x1 = 1
        x2 = 2
        hy1 = hy2 = y1 = y2 = 0
        hx1 = -x1 - hull
        hx2 = -x2 - hull
    elif direction == 2:
        y1 = 1
        y2 = 2
        hx1 = hx2 = x1 = x2 = 0
        hy1 = -y1 - hull
        hy2 = -y2 - hull
    elif direction == 3:
        x1 = -1
        x2 = -2
        hy1 = hy2 = y1 = y2 = 0
        hx1 = -x1 + hull
        hx2 = -x2 + hull

    if map[y + y1][x + x1] == "." and map[y + y2][x + x2] != "M":
        moves += 1

    if map[y + hy1][x + hx1] == "." and map[y + hy2][x + hx2] != "M":
        moves += 2

    return moves

if len(sys.argv) <= 1:
    f = open("PeaceMaker.txt","w")
    f.write("")
    print "4"
else:
    arguments = sys.argv[1].split(";")
    sight = 19

    round = int(arguments[0])
    playerID = int(arguments[1])
    x = int(arguments[2].split(",")[0])
    y = int(arguments[2].split(",")[1])
    direction = int(arguments[2].split(",")[2])
    hull = arguments[3]
    moves = int(arguments[4].split(",")[0])
    shots = int(arguments[4].split(",")[1])
    mines = int(arguments[4].split(",")[2])
    cooldown = int(arguments[4].split(",")[3])
    hits = int(arguments[5].split(",")[0])
    kills = int(arguments[5].split(",")[0])
    taken = int(arguments[5].split(",")[0])
    underwater = int(arguments[6].split(",")[0])
    shield = int(arguments[6].split(",")[1])
    scan = int(arguments[6].split(",")[2])
    map = [[list(arguments[7])[j * sight + i] for i in xrange(sight)] for j in xrange(sight)]

    initialShots = shots

    priorities = reversedSpiralOrder(sight)

    actions = ""
    sighted = 0
    for priority in priorities:
        pX = int(priority) % sight
        pY = int(priority) / sight

        if map[pY][pX] == "A":
            sighted += 1
            if shots > 0:
                shots -= 1
                actions += "F" + ("+" if pX - 9 >= 0 else "") + str(pX - 9)  + ("+" if pY - 9 >= 0 else "") + str(pY - 9)

    if shots == initialShots and sighted > 0:
        actions += "D"
    elif shots == initialShots and sighted <= 0:
        actions += "S"
    else:
        actions += ""

    f = open("PeaceMaker.txt","r")
    fC = f.read(1)
    lastDirection = int("1" if fC == "" else fC)

    y = 9
    x = 9

    if lastDirection == 1:
        if canMove(x, y, direction, len(hull), map) == 1 or canMove(x, y, direction, len(hull), map) == 3:
            actions += "M"
        elif canMove(x, y, direction, len(hull), map) == 2:
            actions += "B"
            lastDirection = 0
    elif lastDirection == 0:
        if canMove(x, y, direction, len(hull), map) == 2 or canMove(x, y, direction, len(hull), map) == 3:
            actions += "B"
        elif canMove(x, y, direction, len(hull), map) == 1:
            actions += "M"
            lastDirection = 1

    f = open("PeaceMaker.txt","w")
    f.write(str(lastDirection))

    print actions

'PeaceMaker shoots'. You lost me there.


text:
Mow a Rectangular Lawn
A lawn is defined as a rectangular field with of one character surrounded by two layers of visible whitespace. This means two lines above and twos lines below, and a two space padding on the left (the right has visible whitespace, so you do not need to include it).

  |||||
  |||||
  |||||

A mowed lawn is a similar structure, except that the main character is a shortened version of the first character.

  .....
  .....
  .....

A mower is two different characters, different than the two lawn characters. Here is an example, with = as the back of the mower and o as the front:
=o

A mower will move around the lawn vertically, and can also rotate on its front. The above mower may look like any of the below during some point in the animation:
=o

o=

o
=

=
o

The mower can start on any set of the below positions on the below lawn. Mowers with o would drive around the lawn clockwise. Mowers with 0 would drive around the lawn counterclockwise.
  =   =
  0   o
=o|||||0=
  |||||
=0|||||o=
  o   0
  =   =

The animation starts at second 0. Each second, the mower moves forward one space, and cut the grass on its front. When the mower vacates a spot, it appears cut. When the mower front reaches the last uncut item on a line (and there is still uncut grass), the mower back rotates once so as to continue the current mow (staying in clockwise/counterclockwise based on original position) When the mower is finished, it continues straight (mowing already cut grass) until it is completely off the lawn.
With a mower starting in the left top, this shows the basic progression for a 5x3 lawn:
Second 0  Second 1  Second 2  Second 3  Second 4  Second 5  Second 6  Second 7  Second 8  Second 9  Second 10 Second 11 Second 12 Second 13 Second 14 Second 15 Second 16 Second 17 Second 18 Second 19 Second 20 Second 21 Second 22

                                                                  =
=o|||||    =o||||     =o|||     .=o||     ..=o|     ...=o     ....o     ....=     .....     .....     .....     .....     .....     .....     .....     .....     .....     .....     .....     .....     .....     .....     .....
  |||||     |||||     |||||     |||||     |||||     |||||     |||||     ||||o     ||||=     ||||.     ||||.     ||||.     ||||.     ||||.     ||||.     o|||.    =o|||.     =o||.     .=o|.     ..=o.     ...=o     ....=o    .....=o
  |||||     |||||     |||||     |||||     |||||     |||||     |||||     |||||     ||||o     ||||o=    |||o=     ||o=.     |o=..     o=...     o....     =....     .....     .....     .....     .....     .....     .....     .....
                                                                                =

Input
Your input will be the dimensions of the lawn (two integers).
Output
Print the lawn and the mower in your chosen position. You may chose the four characters for grass, cut grass, mower front, and mower back. You only to need enough whitespace to show the current second's content to specs, but extra whitespace is completely allowed, as long as it looks the same.
Since this is an animation, you may either clear the output each second, or print enough newlines to appear to animate in the viewing frame (you may assume the viewing frame is the size needed to appear to animate).
A consistent time interval other than one second is allowed (i.e. 999 millis to save a byte, or two seconds for some reason), but it should be such that the lawn mower still appears to be moving naturally.
If possible, provide a visual (TIO, Snippet, GIF, etc.)
This is code-golf, so shortest answer in bytes wins.

Nice challenge! Speaking from the perspective of a person who is annoyed by wires, you'd probably end up mowing over your wire :)

May we assume that the output window is sized to fit the lawn?

Something else you might want to allow is returning a list of all the states, similar to your example run.

What if we like to mow our lawn the right way? https://s-media-cache-ak0.pinimg.com/736x/92/5c/7c/925c7ce055dcbf15467ccd2f4c975ac7.jpg

@tuskiomi I've got another challenge in the works based on the same idea, but where the programmer has control over how it is mowed :)

Not sure if I'll dig into this, but would it be acceptable to assume an ANSI terminal that accepts relative cursor positioning with Escape-sequences?

@avl42 sure, go for it

JavaScript (ES6/Node.js), 664 525 523 chars
f=(w,h)=>{Z=require('sleep');c=a=>console.log(a);X=1;Y=2;D='e';N='|';O={'|':[0,-1],'e':[1,0],'s':[0,1],'w':[-1,0]};S=[N,D,'s','w'];q=d=>F[Y+O[d][1]][X+O[d][0]];b=' '.repeat(w+4),U='  ';F=[b,b].concat([...Array(h)].map(x=>U+N.repeat(w)+U)).concat([b,b]).map(x=>x.split``);for(;;){f=F.map(a=>a.concat());f[Y][X]='@';d=O[D];f[Y-d[1]][X-d[0]]='=';c(f.map(x=>x.join``).join`\n`);if(F[Y][X]==N)F[Y][X]='.';d=O[D],f=q(D),R=S[(S.indexOf(D)+1)%4],r=q(R);(r==N)&&((f==' ')||(f=='.'))?D=R:(X+=d[0],Y+=d[1])
Z.msleep(1E3);c('\033[2J')}}

Unminified with comments:
f=(w,h)=>{
  Z = require('sleep');
  c=a=>console.log(a);
  //mower coordinates
  X = 1;
  Y = 2;
  //mower direction
  D='e'; //n/e/s/w
  N='|';
  //directions with amount of change in [x,y] coordinates
  O = {'|':[0,-1],'e':[1,0],'s':[0,1],'w':[-1,0]};
  //direction short names
  S=[N,D,'s','w'];
  //query for item in specified direction relative to mower
  q=d=>F[Y+O[d][1]][X+O[d][0]];
 //generate field + whitespace
 b=' '.repeat(w+4),U='  ';
 F=[b,b].concat([...Array(h)].map(x=>U+N.repeat(w)+U)).concat([b,b]).map(x=>x.split``);
 for(;;){
    //print the field:
    //make a copy of the field, so we can paste the mower on top of it
    f=F.map(a=>a.concat());
    //print mower head
    f[Y][X]='@';
    //print mower tail
    d = O[D];
    f[Y-d[1]][X-d[0]]='=';
    c(f.map(x=>x.join``).join`\n`);
    //-----
    //move the mower
    if(F[Y][X]==N)F[Y][X]='.';//cut the grass if we stand on some
    d=O[D],//how many fields to move forward
        f=q(D),//item in front of mower
        R=S[(S.indexOf(D)+1)%4],//name of direction if we rotate to the right
        r=q(R);//item to right of mower
    //if there is wall in front of me OR cut grass in front of me and uncut on the right, turn right, else go ahead
    (r==N) && ((f==' ') || (f=='.'))?D=R:(X+=d[0],Y+=d[1])
    Z.msleep(1E3);
    c('\033[2J');
};
}
//test script
f(3,3);

note: I suppose I should get of the 'sleep' package and rewrite with setTimeout to be nodejs independent

I tried sticking this into TIO (it says it works for node.js). Any clue why it isn't working?

because of the 'sleep' module - i'll get rid of it