text:
Find the remaining side of the tangential quadrilateral
(Taken from https://en.wikipedia.org/wiki/File:Tangential_quadrilateral.svg)

A tangential quadrilateral (see example above) is a quadrilateral in which a circle can be inscribed.
Your task is to find the possible value of d given a, b, and c.
Specs

a, b, c will all be positive integers.
If no possible value of d exists, output 0.

Scoring
This is code-golf. Shortest solution in bytes wins.
Testcases
a b c d
3 4 4 3
1 2 3 2
1 5 3 0

Is the orientation of the sides always as in the picture?

@Dennis Yes, it is.

According to Wikipedia's mention of the Pitot theorem, a+c-b should be the only valid solution, provided it's positive.

Is the order for inputting a, b and c  strict, or can I also provide input like a, c, b?

Input are not strict by default.

In case no one has mentioned it before, I recommend posting challenges to the Sandbox where they can get feedback before going live.

@AlexA. Strangely, it seems he is aware of the sandbox as he keeps recommending that other people use it.

Dyalog APL, 4 bytes
0⌈-/

Try it online!
How it works
0⌈-/  Monadic function train. Argument: (a b c)

  -/  Reduce by subtraction.
      APL evaluates everything from right to left, so this computes
      a - b - c = a - (b - c) = a - b + c.
0⌈    Take the maximum of 0 and a - b + c.

Piet, 32 Codels
Codelsize 20:

Notes

Pretty straightforward. Could be 7x3=21 Codels if it wasn't for the termination, but it seems like thats required by default.

Npiet trace images
Valid input [1, 2, 3]

Invalid input [1, 5, 3]

05AB1E, 5 4 bytes
Input is taken as:
b
a
c

Code:
-+0M

Explanation:
      # Inputs: b, a, c
-     # Substract, (a - b).
 +    # Add with implicit input, (a - b + c).
  0   # Push zero on top of the stack.
   M  # Get the largest number that exists in the stack and implicitly print that value.

Try it online!

Jelly, 5 bytes
_@/»0

Try it online! or verify all test cases.
How it works
_@/»0    Main link. Argument: [a, b, c]

_@/      Reduce by swapped subtraction.
         This computes (a _@ b) _@ c = c - (b - a) = c - b + a.
   »0    Take the maximum of 0 and c - b + a.

MATL, 6 bytes
-+OvX>

My very first MATL answer! It can probably be shorter, I'd love tips! Input is backwards, e.g.:
c
b
a

Try it online!.
Explanation:
-        #Subtract the top two numbers (c and b)
 +       #Add the top two numbers (c-b and a)
  O      #Push a 0
   v     #Concatenate this into a array
    X>   #Print the smallest value of the array

My attempt was 6 bytes too, so I cannot offer many tips here :-) For which values do you get -0? BTW, that -0 is an Octave thing; I may need to look into it to produce just 0 in that case. Anyway, -+OhX> (also 6 bytes) probably avoids the minus in the output. You need to use O, not 0, to avoid the 0 sticking to the +

@LuisMendo Well that just made my day! =D I'm getting -0 with  3, 5, 1 as input.

Oh I see. Running on Matlab gives 0, not -0. It's an Octave thing (TIO uses Octave). I'll take note to maybe solve that in the future

Also, thanks for the tip with h! I was trying to do X> but I couldn't figure out how to turn [0, 3] into an array.

Anytime :-) h by default takes two inputs. v would take all the stack and try to concatenate vertically. That would also work here

Cubix, 12 9 bytes
This turned out longer than I wanted and then I messed up the spec. I might be able to knock out a byte or 2.
@w+?II-.\0O@

Wraps onto a cube with side length 2
    @ w
    + ?
I I - . \ 0 O @
. . . . . . . .
    . .
    . .

Gets II integer input twice, -. subtract followed by noop, \ redirect down (in this case around), hits the second I input again, + adds, ? conditional that turns left on negative, right on positive and straight through for zero.Turning left (invalid negative) w change lane to the right onto the literal 0 heading right through the O@ output and terminate.
Straight through (invalid zero) hits \ reflector and head right onto the literal 0 and the O@ output terminate.
Turning right (valid positive) travels around the cube, hitting the O output on the bottom face, onto the w change lane right, that switches the lane to the @ terminate.
Try it here

Have you considered putting a U where the - is? I'm on mobile so I can't really play around with it but it seems like it might allow you to use the third line a bit more efficiently.

@MartinBüttner thanks for the hint, I'll have a look at it and the w does shift to the right, will fix.

PowerShell, 41 38 bytes
param($a,$b,$c)[math]::Max(0,$a+$c-$b)

Pretty straightforward implementation of the Pitot theorem (thanks to Martin for remembering the name of it).
Saved 3 bytes by using the .NET [math]::Max() function.

J, 12 9 8 5 bytes
Input is given as a, b, c. Saved a byte inspired by using Dennis's subtraction method.
0>.-/

Explanation
0>.-/
   -/   reduce argument over subtraction
0>.     greater of the reduction and 0

Test cases
   rem =: 0>.-/
   rem 3 3 4
4
   rem 1 2 3
2
   rem 1 5 3
0
   rem"1 > (3 3 4 ; 1 2 3 ; 1 5 3)
4 2 0

Previously: (a,c,b input) +/@}:-{:), +/@(}:,-@{:)

Python, 25 bytes
lambda a,b,c:max(0,a-b+c)

Jolf, 4 bytes
\r0m4

Replace \r with a literal return, or try it here! Explanation:
\r0m4
   m4  anti-sum of implicit input
\r0    max of `0` and the anti-sum

Reng v.3.3, 33 bytes
ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<

Takes input like a c b. Try it here!
The calculation is simple. i gets input, so ii+ is a + c, and i- is then (a + c) - b. Very simple stuff.
The hard part is taking the max with 0. "What!? How could it be that hard?" Well, I didn't implement inequality in Reng. So we'll have to use math!
Observation 1: max(a,b) = (a+b+|a-b|)/2
Observation 2: max(a,0) = (a+|a|)/2
Observation 3: |a| = Sqrt[a^2]
Observation 4: Reng doesn't have square roots, either. Nor does it have power. But knowing that we'll only be taking the square roots of perfect squares, we can use trial and error, starting at 1. That is, our algorithm can look like this:
x = 1 to a, iterate:
  if x * x == a break, return X

Since we always have k being a perfect square, this algorithm always terminates.
So, into the rest of the code explanation!
ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<

part 1: initialization
I've already explained how ii+i- works, so let's look at the rest of the line.
     :²1#x1ø

: duplicates this number. The bottom number will be a in (a + |a|)/2. Now, we need to take the absolute value of the top value. We can do this using observations 3 and 4. ² squares the top value, and 1#x initializes our counter x with 1. Then we go to the next line with 1ø
part 2: square root loop
:x²eq!vx1+#x

: duplicates our maximum value a from the top of the stack (for the equality check). x² squares our counter x and e pushes a Boolean representing the equality of x² and a. If they are equal, q! breaks out of the loop by going down (v), leaving |a| on the stack. Otherwise, we increment x (x1+) and set x to that value (#x).
finalization
 ~n%2+<

< redirects the program to look left. shhh it saves bytes. It's equivalent to this series of steps:
+2%n~

+ adds the top two of the stack, thus implementing the first part of (a + |a|)/2. 2% divides that sum by two (% is division here because / is a mirror). Lastly, we output this as a number (n) and terminates the program (~).

JavaScript (ES6), 22 bytes
(a,b,c)=>a+c>b?a+c-b:0

Math.max is too long and there isn't a long enough common subexpression to deduplicate, so that's basically it. If a falsy value had been acceptable, then 21 bytes: (a,b,c)=>a+c>b&&a+c-b.

I sometimes wish all the properties of Math were in window.

><>, 7 bytes
-+:0)*n

Input assumed to be on the stack, in the order a, c, b.
It does c-b+a, and compares that with zero. Then it outputs either 0 or the answer before it terminates.
Try it online!

Pyke, 6 bytes
-+0]Se

Explanation:
+-     - do the mathsy bit (a+c)-b
  0]  - create a list with [0, ^]
 Se - Get the maximum value

Try it here!

Mathematica, 13 bytes
Max[##2-#,0]&

Anonymous function. Takes input in the order b, a, c. The ##2-# is just some crazy Sequencecraft that computes #2+#3-#. The Max[..,0] just takes the maximum of the result and 0.

MATLAB / Octave, 20 bytes
@(a,b,c)max(c-b+a,0)

Anonymous function that accepts the three inputs and returns the length of the fourth side. Can be called using ans(a,b,c).
Demo with all test cases

Python 2, 59 53 47 bytes
-6 bytes thanks to @KennyLau!
i=input;a,b,c=i(),i(),i();print(0,a+c-b)[b<a+c]

Takes 3 inputs, a, b and c. Then applies the Pitot Theorem (d=a+c-b).
Ungolfed
a = input()
b = input()
c = input()
if b < a + c:
    print a + c - b
else:
    print 0

you could use print(X if Y else Z) to save some bytes

@KennyLau does such a thing exist? WOW!

Hexagony, 16
?{?>+'<'-{?/@.!<

Try it online!
In expanded form:
  ? { ?
 > + ' <
' - { ? /
 @ . ! <
  . . .

This is actually a fairly simple program. First, we always execute the instructions in this order: ?{?'-{?/<'+ which just reads some values and computes a-b+c. Now if the value is positive, the > sends us north west and we bounce to the lower right < and then print the number (!) and exit (@).
The only really fancy part of the program is how it handles if the result was negative. If this happens, we move south west and execute: '?`{ which actually attempts to read another integer after moving the memory pointer around a bit and we land back on the place where we read another integer. Since the read fails to find a value, it returns zero and because zero isn't positive we wrap to the upper edge of the hexagon in this configuration, so we hit /<!.@ to print out the zero and exit.


text:
Building a Bridge
Your task is to build a bridge to connect two cliffs given an input d, the distance apart. d will always be even
However, the bridge needs columns to hold it up. Each column can hold a max of 6 spaces on each side.
For this example:
________                        ________
        |                      |
   A    |                      |   B

        |----------------------|
                d = 22

The bridge for d = 20should look like this with two columns. Columns do not count in d.
_____|__________|_____
12345|1234554321|12345
     |          |

Rules:

Must have enough columns to stand up.
Must have minimum number of columns needed to stand up.
Must be symmetrical
Lowest amount of Bytes Wins

Examples: (#s are only to help you count spaces. Should not be included in your output)
d = 10
_____|_____
12345|12345
     |

d = 32
_____|___________|___________|_____
12345|12345654321|           |
     |           |           |

d = 8
____|____
1234|1234
    |

d = 4
__|__
12|34
  |

d = 22
_____|____________|_____
12345|123456654321|
     |            |

or
______|__________|______
123456|1234554321|123456
      |          |

To clarify, are the numbers in the output required, or merely illustrative?

@isaacg No they are not needed in the output. They are just there so you guys dont have to count lines on my examples.

I think your specification is flawed? What prevents a 1|2|3|4|5...|d solution where | is a beam.

@Vlo One of the rules is to use the minimum number of columns possible. Therefore using a column every space would not be the minimum.

You say d is always going to be even, but in your last example, d=21.

@Hohmannfan Yes thank you. I fixed it to be 22.

Why does d=4 require any column at all?

@KennyLau You need it since the land in this example does not hold the bridge up.... Only columns

"Each column can hold a max of 5 or 6 spaces on each side": which is it: 5 or 6? "and must have beams going down on each side": I'm not sure what this means. "For this example:" what? Did some text go missing?

JavaScript (ES6), 92 bytes
d=>[..."_  "].map(c=>(s=c+c[r='repeat'](n%6))+'|'+(c[r](12)+'|')[r](n/6)+s,n=d-1>>1).join`\n`

Where \n represents the literal newline character. If d can be odd, it takes me 128 bytes:
d=>[..."_  "].map(c=>[...Array(d+1)].map((_,i)=>(d&1?i&&d-i&&(i>m)+5+i-m:((d-1)%24>11)*6+i-m)%12?'':'|',m=d>>1).join(c)).join`\n`

How can your solution for odd numbers work? For d=35, none of the optimal solutions are symetrical.

@Hohmannfan It returns the least suboptimal symmetrical solution, which in this case is |____________|___________|____________| etc.

I guess that is the best interpretation.

Ruby, 108 bytes
Probably can be golfed down a lot more. Greedy algorithm.
->d{s='',k=6
(s+=?_*[d,k].min+(d>k/2??|:'');d-=k;k=12)while d>0
s=s.chomp(?|)+s.reverse+$/
s+s.tr(?_,' ')*2}

source: Stack Exchange

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

sort: votes


text:
Read n random lines from a potentially huge file
This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.
Input
An integer n and the name of a text file.
Output
n lines of the text file chosen uniformly at random without replacement.
You can assume that n is in the range 1 to the number of lines in the file.
Be careful when sampling n numbers at random from the range that the answer you get is uniform. rand()%n in C is not uniform for example. Every outcome must be equally likely.
Rules and restrictions
Each line of the text file will have the same number of characters and that will be no more than 80.
Your code must not read any of the contents of text file except:

Those lines it outputs.
The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.
Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.
Your answer should be a complete program but you can specify the input in any way that is convenient.
Languages and libraries
You can use any language or library you like.
Notes
There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.
Motivation
In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.
The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:
shuf -n <num-lines>
This is however very slow for large files as it reads in the whole file.

Why the downvote?

This is trivial in languages like C that have fseek, and impossible in others. Additionally, what if n is greater than the number of lines in the file?

How can I skip lines? How can I know how many lines there are if I do not read them all?

@KennyLau "Each line of the text file will have the same number of characters and that will be no more than 80." You can calculate the exact position to jump to.

I don't even know how many lines there are. How can I calculate any position to jump to?

What if I overshoot?

In essence, this is a Do X without Y challenge. Attack drones are en route.

@Mego: regarding your point b): you can calculate the number of lines by dividing the file size by the length of a line.

@nimi A very good point!

I think this is fine, personally would add only one thing: line separators assumed to be consistent 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need.

Can we assume that the last line also has a line break at the end?

@Fatalize Yes please do.

Do X without Y is a warning that starts with "This isn't always bad". The main problem is artificial restrictions like "don't use +" which gives advantage to languages which have a sum(). Not reading a file into memory is a clear and consistent restriction which is in no way arbitrary. It can be tested with a file larger than memory, which cannot be worked around by language differences. It also happens to have real world applications (although that  isn't necessary for a golf...).

It looks like this is actually a restricted complexity code golf where the memory usage is limited despite potentially huge files. It's not about not having certain things in your code but a limitation on how the code may act.

Where does it say all the lines are the same length?

@feersum " Each line of the text file will have the same number of characters and that will be no more than 80."

Should each line be output at most once, or is repetition allowed? In other words, are we outputting line X (where X is the output from the RNG) N times, or are we doing the equivalent of shuffling the lines and outputting the first N?

@Mego The latter . It should be functionally equivalent to the example bash one liner I gave

Just to clarify, is it expected that the output be in random order as well as being random lines, or is the order of the lines not important?

@RobertBenson The order is not important.

Dyalog APL, 63 bytes
⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0

Prompts for file name, then for how many random lines are desired.
Explanation
⍞ Prompt for text input (file name)

⎕NTIE 0 Tie the file using next available tie number (-1 on a clean system)

t← Store the chosen tie number as t

83 80,⍨ Append [83,80] yielding [-1,83,80]

⎕NREAD Read the first 80 bytes of file -1 as 8-bit integers (conversion code 83)

10⍳⍨ Find the index of the first number 10 (LF)

l← Store the line length as l

(⎕NSIZE t)÷ Divide the size of file -1 with the line length

⎕ Prompt for numeric input (desired number of lines)

? X random selections (without replacement) out the first Y natural numbers

¯1+ Add -1 to get 0-origin line numbers*

l× Multiply by the line length to get the start bytes

t 82l∘,¨ Prepend [-1,82,LineLength] to each start byte (creates list of arguments for ⎕NREAD)

⎕NREAD¨ Read each line as 8-bit character (conversion code 82)
Practical example
File /tmp/records.txt contains:
Hello
Think
12345
Klaus
Nilad

Make the program RandLines contain the above code verbatim by entering the following into the APL session:
∇RandLines
⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0
∇

In the APL session type RandLines and press Enter.
The system moves the cursor to the next line, which is a 0-length prompt for character data; enter /tmp/records.txt.
The system now outputs ⎕: and awaits numeric input; enter 4.
The system outputs four random lines.
Real life
In reality, you may want to give filename and count as arguments and receive the result as a table. This can be done by entering:
RandLs←{↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}

Now you make MyLines contain three random lines with:
MyLines←3 RandLs'/tmp/records.txt'

How about returning just a single random line if count is not specified:
RandL←{⍺←1 ⋄ ↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}

Now you can do both:
MyLines←2 RandL'/tmp/records.txt'

and (notice absence of left argument):
MyLine←RandL'/tmp/records.txt'

Making code readable
Golfed APL one-liners are a bad idea. Here is how I would write in a production system:
RandL←{ ⍝ Read X random lines from file Y without reading entire file
    ⍺←1 ⍝ default count
    tie←⍵⎕NTIE 0 ⍝ tie file
    length←10⍳⍨⎕NREAD 83 80,⍨tie ⍝ find first NL
    size←⎕NSIZE tie ⍝ total file length
    starts←length×¯1+⍺?size÷length ⍝ beginning of each line
    ↑⎕NREAD¨tie 82length∘,¨starts ⍝ read each line as character and convert list to table
}

*I could save a byte by running in 0-origin mode, which is standard on some APL systems: remove ¯1+ and insert 1+ before 10.

Ahh.. APL :)  Is there some way to test this code in linux?

@Lembik Sure, this code is cross platform. Download from dyalog.com

As I don't read APL, could you explain the code? The tricky parts are sampling lines without replacement and jumping directly to the right place in the file to read the lines.

@Lembik That part is easy. ⎕NREAD's argument is TieNumber ConversionCode BytesToRead [StartByte]. It reads just the required bytes. The rest is just figuring out what to read.

@Lembik I'm curious why my answer didn't win the bounty.

@Nᴮᶻ I can't speak for Lembik but according to the bounty FAQ page if the bounty is not manually awarded by whoever initiated it, it will be awarded to the answer with the highest score

I feel a little guilty (and did ask on chat about this) but I awarded the bounty to the answer I liked most.  To be fair I have accepted your answer as well.

Ruby, 104 94 92 90 bytes
File name and number of lines are passed into the command line. For example, if the program is shuffle.rb and the file name is a.txt, run ruby shuffle.rb a.txt 3 for three random lines.
-4 bytes from discovering the open syntax in Ruby instead of File.new
f=open$*[0]
puts [*0..f.size/n=f.gets.size+1].sample($*[1].to_i).map{|e|f.seek n*e;f.gets}

Also, here's a 85-byte anonymous function solution that takes a string and a number as its arguments.
->f,l{f=open f;puts [*0..f.size/n=f.gets.size+1].sample(l).map{|e|f.seek n*e;f.gets}}

Below 100 bytes! Maybe Ruby is the best golfing language after all. Does 'sample' avoid repetitions?

@Lembik http://ruby-doc.org/core-2.2.0/Array.html#method-i-sample It does avoid repetitions. Don't tell me... was I supposed to have repetitions?

No you are perfect :)

Can you save any bytes by reading from stdin?  ruby shuffle.rb 3 < a.txt gives you a seekable stdin.  IDK Ruby, though.

@PeterCordes no luck, you get undefined method \size' for #<IO:> (NoMethodError)` because we need file size to determine number of lines. Also, reading from STDIN is probably reading the whole file into memory in order to pipe it in, so I think it's against the rules

I was imagining that Ruby might let you do f=stdin instead of f=open....   In Unix, standard input is just another file descriptor that's open when your process starts.  Seeking on it works just like any other file descriptor: fails if it's not open on a seekable file.  POSIX lseek(2) / C fseek(3) either works or fails, there's no read-and-discard fallback.  (And if stdin is redirected from a file, it will work.  With cat | ruby, it would of course fail.)  Like I said, I don't know Ruby, just the underlying Unix syscalls.

@PeterCordes That makes sense, but as mentioned, the point of failure is Ruby being unable to read the file size of stdin, so it didn't work out.

Haskell, 240 224 236 bytes
import Test.QuickCheck
import System.IO
g=hGetLine
main=do;f<-getLine;n<-readLn;h<-openFile f ReadMode;l<-(\x->1+sum[1|_<-x])<$>g h;s<-hFileSize h;generate(shuffle[0..div s l-1])>>=mapM(\p->hSeek h(toEnum 0)(l*p)>>g h>>=putStrLn).take n

Reads filename and n from stdin.
How it works:
main=do
  f<-getLine                   -- read file name from stdin
  n<-readLn                    -- read n from stdin
  h<-openFile f ReadMode       -- open the file
  l<-(\x->1+sum[1|_<-x])<$>g h -- read first line and bind l to it's length +1
                               -- sum[1|_<-x] is a custom length function
                               -- because of type restrictions, otherwise I'd have
                               -- to use "toInteger.length"
  s<-hFileSize h               -- get file size
  generate(shuffle[0..div s l-1])>>=
                               -- shuffle all possible line numbers
  mapM (\->p  ...  ).take n    -- for each of the first n shuffled line numbers
     hSeek h(toEnum 0).(l*p)>> -- jump to that line ("toEnum 0" is short for "AbsoluteSeek")
     g h>>=                    -- read a line from current position
     putStrLn                  -- and print

It takes a lot of time and memory to run this program for files with many lines, because of a horrible inefficient shuffle function.
Edit: I missed the "random without replacement" part (thanks @feersum for noticing!).

Haskell rocks :)

How does it avoid picking a line which was already chosen?

@feersum: oh, I missed that part. Fixed.

I see http://stackoverflow.com/questions/13779630/better-way-of-taking-random-sample-without-replacement-from-list-in-haskell is somewhat verbose!

@Lembik: implementing shuffle by hand is far too long. Of all the libraries with shuffle functions I've found, Test.QuickCheck requires the least overhead. Oh, and taking elements from a list of random numbers and discarding duplicates isn't deterministic, so you can't go that way (but I guess it's longer anyway)

Maybe there should be a separate challenge on sampling without replacement in small space.

PowerShell v2+, 209 bytes
param($a,$n)
$f=New-Object System.IO.FileStream $a,"Open"
for(;$f.ReadByte()-ne10){$l++}
$t=$f.Length/++$l-1
[byte[]]$z=,0*$l
0..$t|Get-Random -c $n|%{$a=$f.Seek($l*$_,0);$a=$f.Read($z,0,$l-1);-join[char[]]$z}

Takes input $a as the filename and $n as the number of lines. Note that $a must be a full-path filename, and assumed to be ANSI encoding.
We then construct a new FileStream object, and tell it to access the file $a with Open privilege.
The for loop .Read()s through the first line until we hit a \n character, incrementing our line-length counter each character. We then set $t equal to the size of the file (i.e., how long the stream is) divided by how many characters per line (plus one so it counts the terminator), minus one (since we're zero-indexed). We then construct our buffer $z to also be line length.
The final line constructs a dynamic array with the .. range operator.1 We pipe that array to Get-Random with a -Count of $n to randomly select $n line numbers without repetition. The lucky numbers are piped into a loop with |%{...}. Each iteration we .Seek to the particular location, and then .Read in a line's worth of characters, stored into $z. We re-cast $z as a char-array and -join it together, leaving the resultant string on the pipeline and output is implicit at the end of the program.
Technically we should end with a $f.Close() call to close out the file, but that costs bytes! :p
Example
a.txt:
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000003
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000005
a0000000000000000000000000000000000000000000000006
a0000000000000000000000000000000000000000000000007
a0000000000000000000000000000000000000000000000008
a0000000000000000000000000000000000000000000000009
a0000000000000000000000000000000000000000000000010

PS C:\Tools\Scripts\golfing> .\read-n-random-lines.ps1 "c:\tools\scripts\golfing\a.txt" 5
a0000000000000000000000000000000000000000000000002
a0000000000000000000000000000000000000000000000001
a0000000000000000000000000000000000000000000000004
a0000000000000000000000000000000000000000000000010
a0000000000000000000000000000000000000000000000006

1 Technically, this means we can only support a maximum of 50,000 lines, as that's the largest range that can be dynamically created in this manner. :-/ But, we can't just loop a Get-Random command $n times, discarding duplicates each loop, since that's not deterministic ...

Python 3, 146 139 bytes
from random import*
i=input
f=open(i())
l=len(f.readline())
[(f.seek(v*l),print(f.read(l)))for v in sample(range(f.seek(0,2)//l),int(i()))]
#print is here^

Input: [filename]\n[lines]\n
This solution heavily stole from @pppery but is python3.5 only and is a complete program.
Edit: Thanks to @Mego for the inline range and python3.x compatibility.
Edit2: Clarification where the print is because i got two comments about it. (Comment is obviously not part of the code or the byte count.)

Thank you! Which part is python 3.5 only?

r=range(f.seek(0,2)//l) will work, which shaves off 3 bytes and removes the need for 3.5. Even better, shave off 3 more bytes by inlining the range call in the sample call. Additionally, this is not a complete program - you need to actually print the list.

@Lembik: It was 3.5 only because i used r=[*range(f.seek(0,2)//l)] because i thought i couldn't sample a generator. Turns out I could.
@Mega: It is complete because it prints a every line inside the list comprehension print(f.read(l))

You do need a print statement though.

print is inside the list comprehension.

Oops! Sorry about that.

Bash (well, coreutils), 100 bytes
n=`head -1 $2|wc -c`;shuf -i0-$[`stat -c%s $2`/$n] -n$1|xargs -i dd if=$2 bs=$n skip={} count=1 2>&-

Explanation
This avoids reading the whole file using dd to extract the portions of the file we need without reading the file entirely, unfortunately it ends up quite large with all the options we have to specify:
if is the input file
bs is the block size (here we set it to $n which is the length of the first line
skip is set to the random integers extracted from shuf and equates to the ibs value skipping skip*ibs bytes
count the number of ibs length sections to return
status=none is needed to strip out the information normally output by dd
We get the line length using head -1 $2|wc -c and the filesize with stat -c%s $2.
Usage
Save above as file.sh and run using file.sh n filename.
Timings
time ~/randlines.sh 4 test.txt
9412647
4124435
7401105
1132619

real    0m0.125s
user    0m0.035s
sys     0m0.061s

vs.
time shuf -n4 test.txt
1204350
3496441
3472713
3985479

real    0m1.280s
user    0m0.287s
sys     0m0.272s

Times above for a 68MiB file generated using seq 1000000 9999999 > test.txt.
Thanks to @PeterCordes for his -1 tip!

I always love a bash answer but can you explain how this doesn't read the whole file?

@Lembik added explanation!

You can bs= instead of ibs=, since setting obs as well is fine.  I guess you can't replace if=$2 with <$2 though, since this is still xargs's command line.  \<$2 doesn't work either (xargs uses exec directly, without a shell).

I hope this isn't too much but I sort of love this answer :)  Just tested it with a 1GB file.

Thanks for that @PeterCordes! -1 byte! I've golfed it down a little further, I tried using od instead of dd, but I can't get the output in a nice format, I got close with xxd -r -p but got some weird results. I might play with it again tomorrow! Glad you liked it @Lembik! I've just made it a bit shorter, but I still can't compete with APL or Ruby... Yet...

re: redirecting stderr to stdin: You could also close stderr with 2>&-, so there's no danger of the output going anywhere (e.g. if stdin happened to be a read-write file descriptor).  It works with GNU dd: It still produces its stdout before trying and failing to write to stderr.

@PeterCordes Nice! Didn't think to close it fully, even better! Updated!

Lua, 126 122
r=io.read;f=io.open(r())c=2+f:read():len()for i=1,r()do f:seek("set",c*math.random(0,f:seek("end")/c-1))print(f:read())end

Uses 2 bytes for line breaks. Change the 2 to a 1 for 1. I only have it as 2 because that's what my test file had.
Got myself under the PHP entry, but still 2nd place (currently). Curse you, Ruby entry!

Lua was the first programming language I learned, and even with all I've learned since then, it's still my favorite. It's just so versatile for its ease to write.

Python 3 - 161 160  149 bytes
from random import*;
def f(n,g):f=open(g);l=len(f.readline());r=list(range(f.seek(0,2)/l));shuffle(r);[(f.seek(v*l),print(f.read(l)))for v in r[:k]]

This code defines a function which is called like f(10,'input.txt')

The challenge requires a full program, so I'm afraid a function definition is not enough.

To save a byte remove space between import and *.

@nimi Requiring a full program for this challenge seems to be arbitarily overriding the default code format rules

@ppperry: yes, maybe, but that's just how it is.

To get the length of the file you could f.seek(0,2), that makes import os and os.stat obsolete.

Python (141 bytes)
Keeps each line with equal probability, use with pipes too. It doesn't answer the skip ahead limitation of the question though...
Usage cat largefile | python randxlines.py 100 or python randxlines 100 < largefile (as @petercordes pointed out)
import random,sys
N=int(sys.argv[1])
x=['']*N
for c,L in enumerate(sys.stdin):
    t=random.randrange(c+1)
    if(t<N):x[t] = L
print("".join(x))

The whole point of this question is that you have to seek in the input stream.  You should probably say that that's the part of the question's restrictions you're ignoring (although the read-from-a-pipe example usage makes that pretty clear).  Reading from stdin with python ./randxlines.py 100  < largefile would be fine for a proper answer, though: in that case stdin will be seekable.

C# 259 bytes without duplicates
class Program{static void Main(string[]a){int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);HashSet<int>n=new HashSet<int>();while(n.Count<c)n.Add(new Random().Next(0,h.Count()));for(;c>0;c--)Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());}}

Ungolfed
class Program{static void Main(string[] a)
{
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        HashSet<int> n = new HashSet<int>();
        while (n.Count < c)
            n.Add(new Random().Next(0, h.Count()));
        for (; c > 0; c--)
            Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());
    }
}

File.ReadLines is Lazy.
This has the additional benefit that all lines can have different length.
Running it would be:
sample.exe a.txt 10000

C# 206 bytes with duplicates
class Program{static void Main(string[]a){var n=new Random();int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);for(;c>0;c--)Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());}}

Ungolfed
class Program
{
    static void Main(string[] a)
    {
        Random n = new Random();
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        for (; c > 0; c--)
            Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());
    }
}

I don't fully follow your solution. If all lines have different lengths then the task is impossible. Also, how you are randomly sampling lines without replacement exactly? I apologise my C# isn't good enough.

@Lembik You are right, i didn't think about duplicates. And I can count the amount of lines and extract lines by linenumber, which is why lines may be variable lengh.

But you have to jump to a location in the file only knowing the line number don't you? You can't tell where that is unless all the lines have the same length.

@Lembik File.ReadLines("pathToFile") create a Lazy enumeration on all Lines of the File, File.ReadLines("pathToFile").elementAt(19) returns the 19th Line of the File. Kinda like a Map of all Linestarts.

I don't think Lazy enumeration jumps (or seeks) in the file sadly. So it doesn't fit the rules currently.

To be a little clearer, your code reads (many) lines that it doesn't output which violates the rules of the challenge.

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


text:
Remove unnecessary parentheses
You are given a string composed with the characters 0123456789+*(). You can assume that string is always a valid mathematical expression.
Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.
The parentheses should be removed only when they are not needed structurally:

because of multiplication higher priority: 3+(4*5) => 3+4*5
because of multiplication or addition associativity: 3*(4*5) => 3*4*5
when they are redundant around an expression: 3*((4+5)) => 3*(4+5)

Parentheses should be kept when they could be simplified because of specific number values:

1*(2+3) should not be simplified to 1*2+3
0*(1+0) should not be simplified to 0*1+0

Examples:
(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)

(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6

More testcases please?

Not a trivial task. Somewhat related: http://codegolf.stackexchange.com/questions/67651/parenthesize-an-expression/68089

1*(2*(3+4)*5)*6 should be an interesting testcase (which my solution currently fails for).

There won't be whitespace in the expression, right?

@orlp no whitespace, only 0123456789+*()

Is "unnecessary" defined structurally or on a per-case basis? In other words, are the parentheses unnecessary here? (2+2)*1

@LuisMendo I think it's fair to interpret it in either way

@anatolyg I don't think that'd be fair, because the approaches for the two would be very different. It would be good if we got some clarification.

@Sp3000 I've added more details. I should have used variables [a..z] rather than numbers...

Suggest case 1+((2+3)*4) -> 1+(2+3)*4, 1*((2+3)*4+(5+6)) -> unchanges

Mathematica, 105 97 91 bytes
-6 bytes thanks to Roman!
a=StringReplace;ToString@ToExpression@a[#,{"*"->"**","+"->"~~"}]~a~{" ** "->"*","~~"->"+"}&

Replaces + and * with ~~ (StringExpression) and ** (NonCommutativeMultiply) respectively, evaluates it, stringifies it, and replaces the operators back.

What? Mathematica doesn't have a built-in?

@EriktheGolfer It basically does; I'm trying to make it not evaluate the operators.

That's why Mathematica is so-advertised and so-expensive... because of the built-ins I think. But, Mathematica hasn't got a change over other languages if the puzzle is tough enough, yet "other languages" don't compete at all here.

91 bytes by using StringExpression instead of Dot, and removing the " "->"" clause: a=StringReplace;ToString@ToExpression@a[#,{"*"->"**","+"->"~~"}]~a~{" ** "->"*","~~"->"+"}&

@Roman Thanks! It seems you found another good associative non-commutative unevaluated operator that doesn't combine with numbers.

JavaScript (ES6) 163 178
Edit 15 bytes saved thx @IsmaelMiguel
a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')?-s.push(b[p-1]=='*'|z=='*'?x:y):y))b=a;${_}-\\d+/,x=>s[~x]))b=a`)

Less golfed
a=>{
  for(s=[],b='';
      a!=b;
      a=b.replace(/\(([^()]*)\)(?=(.?))/,(x,y,z,p)=>y.indexOf('+')<0?y:-s.push(b[p-1]=='*'|z=='*'?x:y)))
    b=a;
  for(b=0;
      a!=b;
      a=b.replace(/-\d+/,x=>s[~x]))
    b=a;
  return a
}

Test

f=a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')
?-s.push(b[p-1]=='*'|z=='*'?x:y)
:y))b=a;${_}-\\d+/,x=>s[~x]))b=a`)

console.log=x=>O.textContent+=x+'\n'

test=`(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)
(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6`

test.split`\n`.forEach(r=>{
  var t,k,x
  [t,,k]=r.match(/\S+/g)
  x=f(t)
  console.log((x==k?'OK ':'KO ')+t+' -> '+x+(x==k?'':' expected '+k))
})

Why did you wrote y.indexOf('+') instead of y.indexOf`+`[...]? ([...] added to avoid tripping the formatting) Was it bugging out that way?

Here you go, 170 bytes: a=>eval(`for(b=s=[]${_=';a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')<0?-s.push(b[p-1]=='*'|z=='*'?x:y):y))b=a;for(b=0${_}-\\d+/,x=>s[~x]))b=a`)

@IsmaelMiguel that's really clever, thanks! Lesson learned: when passing to eval, rethink it all again

I'm glad you liked my simple solution to reduce your code. I wish I could do something about for(b=, =='*' and other repeated bits. Also, isn't ~y.indexOf('+')<0 the same as ~y.indexOf('+')? Since the only value that indexOf() returns that evaluates to a falsy value is -1, the <0 seems redundant. Or, if I got it wrong, you could do y.indexOf('+')>1

@IsmaelMiguel 1: yes, the <0 is crap remaining from the ungolfed version and should be removed. 2: thinking again, the for can be revised to be included in the repeated part. Thanks again

Wow, you made a really nice touch! I didn't though about it! I wish I could upvote again... But nice work on chopping off those bytes!

@Oliver: http://meta.codegolf.stackexchange.com/questions/8428/avoid-useless-edit-about-byte-count

Python3 + PEG implementation in Python, 271 bytes
import peg
e=lambda o,m=0:o.choice and str(o)or(m and o[1][1]and"("+e(o[1])+")"or e(o[1]))if hasattr(o,"choice")else o[1]and e(o[0],1)+"".join(str(x[0])+e(x[1],1)for x in o[1])or e(o[0])
print(e(peg.compile_grammar('e=f("+"f)*f=p("*"p)*p="("e")"/[0-9]+').parse(input())))

A while back I made a PEG implementation in Python. I guess I can use that here.
Parses the expression into a tree, and only keeps parenthesis if the child is addition, and the parent is multiplication.

Perl, 132 bytes
129 bytes source + 3 for -p flag:
#!perl -p
0while s!\(([^\(\)]+)\)!$f{++$i}=$1,"_$i"!e;s!_$i!($v=$f{$i})=~/[+]/&&($l.$r)=~/[*]/?"($v)":$v!e
while($l,$i,$r)=/(.?)_(\d+)(.?)/

Using:
echo "1*(2*(3+4)*5)*6" | perl script.pl

Ruby, 140 130 bytes
127 bytes source + 3 for  -p flag:
t={}
r=?%
0while$_.gsub!(/\(([^()]+)\)/){t[r+=r]=$1;r}
0while$_.gsub!(/%+/){|m|(s=t[m])[?+]&&($'[0]==?*||$`[/\*$/])??(+s+?):s}

And ungolfed:
tokens = Hash.new
key = '%'

# convert tokens to token keys in the original string, innermost first
0 while $_.gsub!(/\(([^()]+)\)/) { # find the innermost parenthetical
  key += key # make a unique key for this token
  tokens[key] = $1
  key # replace the parenthetical with the token key in the original string
}

# uncomment to see what's going on here
# require 'pp'
# pp $_
# pp tokens

# convert token keys back to tokens, outermost first
0 while $_.gsub!(/%+/) {|key|
  str = tokens[key]
  if str['+'] and ($'[0]=='*' or $`[/\*$/]) # test if token needs parens
    '(' + str + ')'
  else
    str
  end
}
# -p flag implicity prints $_

very nice answer.  what is happening with the 0 while syntax?

@Jonah In Ruby, expr while cond is equivalent to while cond; expr; end. Here, I only want to perform cond repeatedly and don't actually have a loop body. Usually one would write this as while cond; end or perhaps loop{ break unless cond } but 0 while cond is fewer bytes. The 0 doesn't do anything; it's just there because the short form of the while loop requires a body.

Retina, 155 bytes
{`\(((\d+|\((((\()|(?<-5>\))|[^()])*(?(5)^))\))(\*(\d+|\((((\()|(?<-10>\))|[^()])*(?(10)^))\)))*)\)
$1
(?<!\*)\((((\()|(?<-3>\))|[^()])*(?(3)^))\)(?!\*)
$1

Try it online!
Verify all testcases at once.
Explanation
The main thing is this code:
(((\()|(?<-3>\))|[^()])*(?(3)^)

This regex can match any string in which the brackets are balanced, e.g. 1+(2+(3))+4 or 2+3.
For the ease of explanation, let this regex be B.
Also, let us use < and > instead for the brackets, as well as p and m for \+ and \*.
The code becomes:
{`<((\d+|)(m(\d+|))*)>
$1
(?<!m)(?!m)
$1

The first two lines match for brackets which consist of only multiplication, e.g. (1*2*3) or even (1*(2+3)*4). They are replaced by their content inside.
The last two lines match for brackets which are not preceded and which are not followed by multiplication. They are replaced by their content inside.
The initial {` means "replace until idempotent", meaning that the replacements are done until they either no longer match or they are replaced with themselves.
In this case, the replacements are done until they no longer match.

Fails for 1*(2*(3+4)*5)*6.

@orlp Thanks, fixed.

Fails for (1*(2+3)+4)*5

@Sp3000 Thanks, fixed.

Python 3, 274 269 359 337 336 bytes
This method basically removes every possible pair of parentheses and checks to see if it still evaluates the same.
from re import *
def f(x):
    *n,=sub('\D','',x);x=sub('\d','9',x);v,i,r,l=eval(x),0,lambda d,a,s:d.replace(s,"?",a).replace(s,"",1).replace("?",s),lambda:len(findall('\(',x))
    while i<l():
        j=0
        while j<l():
            h=r(r(x,i,"("),j,")")
            try:
                if eval(h)==v:i=j=-1;x=h;break
            except:0
            j+=1
        i+=1
    return sub('9','%s',x)%tuple(n)

Test Harness
print(f("(4*12)+11")=="4*12+11")
print(f("(1+2)*3") =="(1+2)*3")
print(f("3*(4*5)")=="3*4*5")
print(f("((((523))))")=="523")
print(f("(1+1)")=="1+1")
print(f("1*(2*(3+4)*5)*6")=="1*2*(3+4)*5*6")
print(f("(((2+92+82)*46*70*(24*62)+(94+25))+6)")=="(2+92+82)*46*70*24*62+94+25+6")
print(f("1*(2+3)")=="1*(2+3)")
print(f("0*(1+0)")=="0*(1+0)")

Updates

-1 [16-10-04] Removed extra space
-22 [16-05-07] Made use of the re lib
+90 [16-05-07] Updated to handle the new test cases
-5 [16-05-07] Removed parameter from the length (l) lambda

This fails the test case 1*(2+3), because OP said not to simplify for special number cases. Good answer though; this has my upvote.

@AlexL. Thanks for catching that! I didn't update my test cases D: But it is fixed now.

PHP, 358 bytes
function a($a){static$c=[];$d=count($c);while($g=strpos($a,')',$g)){$f=$a;$e=0;for($j=$g;$j;--$j){switch($a[$j]){case')':++$e;break;case'(':--$e;if(!$e)break 2;}}$f[$g++]=$f[$j]=' ';if(eval("return $f;")==eval("return $a;"))$c[str_replace(' ', '', $f)]=1;}if(count($c)>$d){foreach($c as$k=>$v){a($k);}}return$c;}$t=a($argv[1]);krsort($t);echo key($t);

Not an impressive length, that's what I get for taking a less than optimal approach (and using a less than optimal language).
Strips a pair of brackets out, then evals the resulting expression. If the result is the same as the original it adds it to a map of valid expressions and recurses until no new expressions can be found. Then prints the shortest valid expression.
Breaks when the result of the expression gets large and casts to double / exponent notation show up.

Prolog (SWI), 122 118 bytes
T+S:-term_string(T,S).
I/O:-X+I,X-Y,Y+O.
E-O:-E=A+(B+C),A+B+C-O;E=A*(B*C),A*B*C-O;E=..[P,A,B],A-X,B-Y,O=..[P,X,Y];E=O.

Try it online!
Defines a predicate //2 which removes parentheses from its first argument's string value and outputs a string through its second argument. If input could be in Prolog terms, this would only be 81 77 bytes defining +/2 without having to deal with the verbose term_string/2, but a lot of unnecessary parentheses would simply not have existed to begin with that way so it would be pretty close to cheating, since all that +/2 does is handle associativity.
I tried to use =../2 for all of it, but it came out far longer, because a three-byte operator that works with lists isn't exactly terse:
Prolog (SWI), 124 bytes
T+S:-term_string(T,S).
I/O:-X+I,X-Y,Y+O.
X-Y:-X=..[O,A,B],(B=..[O,C,D],E=..[O,A,C],F=..[O,E,D],F-Y;A-C,B-D,Y=..[O,C,D]);X=Y.

Try it online!

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


text:
Outline a PNG image
Intro (semi fictional)
I'm the solo developer of a game, I'm already struggling with character design as is. Hence I've thought of a smart solution, I'll just use images for regular monsters, outline them a bit and suddenly they are boss monsters! That will save me from thinking up new bosses yay.
However, I have approximately 100 monster designs already and I wouldn't like duplicating them all and manually drawing an outline to the images...
Challenge
Given a file name (of a PNG file) as input, you should write a program/function which will draw an outline around every non-transparent pixel. The program/function should save the output file to a new file called a.png
What does outlining mean
Outlining is the process of adding non-transparent pixels in the place of transparent pixels, around pixels which were non-transparent already. Any transparent pixel has an opacity of exactly 0%, anything else is defined as non-transparent. Any pixel which will be outlined will have an opacity of 100%, aka the alpha channel of that pixel will be 255.
Input
Your program/function should take 3 variables as input. Feel free to provide these as function parameters, read them from stdin or any other method which suits you best.
The first variable is the file name, which is always a PNG file.
The second variable is the outline colour, which is a round integer, you can also take the colour from 3 separate r,g,b byte values.
The third variable is the outline width, also an integer.
Outline width
The width of the outline equals the maximum distance any transparent pixel should have to a non-transparent pixel in order to be outlined. The distance is calculated using the Manhattan distance between two points.
If the input image has only 1 non-transparent pixel, at [0,0] and the outline width is 2, then the following pixels will be coloured:
[0,1] [0,-1] [1,0] [-1,0] [1,1] [-1,-1] [1,-1] [-1,1] [2,0] [-2,0] [0,2] [0,-2], for these have a manhattan distance of 2 or less from the coloured pixel
Test cases
The following test cases are scaled up 7 times for visibility, so every block of 7 pixels should be treated as a single pixel
These are the input images used for the test cases:
input1.png

input2.png

input3.png

These are the actual test cases:
input1.png, 0xFF0000, 0

input1.png, 0xFF0000, 1

input1.png, 0xFF0000, 2

input1.png, 0xFF0000, 3

input1.png, 0xFF0000, 10

input2.png, 0xFF0000, 2

input3.png, 0x000000, 2

Click here for the full Imgur album.
This is code-golf, standard loopholes apply! Feel free to submit your own images as test cases, since these pixel images aren't very creative ;)

Could the color also be taken as three separate r,g,b values?

@flawr also fine with me

I assume you enlarged the images in the challenge description. Can you also post the ones with the original size?

The PNG image requirement ruins the challenge.

Matlab, 202 bytes
function f(i,r,g,b,n);[i,~,a]=imread(i);[x,y]=ndgrid(abs(-n:n));d=permute([r,g,b,255]',3:-1:1);I=cat(3,i,a);J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I;imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4))

As always:

Convolution is the key to success.

The function can be called like so:
f('my_image.png', red_int, green_int, blue_int, dist)

Commented:
function f(i,r,g,b,n)
[i,~,a]=imread(i);                   %read image and alpha channel
[x,y]=ndgrid(abs(-n:n));             %computations for convolution kernel
d=permute([r,g,b,255]',3:-1:1);      %create 'pixel' that will be inserted
I=cat(3,i,a);                        %concatenate image and alpha channel
J=uint8(bsxfun(@times,~~convn(a,x+y<=n,'s')&~a,d))+I; %find border via convolution of kernel, insert pixels and recombine with original
imwrite(J(:,:,1:3),'a.png','Al',J(:,:,4)) %write file

PHP, 559 chars
Ungolfed
<?php
error_reporting(0);
$p=$argv[1];
$img = ImageCreateFromPng($p);
$width = imagesx($img);
$height = imagesy($img);
$new = ImageCreateFromPng($p);
alphaFix($img);
alphaFix($new);
$inv = '2130706432';
for($w=0;$w<$width;$w++)
    for($h=0;$h<$height;$h++)
    {
        $color = ImageColorAt($img, $w, $h);
        if($color != $inv)
            for($x=0;$x<$width;$x++)
                for($y=0;$y<$height;$y++)
                {
                    if(abs($h - $y) + abs($w - $x) <= intval($argv[3]))
                    {
                        $_color = ImageColorAt($img, $x, $y);
                        if($_color == $inv)
                            imagesetpixel($new, $x, $y, hexdec($argv[2]));
                    }
                }
    }
imagepng($new, str_replace(".png", ".border.png", $p));

function alphaFix(&$img)
{
    $background = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $background);
    imagealphablending($img, false);
    imagesavealpha($img, true);
}
?>

Golfed
<?error_reporting(0);$j=$argv[1];$g=ImageCreateFromPng($j);$e=imagesx($g);$b=imagesy($g);$l=ImageCreateFromPng($j);a($g);a($l);$f='2130706432';for($m=0;$m<$e;$m++)for($l=0;$l<$b;$l++){$d=ImageColorAt($g,$m,$l);if($d!=$f)for($k=0;$k<$e;$k++)for($i=0;$i<$b;$i++){if(abs($l-$i)+abs($m-$k)<=intval($argv[3])){$c=ImageColorAt($g,$k,$i);if($c==$f)imagesetpixel($l,$k,$i,hexdec($argv[2]));}}}imagepng($l,str_replace(".png",".border.png",$j));function a(&$g){$a=imagecolorallocate($g,0,0,0);imagecolortransparent($g,$a);imagealphablending($g,0);imagesavealpha($g,1);}

Syntax
php outline.php "image1.png" 0xFF0000 1
                     |           |    |
                     |           |    *- Border Size
                     |           *------ Color HEX
                     *------------------ Image Name

Examples
I made an Imgur album, because I slightly changed the images and there you can also see the arguments I passed my script.


text:
Finite Cantor's Diagonal
Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.
Example
Given this list:
1234
4815
1623
4211

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.
Inputs

You may take both the list and N as input, or only the list if you wish.
Each integer in the list will necessarily have as many digits as the length of the list (N)
Numbers will not have any leading zeroes
The input list must contain numbers and not strings.
You may take inputs as function arguments, through STDIN, or anything similar.
You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.
You can use any digit selection strategy that respects the constraint of different digits.
The number cannot have leading zeroes
You may output the number through STDOUT, return it from a function, etc.

Test cases
Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2

Scoring
This is code-golf, so the shortest answer in bytes wins.

So we have to convert the STDIN to integer before parsing?

@KennyLau input has to be numbers, if you language can parse digits directly you don't have to convert anything.

But STDIN is string by default...

Then convert the input string to a list of integers.

Can we output a list of digits?

@CᴏɴᴏʀO'Bʀɪᴇɴ No, the output is an integer.

Can I answer in say, Retina, which doesn't have the concept of a number? (at least in the sense of it being different from a string in any meaningful way)

@FryAmTheEggman If your language's natural representation of integers is strings then yes.

When you say the output cannot have leading zeroes, does that mean it must be the same length as the input, or can there be fewer digits as long as leading zeroes are not displayed?

@xnor there cannot be fewer digits

This is naturally best done in DZZZZ

Jelly, 8 7 bytes
1 byte saved thanks to Dennis.
DŒDḢỊ‘Ḍ

Try it online!
Explanation
DŒDḢỊ‘Ḍ    Main link. Takes list as argument.
D          Convert each integer to decimal.
 ŒD        Get the diagonals.
   Ḣ       Get the first diagonal.
    Ị      Check if every digit <= 1.
     ‘     Increment every digit.
      Ḍ    Convert back to integer from decimal.

Converts each digit to 1, except 0 and 1 becomes 2.

CJam (15 14 bytes)
qN/ee{:=i2%)}%

Online demo
Thanks to Adnan for a one-byte saving.
Dissection
qN/    e# Split input on newlines
ee{    e# Label each line with its index and map:
  :=i  e#   Get the character at the same index (i.e. diagonalise)
  2%)  e#   Compute (ASCII value mod 2) + 1
       e#   Maps 0 1 2 3 4 5 6 7 8 9
       e#     to 1 2 1 2 1 2 1 2 1 2
}%

@Adnan, that does work, thanks. Alternatively i2%) could be 49&), working directly with characters rather than ASCII codes.

Python 2, 47 45 bytes
lambda x,n:int(`x`[1::n+3])%(10**n/2)+10**n/9

Thanks to @xnor for golfing off 2 bytes!
Test it on Ideone.
How it works
`x` yields a string representation of the list x.
For the first test case, this gives the string
[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]

[1::n+3] retrieves every (n + 3)th character – where n is the length of x starting with the second one. Accounting 2 characters for ,, we retrieve the first digit of the first number, the second digit of the second number, etc.
[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]
 ^          ^          ^          ^          ^          ^          ^          ^

We now take the number modulo 10n ÷ 2 to map the first digit in the range [0, 4].
For 93579135, we get 93579135 % 50000000 = 43579135.
Finally, we add 10n ÷ 9 to the last result, which increments – wrapping around from 9 to 0 – all digits by 1 (no carry) or 2 (with carry).
For 43579135, we get 43579135 + 11111111 = 54690246.

MATL, 11 10 9 bytes
VXd9\QV!U

Takes only a column vector of integers as input. N is not provided.
Try it Online
Explanation
    % Implicity grab input as column vector of numbers
V   % Convert the input column vector into a 2D character array
Xd  % Grab the diagonal elements of the character array
9\  % Take the modulus of each ASCII code and 9
Q   % Add 1 to remove all zeros
V   % Convert the result to a string
!   % Transpose to yield a row vector of characters
U   % Convert back to an integer (as per the rules)
    % Implicitly display result

@LuisMendo Oh crud. It looks like it has a leading zero issue though when the first digit is 2: http://matl.tryitonline.net/#code=VlhkMTBcViFV&input=WzIyMzQ1Njc4OzIzNDU2Nzg5OzM0NTY3ODkwOzQ1Njc4OTAxOzU2Nzg5MDEyOzY3ODkwMTIzOzc4OTAxMjM0Ozg5MDEyMzQ1XQ

Maybe VXd9\QV!U

Oh, I hadn't thought of leading zero...

@LuisMendo Does it matter that they aren't unique? As long as they aren't the same value as the input it shouldn't matter.

You're totally right. I was thinking about it the wrong way

@LuisMendo Well together we were finally able to save that byte! Thanks!

Well, my contribution was to push you in the wrong direction so that you could solve it yourself :-D

Pyth, 11 bytes
jk.eh!ts@`b

Simple loop, change every digit to 1, except 1 becomes 2.

Nice usage of the implicit Q and k! You can save one byte with during the digit-transformation though: s.eh-12@`b

Retina, 39 38 37
(?<=(.*¶)*)(?<-1>.)*(.).*¶
$2
T`d`121

Saved 1 byte thanks Martin!
Requires a trailing linefeed in the input.
Gets diagonals and translates 0 and 2-9 to 1 and 1 to 2.
The basic idea for getting the diagonals is to push a capture for each row above the current row and then consume a capture to match a character, then keep the next character.
Try it online

Java, 93 bytes
String k(int n,int[]a){String s="";for(int i=0;i<n;)s+=(a[i]+s).charAt(i++)<57?9:1;return s;}

Ungolfed
String k(int n, int[] a) {
    String s = "";
    for (int i = 0; i < n; )
        s += (a[i] + s).charAt(i++) < 57 ? 9 : 1;
    return s;
}

Output
Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Output:
99991999

Input:
1234
4815
1623
4211

Output:
9999

J, 26 22 bytes
1+1>:i.@#{"_1"."0@":"0

Similar approach to the others using the <= 1 and increment method of the diagonal.
Usage
Only requires the list of integers as an argument.
   f =: 1+1>:i.@#{"_1"."0@":"0
   f 1234 4815 1623 4211
2 1 1 2
   f 92345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345
1 1 1 1 1 2 1 1

Sorry to break the 1 streak...

Perl, 18 bytes
Includes +1 for -p
Run with the input lines on STDIN. Output is 1 except 2 when the diagonal is 1
cantor.pl
#!/usr/bin/perl -p
pos=$.;$_=/1\G/+1

Python 2, 54 bytes
d,r=1,""
for n in input():r+=`1+-~n/d%9`;d*=10
print r

Sounds familiar. -~n

Java, 94 bytes
int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}

Pure numeric operations for the win! :)
Sample input/output:
8            <-- size
12345678     <-- start of list
23456789
34567890
45678901
56789012
67890123
78901234
89012345     <-- end of list
21111211     <-- result from ungolfed code
21111211     <-- result from golfed code

Full program (with ungolfed code):
import java.util.Scanner;

public class Q79444 {
    int cantor_ungolfed(int[] data){
        int power = 1;
        int result = 0;
        for(int i=0;i<data.length;i++){
            result += (((data[data.length-i-1]/power))%10==1? 2 : 1)*power;
            power *= 10;
        }
        return result;
    }
    int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] input = new int[n];
        for(int i=0;i<n;i++){
            input[i] = sc.nextInt();
        }
        System.out.println(new Q79444().cantor_ungolfed(input));
        System.out.println(new Q79444().c(input));
        sc.close();
    }
}

Reng v.3.3, 60 bytes
k1-#kaiír1ø          ~; !nb$<
1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$

For Reng, that was rather simple. Try it here! Input is a space-separated list of numbers.
1: init
k1-#kaiír1ø

k is the number of inputs (number of numbers), and we decrement by 1 and restore for the loop stage. aií takes all input. r reverses the stack for the processing of input. 1ø goes to the next line.
2: loop
1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$

1[ takes the top item off the stack and into a new stack. å splits it into digits. {$} pushes a code block containing the operation "drop"; this is repeated k times (k*) and the code block is dropped ($. k1-#k decrements k. )9( puts 9 at the STOS, and - subtracts TOS from the STOS. #o stores this number in o, and a$; drops all the members of the stack. ] closes the parent stack. o puts o back at the top; this is our digit we're saving. ) moves it to the bottom so that we can continue our looping. s usually checks for non-input (i.e., equality to -1), but we can use it to break out of our loop when k == -1. So s^ goes up when k == -1. $ drops k from the stack, and our loop begins again.
3: final
                     ~; !nb$<

< directs the pointer left, and $ drops k from the stack. b is a leftway mirror, so we enter through it, but it bounce back when hitting ;, a stack-condition mirror. !n prints a digit if and only if we're going left. ~ ends the program when we're done printing.

Ruby, 21 bytes
$><<$_[$.-1].hex%2+1

A full program. Run with the -n flag. Uses the following mapping: n -> n%2+1.

Pyth, 14 bytes
s.e|-\1@bk\2`M

Try it online!

J, 37 bytes
f@(9&-@"."0@((>:@#*i.@#){f=:[:,":"0))

Can probably be golfed, but I forgot if there was a command for "diagonals".

I've seen it used before, Martin used the anti-diagonals here.

@FryAmTheEggman Yeah, that's close. I'm still looking, but there might not be.

This seems to produce a leading zero if the diagonal begins with a 9.

You can create the digits table if you take the input n using <list> (#:~#&10) <n>. The first diagonal can be found with (< 0 1) |: <list> where (< 0 1) is a box for the axes to select, using both, with |:

Mathematica 52 bytes
FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@#]]&

This follows the approach of Peter Taylor and others (without using Ascii codes).
Example
FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@ #]]&[{1234,4815,1623,4211}]

2112

ClojureScript, 58 chars
#(int(apply str(map-indexed(fn[i x](- 9(get(str x)i)))%)))

Type requirements made this a little longer than necessary, and map-indexed being so many chars didn't help.
Often my submissions are valid Clojure as well, but this is using some of ClojureScript's leakiness with JavaScript.  Subtraction of a number and string coerces the string to a number--that is, (- 9 "5") equals 4.

PHP, 46/41/40 bytes
while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;

while($a=$argv[++$i])echo$a[$i-1]==7?6:7;

while($a=$argv[++$i])echo($a[$i-1]%2)+1;

Various digit selectors for comparison. I thought "9-digit" would be shortest, but the special case needed to keep a zero out of the first digit overwhelms it.
Fed from CLI arguments:
php -r "while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;" 12345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345
86421864

JavaScript (ES6), 41
The %9+1 trick is borrowed from Suever's answer. For once, .reduce beats .map. Note, the += operator is used to avoid parentheses.
a=>+a.reduce((t,n,d)=>t+=(n+t)[d]%9+1,'')

Vyxal, 49 bitsv2, 6.125 bytes
vfÞ/ċ›ṅ

Try it Online!
Port of Jelly


text:
Matrix Trigonometry
Introduction
The two most common trigonometric functions, sine and cosine (or sin and cos for short), can be extended to be matrix-valued functions. One way to compute the matrix-valued analogs is as follows:
Consider these two important trigonometric identities:
$$
e^{i x} = \cos(x) + i \sin(x) \\
\sin^2(x) + \cos^2(x) = 1
$$
Using these identities, we can derive the following equations for sin and cos:
$$
\sin(x) = \frac{e^{i x} - e^{-i x}}{2 i} \\
\cos(x) = \frac{e^{i x} + e^{-i x}}{2}
$$
The matrix exponential exists for all square matrices and is given by:
$$
e^A = \sum_{k = 0}^\infty \frac{1}{k!} A^k
$$
where A0 is the identity matrix I with the same dimensions as A. Using the matrix exponential, these two trigonometric functions (and thus all the other trigonometric functions) can be evaluated as functions of matrices.
The Challenge
Given a square matrix A, output the values of sin(A) and cos(A).
Rules

Input and output may be in any convenient, reasonable format (2D array, your language's matrix format, etc.).
You may write a single program, two independent programs, a single function, or two functions. If you choose to write two functions, code may be shared between them (such as imports and helper functions).
The input matrix's values will always be integers.
Your solution may have accuracy issues as the result of floating-point imprecision. If your language had magical infinite-precision values, then your solution should work perfectly (ignoring the fact that it would require infinite time and/or memory). However, since those magical infinite-precision values don't exist, inaccuracies caused by limited precision are acceptable. This rule is in place to avoid complications resulting from requiring a specific amount of precision in the output.
Builtins which compute trigonometric functions for matrix arguments (including hyperbolic trig functions) are not allowed. Other matrix builtins (such as multiplication, exponentiation, diagonalization, decomposition, and the matrix exponential) are allowed.

Test Cases
Format: A -> sin(A), cos(A)
[[0]] -> [[0]], [[1]]
[[0, 2], [3, 5]] -> [[-0.761177343863758, 0.160587281888277], [0.240880922832416, -0.359709139143065]], [[0.600283445979886, 0.119962280223493], [0.179943420335240, 0.900189146538619]]
[[1, 0, 1], [0, 0, 0], [0, 1, 0]] -> [[0.841470984807897, -0.158529015192103, 0.841470984807897], [0, 0, 0], [0, 1, 0]], [[0.540302305868140, -0.459697694131860, -0.459697694131860], [0, 1, 0], [0, 0, 1]]
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] -> [[0.841470984807897, 0, 0, 0, 0], [0, 0.841470984807897, 0, 0, 0], [0, 0, 0.841470984807897, 0, 0], [0, 0, 0, 0.841470984807897, 0], [0, 0, 0, 0, 0.841470984807897]], [[0.540302305868140, 0, 0, 0, 0], [0, 0.540302305868140, 0, 0, 0], [0, 0, 0.540302305868140, 0, 0], [0, 0, 0, 0.540302305868140, 0], [0, 0, 0, 0, 0.540302305868140]]
[[-3, 2, -6], [3, 0, 4], [4, -2, 7]] -> [[-0.374786510963954, 0.135652884035570, -1.35191037980742], [1.14843105375406, 0.773644542790111, 1.21625749577185], [1.21625749577185, -0.135652884035570, 2.19338136461532]], [[4.13614256031450, -1.91289828483056, 5.50873853927692], [-2.63939111203107, 1.49675144828342, -3.59584025444636], [-3.59584025444636, 1.91289828483056, -4.96843623340878]]

Further Reading
This excellent question over at Math.SE includes some alternate derivations of the matrix-valued analogs of trigonometric functions.

I got sin([[1, 0, 1], [0, 0, 0], [0, 1, 0]]) = {{0.841, -0.158, 0.841}, {0, 0, 0}, {0, 1, 0}} with Mathematica, can you check?

@kennytm That is what the test case shows.

So it is disallowed to sum some terms of the series, because adding a finite number of terms does not give an infinitely accurate value?

@feersum Correct. Unless it converges in a finite number of terms (which it doesn't), that's not a valid approach.

@Mego Apparently all of the existing answers should be deleted then.

@feersum There are other ways to compute the matrix exponential other than just evaluating the series, such as diagonalization/Jordan decomposition. It's fair to assume that a builtin would use one of the more robust methods, rather than summing a finite number of terms of the sequence.

@Mego It's completely unreasonable to think that all of the floating-point based builtins use an exact algorithm (or one that would be exact if floating-point operations were replaced with "real number" operations).

I'm not sure I'm interpreting this discussion correctly, but irrational numbers cannot be represented exactly as decimals or floating point numbers, unless you have both infinite memory to store the representation and infinite time to calculate its value. My answer keeps adding terms of the Taylor series until the result no longer changes. It gives an inaccurate result, but its accuracy increases as the precision of the floating point type increases. Is that allowed?

@feersum I tried to make this as simple as possible when writing the challenge. Let me try stating it a different way: Use matrix exponential builtins if you want. Don't worry about inaccuracies due to limited precision with floating point values. Assume that, if your language had magical infinite-precision numeric values, the builtins would use them and everything would work like you expect.

@Dennis I'm going to allow that approach. What I specifically meant when I said that summing a finite number of terms was not valid was, if you sum some N terms of the series, where N is constant, it's not valid. If you sum terms of the series until the delta hits 0, that's valid (because N would be dependent on the precision of the numeric values, rather than a constant). Summing 5 terms and calling it good enough is not ok. Summing terms until they go below the machine/language floating point epsilon is ok.

Summing until the delta becomes zero would fail if the language did have infinite precision values as the program would not halt.

@feersum I've addressed that in my latest edit: (ignoring the fact that it would require infinite time and/or memory)

Hrm. The current conditions sound like they forbid the technique of using the recurrence (cos(x) ,sin(x)) = (2 cos(x/2)^2 - 1, 2 sin(x/2) cos(x/2)) until the argument is small enough that you can just use cos(x) = 1 - x^2/2 and sin(x) = x.

(1) I've fixed that. (2) I'm rather sure that they do. (3) The notion of well-ordering has no relation to this topic. There are plenty of norms one can put on matrices. (4) The same technique works for negative real numbers.

Julia, 33 19 bytes
A->reim(expm(A*im))

This is a function that accepts a 2-dimensional array of floats and returns a tuple of such arrays correponding to the cosine and sine, respectively. Note that this is the reverse of the order given in the test cases, in which sine is listed first.
For a real-valued matrix A, we have

and

That is, the sine and cosine of A correspond to the imaginary and real parts of the matrix exponential eiA. See Functions of Matrices (Higham, 2008).
Try it online! (includes all test cases)
Saved 14 bytes thanks to Dennis!

Mathematica, 27 bytes
{Im@#,Re@#}&@MatrixExp[I#]&

Based on @Rainer P.'s solution.
Takes the square matrix A as an argument and outputs a list containing {sin(A), cos(A)}.
The input is formatted with N to get a numerical value instead of a long exact formula and Column to display the results of sin(A) and cos(A) as separate matrices instead of a nested list.

Calculating the values separately requires 38 bytes
{(#2-#)I,+##}/2&@@MatrixExp/@{I#,-I#}&

Jelly, 23 22 bytes
³æ*÷!
®Ḥ‘©r0Ç€s2_@/µÐL

Try it online!
Background
This approach directly computes the Taylor series for sine and cosine, i.e.,

It increases the number of initial terms of both series until the result no longer changes, so its accuracy is only limited by the precision of the floating point type.
How it works
®Ḥ‘©r0Ç€s2_@/µÐL  Main link, Argument: A (matrix)

             µÐL  Loop; apply the chain until the results are no longer unique.
                  Return the last unique result.
®                   Yield the value of the register (initially zero).
 Ḥ                  Unhalve/double it.
  ‘©                Increment and copy the result (n) to the register.
    r0              Range; yield [n, ..., 0].
      Ç€            Apply the helper link to each k in the range.
        s2          Split the results into chunks of length 2. Since n is always
                    odd, this yields [[Ç(n), Ç(n-1)], ..., [Ç(1), Ç(0)]].
          _@/       Reduce the columns of the result by swapped subtraction,
                    yielding [Ç(1) - Ç(3) + ... Ç(n), Ç(0) - Ç(2) + ... Ç(n - 1)].

³æ*÷!             Helper link. Argument: k (integer)

³                 Yield the first command-line argument (A).
 æ*               Elevate A to the k-th power.
    !             Yield the factorial of k.
   ÷              Divide the left result by the right one.

C++, 305 bytes
#include<cmath>
#include<iostream>
#include<vector>
int x,i=0, j;void p(std::vector<double> v){int x=sqrt(v.size());for(i=0;i<x;i++){for(j=0;j<x;j++) std::cout << v[x] << " ";std::cout << "\n";}}int main(){std::vector<double> s, c;while(std::cin >> x){s.push_back(sin(x));c.push_back(cos(x));}p(s);p(c);}

Input is a list of numbers that are a perfect square on stdin. Output is a pretty printed 2d array on stdout

Matlab, 37 bytes
@(A){imag(expm(i*A));real(expm(i*A))}

Matlab, 138 121 52 50 bytes
Since matrix exponentiation is allowed, (what I didnt notice first, d'oh) I do not need to define my helper funciton anymore, and the whole thing can be trivially solved:
A=input('')*i;a=expm(A);b=expm(-A);[(b-a)*i,a+b]/2

The input should be a matrix e.g. [1,2;4,5] or alternatively [[1,2];[3,4]]
An unexpected thing (in hindsight not so unexpected) is that the cosine and sine matrix still satisfy
I = sin(A)^2+cos(A)^2

Isn't A^0 the same as eye(size(A))?

Oh, you're right, thank you!

Why not use expm?

Matrix exponential is not forbidden. Only matrix sine/cosine/secant/cosecant.

As per the identity: I should hope they satisfy that identity, considering that the scalar form was used to extend the functions to matrices!

Well then the whole thing becomes almost trivial.

@LuisMendo Since sinm and cosm were nto allowed, I assumed that matrix exponentiation itself wasn't allowed either.

Julia 0.4, 28 bytes
A->imag({E=expm(im*A),im*E})

Input is a matrix of floats, output is an array of matrices. Try it online!

Sage, 44 bytes
lambda A:map(exp(I*A).apply_map,(imag,real))

Try it online.
This anonymous function returns a list of 2 matrices corresponding to sin(A) and cos(A), respectively. exp(I*A) computes the matrix exponential for I*A (A with all elements multiplied by the imaginary unit), and matrix.apply_map(f) returns a matrix where f has been applied to all of its elements. By applying imag and real (the functions for getting the imaginary and real parts of a scalar value) to the matrices, we get the values of sin(A) and cos(A), thanks to Euler's famous identity (referenced in the challenge text).

Itr, 8+9=17 bytes
cosine
iäeà~e+½

sine:
iä~eàe-½i

Takes a matrix as input, also works for complex inputs
Explanation
implements the equations
\$ \sin(x)= i*\frac{e^{-ix}-e^{ix}}{2}\$
\$ \cos(x)= \frac{e^{ix}+e^{-ix}}{2}\$
i         ; i times the implicit input
 ä        ; duplicate
  ~       ; negate
   e      ; exponential
    à     ; swap
     e    ; exponential
      -   ; subtract
       ½  ; half
        i ; times i
          ; implicit output

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


text:
Write a program whose nontermination is independent of Peano arithmetic
Challenge
Write a program P, taking no input, such that the proposition “the execution of P eventually terminates” is independent of Peano arithmetic.
Formal rules
(In case you are a mathematical logician who thinks the above description is too informal.)
One can, in principle, convert some Universal Turing machine U (e.g. your favorite programming language) into a Peano arithmetic formula HALT over the variable p, where HALT(p) encodes the proposition “U terminates on the program (Gödel-encoded by) p”.  The challenge is to find p such that neither HALT(p) nor ¬HALT(p) can be proven in Peano arithmetic.
You may assume your program runs on an ideal machine with unlimited memory and integers/pointers big enough to access it.
Example
To see that such programs exist, one example is a program that exhaustively searches for a Peano arithmetic proof of 0 = 1.  Peano arithmetic proves that this program halts if and only if Peano arithmetic is inconsistent.  Since Peano arithmetic is consistent but cannot prove its own consistency, it cannot decide whether this program halts.
However, there are many other propositions independent of Peano arithmetic on which you could base your program.
Motivation
This challenge was inspired by a new paper by Yedidia and Aaronson (2016) exhibiting a 7,918-state Turing machine whose nontermination is independent of ZFC, a much stronger system than Peano arithmetic.  You may be interested in its citation [22].  For this challenge, of course, you may use your programming language of choice in place of actual Turing machines.

What axiom systems may be used to prove that (a) the program does not halt, and (b) the program's non-halting is unprovable in PA?

I don't think it's reasonable to require that this question contain all the needed background in mathematical logic. There's quite a bit of it, and there are links to the relevant info. It's not obfuscated, it's just a technical topic. I think it would help for accessibility to state the requirement for the code separate from the motivation involving Turing machines and to link to some example of Peano-independent statements to consider, in particular Goodstein's Theorem (related golf)

For this to make sense, we'd need to assume the code runs on idealized machine with unlimited memory. Can we also assume the machine has arbitrary real precision?

@feersum I am not expecting an axiomatic proof of (a) and (b). Just write a program, and provide enough description/arguments/citations to be reasonably convincing that the claims are true, as you would with any other challenge. You may rely on any standardly accepted axioms and theorems that you need.

@xnor You may assume unlimited memory, and unbounded pointers with which to access it. But I don’t think it’s reasonable to assume arbitrary real precision unless your language actually provides it; in most languages, a program like x = 1.0; while (x) { x = x / 2.0; } will actually halt very quickly.

Is randomness allowed?

@PyRulez I won’t stop you from using your language’s hash tables just because they’re seeded randomly; randomness is fine if it doesn’t change how the program works. But you don’t get to claim that your behavior is independent of PA just because you wrote if (random() < 0.5) while(true); else return;.

@AndersKaseorg I meant something like simulating Goodstein's theorem on random input (you can only prove that the function halts if Goodstein's theorem is true, otherwise there is some nonzero probability that it does not halt).

@PyRules As feersum pointed out in response to one of the deleted answers, “even if randomness is allowed I still don't think it works, because if you have a random process that can generate any natural number with nonzero probability, then you should be able to prove that the part of the program that chooses the random number can fail to terminate.” (This is essentially because the program can only branch on finitely much information during a particular computation step.)

Haskell, 838 bytes
“If you want something done, …”
import Control.Monad.State
data T=V Int|T:$T|A(T->T)
g=guard
r=runStateT
s!a@(V i)=maybe a id$lookup i s
s!(a:$b)=(s!a):$(s!b)
s@((i,_):_)!A f=A(\a->((i+1,a):s)!f(V$i+1))
c l=do(m,k)<-(`divMod`sum(1<$l)).pred<$>get;g$m>=0;put m;l!!fromEnum k
i&a=V i:$a
i%t=(:$).(i&)<$>t<*>t
x i=c$[4%x i,5%x i,(6&)<$>x i]++map(pure.V)[7..i-1]
y i=c[A<$>z i,1%y i,(2&)<$>y i,3%x i]
z i=(\a e->[(i,e)]!a)<$>y(i+1)
(i?h)p=c[g$any(p#i)h,do q<-y i;i?h$q;i?h$1&q:$p,do f<-z i;a<-x i;g$p#i$f a;c[i?h$A f,do b<-x i;i?h$3&b:$a;i?h$f b],case p of A f->c[(i+1)?h$f$V i,do i?h$f$V 7;(i+1)?(f(V i):h)$f$6&V i];V 1:$q:$r->c[i?(q:h)$r,i?(2&r:h)$V 2:$q];_->mzero]
(V a#i)(V b)=a==b
((a:$b)#i)(c:$d)=(a#i)c&&(b#i)d
(A f#i)(A g)=f(V i)#(i+1)$g$V i
(_#_)_=0<0
main=print$(r(8?map fst(r(y 8)=<<[497,8269,56106533,12033,123263749,10049,661072709])$3&V 7:$(6&V 7))=<<[0..])!!0

Explanation
This program directly searches for a Peano arithmetic proof of 0 = 1.  Since PA is consistent, this program never terminates; but since PA cannot prove its own consistency, the nontermination of this program is independent of PA.
T is the type of expressions and propositions:

A P represents the proposition ∀x [P(x)].
(V 1 :$ P) :$ Q represents the proposition P → Q.
V 2 :$ P represents the proposition ¬P.
(V 3 :$ x) :$ y represents the proposition x = y.
(V 4 :$ x) :$ y represents the natural x + y.
(V 5 :$ x) :$ y represents the natural x ⋅ y.
V 6 :$ x represents the natural S(x) = x + 1.
V 7 reprents the natural 0.

In an environment with i free variables, we encode expressions, propositions, and proofs as 2×2 integer matrices [1, 0; a, b], as follows:

M(i, ∀x [P(x)]) = [1, 0; 1, 4] ⋅ M(i, λx [P(x)])
M(i, λx [F(x)]) = M(i + 1, F(x)) where M(j, x) = [1, 0; 5 + i, 4 + j] for all j > i
M(i, P → Q) = [1, 0; 2, 4] ⋅ M(i, P) ⋅ M(i, Q)
M(i, ¬P) = [1, 0; 3, 4] ⋅ M(i, P)
M(i, x = y) = [1, 0; 4, 4] ⋅ M(i, x) ⋅ M(i, y)
M(i, x + y) = [1, 0; 1, 4 + i] ⋅ M(i, x) ⋅ M(i, y)
M(i, x ⋅ y) = [1, 0; 2, 4 + i] ⋅ M(i, x) ⋅ M(i, y)
M(i, S x) = [1, 0; 3, 4 + i] ⋅ M(i, x)
M(i, 0) = [1, 0; 4, 4 + i]
M(i, (Γ, P) ⊢ P) = [1, 0; 1, 4]
M(i, Γ ⊢ P) = [1, 0; 2, 4] ⋅ M(i, Q) ⋅ M(i, Γ ⊢ Q) ⋅ M(i, Γ ⊢ Q → P)
M(i, Γ ⊢ P(x)) = [1, 0; 3, 4] ⋅ M(i, λx [P(x)]) ⋅ M(i, x) ⋅ [1, 0; 1, 2] ⋅ M(i, Γ ⊢ ∀x P(x))
M(i, Γ ⊢ P(x)) = [1, 0; 3, 4] ⋅ M(i, λx [P(x)]) ⋅ M(i, x) ⋅ [1, 0; 2, 2] ⋅ M(i, y) ⋅ M(i, Γ ⊢ y = x) ⋅ M(i, Γ ⊢ P(y))
M(i, Γ ⊢ ∀x, P(x)) = [1, 0; 8, 8] ⋅ M(i, λx [Γ ⊢ P(x)])
M(i, Γ ⊢ ∀x, P(x)) = [1, 0; 12, 8] ⋅ M(i, Γ ⊢ P(0)) ⋅ M(i, λx [(Γ, P(x)) ⊢ P(S(x))])
M(i, Γ ⊢ P → Q) = [1, 0; 8, 8] ⋅ M(i, (Γ, P) ⊢ Q)
M(i, Γ ⊢ P → Q) = [1, 0; 12, 8] ⋅ M(i, (Γ, ¬Q) ⊢ ¬P)

The remaining axioms are encoded numerically and included in the initial environment Γ:

M(0, ∀x [x = x]) = [1, 0; 497, 400]
M(0, ∀x [¬(S(x) = 0)]) = [1, 0; 8269, 8000]
M(0, ∀x ∀y [S(x) = S(y) → x = y]) = [1, 0; 56106533, 47775744]
M(0, ∀x [x + 0 = x]) = [1, 0; 12033, 10000]
M(0, ∀y [x + S(y) = S(x + y)]) = [1, 0; 123263749, 107495424]
M(0, ∀x [x ⋅ 0 = 0]) = [1, 0; 10049, 10000]
M(0, ∀x ∀y [x ⋅ S(y) = x ⋅ y + x]) = [1, 0; 661072709, 644972544]

A proof with matrix [1, 0; a, b] can be checked given only the lower-left corner a (or any other value congruent to a modulo b); the other values are there to enable composition of proofs.
For example, here is a proof that addition is commutative.

M(0, Γ ⊢ ∀x ∀y [x + y = y + x]) = [1, 0; 6651439985424903472274778830412211286042729801174124932726010503641310445578492460637276210966154277204244776748283051731165114392766752978964153601068040044362776324924904132311711526476930755026298356469866717434090029353415862307981531900946916847172554628759434336793920402956876846292776619877110678804972343426850350512203833644, 14010499234317302152403198529613715336094817740448888109376168978138227692104106788277363562889534501599380268163213618740021570705080096139804941973102814335632180523847407060058534443254569282138051511292576687428837652027900127452656255880653718107444964680660904752950049505280000000000000000000000000000000000000000000000000000000]

You can verify it with the program as follows:
*Main> let p = A $ \x -> A $ \y -> V 3 :$ (V 4 :$ x :$ y) :$ (V 4 :$ y :$ x)
*Main> let a = 6651439985424903472274778830412211286042729801174124932726010503641310445578492460637276210966154277204244776748283051731165114392766752978964153601068040044362776324924904132311711526476930755026298356469866717434090029353415862307981531900946916847172554628759434336793920402956876846292776619877110678804972343426850350512203833644
*Main> r(8?map fst(r(y 8)=<<[497,8269,56106533,12033,123263749,10049,661072709])$p)a :: [((),Integer)]
[((),0)]

If the proof were invalid you would get the empty list instead.

Please explain the idea behind the matrices.

@proudhaskeller They’re just a convenient, relatively compact way of Gödel numbering all possible proof trees. You can also think of them as mixed-radix numerals that get decoded from the least-significant side using div and mod by the number of possible choices at each step.

How did you encode the induction axioms?

@PyRulez M(i, Γ ⊢ ∀x, P(x)) = [1, 0; 12, 8] ⋅ M(i, Γ ⊢ P(0)) ⋅ M(i, λx [(Γ, P(x)) ⊢ P(S(x))]) is the induction axiom.

I think you could make this smaller if you use Calculus of Constructions instead (since Calculus of Constructions has first-order logic built in, and is very small). Calculus of Constructions is about as strong as ZFC, so its consistency is surely independent of PA. To check if its consistient, you simply look for a term of an empty type.

Or some stronger theory with a simpler axiomization, such as ACA_0 or NBG.

There is a theory with only a binary relation ∈ and a single axiom schema that is mutually interpretable with PA: ∃z ∀w (w ∈ z ↔ (z ∈ x ∨ z = y) ∧ φ) where z is not free in φ. See axiom of adjunction. This seems like it could yield a shorter answer. Perhaps one could also search over proofs in minimal logic rather than classical logic (e.g., PA and Heyting arithmetic are equiconsistent).


text:
Continued Fraction of a Rational Number
The continued fraction of a number n is a fraction of the following form:

which converges to n.
The sequence a in a continued fraction is typically written as: [a0; a1, a2, a3, ..., an].
Your goal is to return the continued fraction of the given rational number (positive or negative), whether it is an:

integer x
fraction x/y
decimal x.yz

Input
May be a string representation, or numbers. For fractions, it may be a string, or some native data type for handling fractions, but you may not take it as a decimal.
Output
May be a delimited list or string of the convergents (the resulting numbers). The output does not have to have a semi-colon between a0 and a1, and may use a comma instead.
Note that although [3; 4, 12, 4] and [3; 4, 12, 3, 1] are both correct, only the first will be accepted, because it is simpler.
Examples:
860438      [860438]
3.245       [3; 4, 12, 4]
-4.2        [-5; 1, 4]
-114.7802   [-115; 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]
0/11        [0]
1/42        [0; 42]
2/7         [0; 3, 2]
-18/17056   [-1; 1, 946, 1, 1, 4]
-17056/18   [-948; 2, 4]

Rules

Shortest code wins.
Built-ins are allowed, but I'd also like you to post in the same answer what it would be without built-ins, so that you have to know how to do it.

Related: Determining the continued fractions of square roots

Can the input be required to be a fraction/rational type (which would require inputting the decimal 3.245 as 3245/1000 or similar)?

Mathematica wins >:|

What if there are several solutions? Is '3'    '2'    '3'    '-6' acceptable for 3.245? Also, are leading 0 convergents accepted?

@LuisMendo What method is used to find alternate solutions? The program I created only finds positive convergents.

@mbomb007 I use a Matlab function which produces negative ones. But I think the standard represwentation requires positive ones except for possibly the first

@LuisMendo Just positive only would be great, since that's easier for me to verify.

Jelly, 16 13 12 bytes
:;ç%@¥@⁶Ṗ¤%?

Try it online!

Ruby, 45 43 46 bytes
f=->n{x,y=n.to_r.divmod 1;[x,*y==0?[]:f[1/y]]}

Accepts input as a string.
All test cases pass:
llama@llama:~$ for n in 860438 3.245 -4.2 -114.7802 0/11 1/42 2/7 -18/17056 -17056/18; do ruby -e 'f=->n{x,y=n.to_r.divmod 1;[x,*y==0?[]:f[1/y]]}; p f["'$n'"]'; done
[860438]
[3, 4, 12, 4]
[-5, 1, 4]
[-115, 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]
[0]
[0, 42]
[0, 3, 2]
[-1, 1, 946, 1, 1, 4]
[-948, 2, 4]

Thanks to Kevin Lau for 2 bytes!

It hurts, to be beaten by 5 minutes and with a better solution in the same language... Hadn't thought of n%1, have a +1

At any rate, here's a tip for you: a<<n.floor should save you 2 bytes.

@KevinLau-notKenny Oh hey I learned a thing!

Rational("3.245") is not allowed, you need to include Rational in the code as the OP requested on my answer.

Correct. The internal representation of a rational is as a numerator and a denominator, so this wouldn't count as handling decimal. As a user, I would want to literally be able to pass the decimals or their string representations in the examples as the input.

@mbomb007 Fixed, input is now a string.

Ruby, 50 48 bytes
I noticed @Doorknob♦ beat me to a Ruby answer right before posting, and theirs is also shorter! As such this is just here for posterity now. Takes in a string or an integer (floats have rounding issues, so decimal values need to be put in as strings)
f=->s{s=s.to_r;[s.floor]+(s%1!=0?f[1/(s%1)]:[])}

s.floor -> s.to_i should save a byte.

@Doorknob♦ It won't. floor rounds towards -∞ while to_i truncates towards 0, so the negative test cases give the wrong results.

Nekomata, 7 bytes
ᶦ{1%ŗ}k

Attempt This Online!
A port of @Parcly Taxel's Mathematica answer.
ᶦ{1%ŗ}k
ᶦ{   }        Iterate the following function until it fails
  1%            Modulo 1
    ŗ           Reciprocal
      k       Floor

JavaScript (ES6), 52 bytes
f=(n,d)=>n%d?[r=Math.floor(n/d),...f(d,n-r*d)]:[n/d]

Accepts numerator and denominator and returns an array, e.g. f(-1147802, 1e4) returns [-115, 4, 1, 1, 4, 1, 1, 5, 1, 1, 4].

What... f=(n,d)=> is allowed??

@KennyLau That's a lambda.

I mean, it is allowed to only take fraction?

@KennyLau Input may be as a string or numbers, but not a decimal. So that was the best that I could do.

MATL, 29 bytes
`t1e7*Yo5M/kwy-t1e-5>?-1^T}xF

Try it online!
This works by repeatedly rounding and inverting (which I think is what Doorknob's answer does too). There may be numerical issues due to using floating point, but it works for all the test cases.
`         % Do...while
  t       %   Duplicate. Takes input implicitly the first time
  1e7*    %   Multiply by 1e7
  Yo      %   Round
  5M/     %   Divide by 1e7. This rounds to the 7th decimal, to try to avoid
          %   numerical precision errors
  k       %   Round
  w       %   Swap top two elements of stack
  y       %   Copy the secomnd-from-bottom element
  -       %   Subtract
  t       %   Duplicate
  1e-5>   %   Is it greater than 1e-5? (1e-5 rather than 0; this is again to
          %   try to avoid numerical precision errors)
  ?       %   If so
    -1^   %     Compute inverse
    T     %     Push true as loop condition (to start a new iteration)
  }       %   Else
    xF    %     Delete and push false (to exit loop)
          %   End if implicitly
          % End do...while implicitly
          % Display implicitly

Java, 85 83 bytes
String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));}

Takes integer or fraction or decimal as String, 311 bytes
String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));String[]a=i.split("/");int n=Integer.decode(a[0]),d=Integer.decode(a[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}}

Sample input/output:
860438
860438

3.245
3,4,12,4

-4.2
-5,1,4

-114.7802
-115,4,1,1,4,1,1,5,1,1,4

0/11
0

1/42
0,42

2/7
0,3,2

-18/17056
-1,1,946,1,1,4

-17056/18
-948,2,4

Actual input/output from full program:
860438
860438
860438
860438
860438
3.245
3,4,12,4
3,4,12,4
3,4,12,4
3,4,12,4
-4.2
-5,1,4
-5,1,4
-5,1,4
-5,1,4
-114.7802
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
0/11
0
0
0
0
1/42
0,42
0,42
0,42
0,42
2/7
0,3,2
0,3,2
0,3,2
0,3,2
-18/17056
-1,1,946,1,1,4
-1,1,946,1,1,4
-1,1,946,1,1,4
-1,1,946,1,1,4
-17056/18
-948,2,4
-948,2,4
-948,2,4
-948,2,4

Full program (including ungolfed functions):
import java.util.Scanner;

public class Q79483 {
    String cf_ungolfed(String input){
        try{
            int result = Integer.parseInt(input);
            return Integer.toString(result);
        }catch(Exception e){
            if(input.indexOf('.')>=0){
                int numerator = Integer.parseInt(input.replaceAll("\\.",""));
                int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1);
                return cf_ungolfed(numerator+"/"+denominator);
            }
            int numerator = Integer.parseInt(input.substring(0,input.indexOf('/')));
            int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1));
            if(numerator%denominator == 0){
                return Integer.toString(numerator/denominator);
            }
            if(numerator < 0){
                return "-"+cf_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator)))+"/"+denominator);
            }
            return (numerator/denominator) + "," + cf_ungolfed(denominator+"/"+(numerator%denominator));
        }
    }
    String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));int n=Integer.decode(i.split("/")[0]),d=Integer.decode(i.split("/")[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}}
    String f_ungolfed(int numerator,int denominator){
        if(numerator%denominator == 0){
            return Integer.toString(numerator/denominator);
        }
        if(numerator < 0){
            return "-"+f_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator))),denominator);
        }
        return (numerator/denominator) + "," + f_ungolfed(denominator,(numerator%denominator));
    }
    String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));}
    public static int[] format(String input){
        if(input.indexOf('.') != -1){
            int numerator = Integer.parseInt(input.replaceAll("\\.",""));
            int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1);
            return new int[]{numerator,denominator};
        }
        if(input.indexOf('/') != -1){
            int numerator = Integer.parseInt(input.substring(0,input.indexOf('/')));
            int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1));
            return new int[]{numerator,denominator};
        }
        return new int[]{Integer.parseInt(input),1};
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String input = sc.next();
            System.out.println(new Q79483().cf_ungolfed(input));
            System.out.println(new Q79483().c(input));
            int[] formatted = format(input);
            System.out.println(new Q79483().f_ungolfed(formatted[0], formatted[1]));
            System.out.println(new Q79483().f(formatted[0], formatted[1]));
        }
        sc.close();
    }
}

Don't catch errors, throw them.

Why is each test case output four times?

@mbomb007 Because I called four functions. Look at the last few lines of the full program.

@mbomb007 Done.

Wolfram Language (Mathematica), 43 bytes
-4 from alephalpha
Floor@NestWhileList[1/t&,#,(t=#~Mod~1)>0&]&

Try it online!

Glad to see when someone answers on an old question of mine.

Floor@NestWhileList[1/t&,#,(t=#~Mod~1)>0&]&

Pyth, 15 bytes
M+]/GH?J%GHgHJY

Try it online! (The g.* at the end is to fetch the input.)

APL(NARS), 107 chars, 214 bytes
dd←{⍵=0:0⋄0>k←1∧÷⍵:-k⋄k}⋄nn←{1∧⍵}⋄f←{⍵=0:0x⋄m←⎕ct⋄⎕ct←0⋄z←{0=(d←dd⍵)∣n←nn⍵:n÷d⋄r←⌊n÷d⋄r,∇d÷n-r×d}⍵⋄⎕ct←m⋄z}

The function of the exercise f, should have as input one rational number (where 23r33 means as "23/33" in math)
...The algo is the same of the one Neil posted as JavaScript solution... test
  f 860438r1
860438
  f 3245r1000
3 4 12 4
  f ¯42r10
¯5 1 4
  f ¯1147802r10000
¯115 4 1 1 4 1 1 5 1 1 4
  f 0r11
0
  f 1r42
0 42
  f 2r7
0 3 2
  f ¯18r17056
¯1 1 946 1 1 4
  f ¯17056r18
¯948 2 4
  f 17056r¯18
¯948 2 4
  f 18r¯17056
¯1 1 946 1 1 4
  f 123r73333333333333333333333333373
0 596205962059620596205962059 1 16 1 1 3
  +∘÷/f 123r73333333333333333333333333373
123r73333333333333333333333333373

Python 3, 46 bytes
f=lambda n,d:[n//d]+(n%d*[0]and f(d,n-n//d*d))

Try it online!
Port of Neil's javascript answer

Scala, 72 bytes
Golfed version. Try it online!
(n,d)=>if(n<0)"-"+f(2*(d+n%d)-n,d)else n/d+(if(n%d<1)""else","+f(d,n%d))

C# (Visual C# Interactive Compiler), 222 bytes/75 bytes
A function that takes a string, 222 bytes
(a,o)=>{var@b=$"{a}/1".Split("/");var@c=$"{b[0]}.0".Split(".");int@n=int.Parse(c[0]),m=int.Parse(c[1]),d=1,r;for(;d<m;d*=10);for(n=n*d+(n>0?1:-1)*m,d*=int.Parse(b[1]);d>0;(n,d)=(d,n-r*d))o.Add(r=(int)Math.Floor(1m*n/d));};

Try it online!
Just the part that takes numerator and denominator, 75 bytes
(n,d,o)=>{for(int@r;d>0;(n,d)=(d,n-r*d))o.Add(r=(int)Math.Floor(1m*n/d));};

Try it online!
Un-golfed code:
(input, output) =>
{
	var fracStr = $"{input}/1".Split("/"); // append "/1" so we never get an array out of bounds
	var decStr = $"{fracStr[0]}.0".Split("."); // append ".0" so we never get an array out of bounds

	// parse the decimal number first,
	// if we weren't passed a decimal, m will be 0
	int n = int.Parse(decStr[0]);
	int m = int.Parse(decStr[1]);
	int d = 1;

	// denominator will be the next power of 10 larger than m:
	for (; d < m; d *= 10);

	// scale the numerator by the denominator, and add the decimal part:
	n = n * d + (n > 0 ? 1 : -1) * m;

	// now handle the fraction case
	// if we weren't passed a fraction then fracStr[1] will be "1"
	// if we were passed a fraction, d will be 1
	d *= int.Parse(fracStr[1]);

	// now actually calculate the continued fraction:
	for (; d > 0; )
	{
		int r = (int)Math.Floor(1m * n / d);
		output.Add(r);
		(n, d) = (d, n - r * d);
	}
};