text:
Write a book writer
Here is a fairly simple ASCII depiction of an open book:
|\
| \
|  \
|   \
|    \__________
|    ||         |
|    || Lorem i |
\    || psum do |
 \   || lor sit |
  \  ||  amet,  |
   \ || consect |
    \||_________|

Notice that the text portion is only on the right page and is 7 characters wide by 5 tall. Also notice that the top edge of the book has 5 backslashes and 10 underscores. The 10 comes from the text width plus 3 and the 5 is half of 10.
Using the same scaling format we can resize the book to have a text area w characters wide and h high, where w is any odd positive integer and h is any positive integer.
Some w×h books: 1×1, 1×2, 3×2
                    |\
          |\        | \
|\        | \____   |  \______
| \____   | ||   |  |  ||     |
| ||   |  | || L |  \  || Lor |
\ || L |  \ || o |   \ || em  |
 \||___|   \||___|    \||_____|

The number of underscores at the top is always w+3 and the number of backslashes is always (w+3)/2.
Goal
Write a progam that takes a filename and w and h as command line arguments, and outputs a book with those text dimensions to stdout, displaying the contents of the file.
When the file has more text than will fit in one page the N key should print the next page and B should go back a page. Nothing should happen if B is pressed from the first page or N is pressed from the last page. The program should stop when the Q key is hit.
Example
Suppose f.txt contains Lorem ipsum dol? and the user has pressed the key sequence N N B N N Q. The program should run something like this:
>>> bookmaker f.txt 3 2
|\
| \
|  \______
|  ||     |
\  || Lor |
 \ || em  |
  \||_____|

|\
| \
|  \______
|  ||     |
\  || ips |
 \ || um  |
  \||_____|

|\
| \
|  \______
|  ||     |
\  || dol |
 \ || ?   |
  \||_____|

|\
| \
|  \______
|  ||     |
\  || ips |
 \ || um  |
  \||_____|

|\
| \
|  \______
|  ||     |
\  || dol |
 \ || ?   |
  \||_____|

>>>

Notice that there is a newline after every book and no trailing spaces. This is required.
Notes

You may assume the file only contains printable ASCII characters (hex 20 to 7E).
Print one character in each available spot, regardless of word boundaries.
w and h are optional arguments that default to 7 and 5 respectively. Your program will either be given neither or both. (You may assume input is always well formed.)
Fill any empty text space on the last page with spaces.
Q should still be required to quit if there is only one page.

Winning
The shortest program in bytes after bonuses are applied wins.
Bonuses

Remove leading spaces so that every line starts with a word (or word segment). e.g. |  amet,  | in the first example would become | amet, c |. (-30 bytes)
Clear the screen of previously drawn books after N or B is pressed (and T if you do the bonus after this) so the book looks like its changing pages in place. (-20 bytes)
Make the T key instantly toggle between the text being drawn from left-to-right top-to-bottom (the default), to top-to-bottom left-to-right. If you did the first bonus it should work for columns in the top-to-bottom mode. (-100 bytes)
So for example:
|\
| \
|  \______
|  ||     |
\  || Lor |
 \ || em  |
  \||_____|

becomes
|\
| \
|  \______
|  ||     |
\  || Lrm |
 \ || oe  |
  \||_____|

the "clear the screen" bonus seems to be a language bonus rather than a code bonus...

You say in text that the filename and book dimensions come from STDIN, but then you proceed to take them as arguments. Which is it, then?

I have noticed, thanks to your notice, that there are no trailing spaces. But are we required not to include them either?

@JanDvorak Sorry, I meant they are only arguments. You you need to have NO trailing spaces. Can you give an example of where the clearing becomes a "code bonus"?

by "language bonus" I mean that the bonus is, based on the language, either not possible, clearly not worth it, or trivial to implement for a cheap point discount.

@JanDvorak Well that's the way it's gonna stay. :P

An example of T bonus?

does the trim bonus only need to work in row mode, or also in column mode?

@edc65 Added. Yes to the trim working in column mode.

@JanDvorak, it seems to me to be more a "run the program in a POSIX terminal" bonus. \033[2J\033[;H

C# 535bytes
Score is 655bytes of code -20byte bonus for clearing, and -100byte bonus for T key... I think, can't say I'm sure I haven't missed something in the spec
I may try and collapse the loops by having the W method return the s argument, but that would require effort, so no promises.
Golfed code:
using C=System.Console;using K=System.ConsoleKey;class P{static void W(int x,int y,string s){C.SetCursorPosition(x,y);C.Write(s);}static void Main(string[]a){int b=a.Length,w=b>0?int.Parse(a[0]):7,h=b>1?int.Parse(a[1]):5,p=0,i,j,o,T=1;var F=System.IO.File.ReadAllText("f.txt");b=(w+3)/2;S:C.Clear();for(i=0;i<w+3;i++){W(o=i+b+1,b-1,"_");W(o,h+b+1,"_");}for(i=0;i<h+2;){W(0,i,"|");W(b,o=i+++b,"||");W(b+w+4,o,"|");}for(i=0;i<b;){W(i+1,i,"\\");W(i,++i+h+1,"\\");}for(i=0;i<w;i++)for(j=0;j<h;)if((o=T>0?j++*w+p+i:i*h+p+j++)<F.Length)W(i+b+3,j+b,F[o]+"");K k=C.ReadKey(1>0).Key;p+=k==K.N&p<F.Length-w*h?w*h:k==K.B&p>0?-w*h:0;T=k!=K.T?T:-T;if (k!=K.Q)goto S;}}

Formatted a bit:
using C=System.Console;
using K=System.ConsoleKey;

class P
{
    static void W(int x,int y,string s)
    {
        C.SetCursorPosition(x,y);
        C.Write(s);
    }

    static void Main(string[]a)
    {
        int b=a.Length,w=b>0?int.Parse(a[0]):7,h=b>1?int.Parse(a[1]):5,p=0,i,j,o,T=1;
        var F=System.IO.File.ReadAllText("f.txt");
        b=(w+3)/2;

    S:
        C.Clear();

        for(i=0;i<w+3;i++)
        {
            W(o=i+b+1,b-1,"_");
            W(o,h+b+1,"_");
        }

        for(i=0;i<h+2;)
        {
            W(0,i,"|");
            W(b,o=i+++b,"||");
            W(b+w+4,o,"|");
        }

        for(i=0;i<b;)
        {
            W(i+1,i,"\\");
            W(i,++i+h+1,"\\");
        }

        for(i=0;i<w;i++)
            for(j=0;j<h;)
                if((o=T>0?j++*w+p+i:i*h+p+j++)<F.Length)
                    W(i+b+3,j+b,F[o]+"");

        K k=C.ReadKey(1>0).Key;
        p+=k==K.N&p<F.Length-w*h?w*h:k==K.B&p>0?-w*h:0;
        T=k!=K.T?T:-T;
        if (k!=K.Q)
            goto S;
    }
}

Java, 1039 1001 993 953 946
With bonus:
Remove leading spaces (-30 bytes)
-> 1009 971 963 923 916
Clearing the screen is not worth it with java (except if I just print a couple of newlines. But then the user has to use the correct console size)
Code:
import java.io.*;import java.util.*;class B {static int w=7,h=5,p,l;static String t="",o,u=" ",y="\\";public static void main(String[]c)throws Exception{if(c.length>1){w=Integer.valueOf(c[1]);h=Integer.valueOf(c[2]);}Scanner s=new Scanner(new FileReader(c[0]));while(s.hasNext()){t+=s.nextLine();}l=t.length();s = new Scanner(System.in);while(true){int q=w+3,z=q/2,i=0,j=0,a=w*h;o="";for(;i<z;i++)o+="\n|"+r(u,i)+y;o+=r("_", q);for(;j<h+2-z;j++){o+="\n|"+r(u,i-1)+"||";if(j==0)o+=r(u,w+2);else o+=u+t()+u;o+="|";}for(;i>0;i--){o+="\n"+r(u,z-i)+y+r(u,i-1)+"||";if(i>1)o+=u+t()+" |";}o+=r("_",w+2)+"|";System.out.print(o);switch(s.next().charAt(0)){case'Q':return;case'B':p=p>a?p-2*a:p-a;break;case'N':p=p>l?p-a:p;}}}static String t(){int e=p+w>l?l:p+w;String r="";if(p<=e)r=t.substring(p,e);r=r.replaceAll("^\\s+","");int y=r.length();p+=w;return y==w?r:r+r(u,w-y);}static String r(String s,int i){return new String(new char[i]).replace("\0",s);}

Pretty:
import java.io.*;import java.util.*;
class B {
    static int w=7,h=5,p,l; // w = text width, h = text height, p = current position in text
    static String t="",o,u=" ",y="\\";
    public static void main(String[]c)throws Exception{
        // get w and h of text, default to 7x5
        if(c.length>1){w=Integer.valueOf(c[1]);h=Integer.valueOf(c[2]);}
        // read file
        Scanner s=new Scanner(new FileReader(c[0]));while(s.hasNext()){t+=s.nextLine();}
        l=t.length();
        // read input
        s = new Scanner(System.in);
        while(true){
            // print book
        int q=w+3,z=q/2,i=0,j=0,a=w*h; // q = number of underscores at the top, z = number of backslashes
        o="";
        // print top of book
        for(;i<z;i++)o+="\n|"+r(u,i)+y;
        o+=r("_", q);
        // print middle of book (hp-z lines). right now: i = z -1
        for(;j<h+2-z;j++){o+="\n|"+r(u,i-1)+"||";if(j==0)o+=r(u,w+2);else o+=u+t()+u;o+="|";}
        // print bottom of book
        for(;i>0;i--){o+="\n"+r(u,z-i)+y+r(u,i-1)+"||";if(i>1)o+=u+t()+" |";}
        o+=r("_",w+2)+"|";
        System.out.print(o);
        // user input
            switch(s.next().charAt(0)){
                case'Q':return;
                case'B':p=p>a?p-2*a:p-a;break;
                case'N':p=p>l?p-a:p;
            }
        }
    }

    /** return w characters of string t, from given position p. increase p*/
    static String t(){
        int e=p+w>l?l:p+w;
        String r="";
        if(p<=e)r=t.substring(p,e);
        r=r.replaceAll("^\\s+",""); // remove leading spaces (cost:28 chars)
        int y=r.length();
        p+=w;
        return y==w?r:r+r(u,w-y);
    }
    static String r(String s,int i){return new String(new char[i]).replace("\0",s);} // repeat given string i times

If the program does not have to run forever, I could also save some bytes by removing the while loop and just calling main.
This is not optimal, but it's a start.

I'm pretty sure you don't need the public keywords... Also, does import java.*; work?

@professorfish I thought about import java.*; as well, but it doesn't work. And the main method does need to be exactly public static void main(String[]c) (including public), otherwise it is not recognized. But the class of course doesn't need to be public, good catch.

source: Stack Exchange

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

sort: votes


text:
Simplify a fraction
Winner: Ian D. Scott's answer, by one byte (48 bytes)! Superb!
Your program must accept input from a fraction that can be simplified, then simplify it.
Rules:

If the fraction is already in its most simplified form, you must inform the user
No built-in functions to do this
The user must type the number at some point, however the method the program reads it does not matter. It can be with stdin, console.readline, etc. As long as the user types 9/18 (for example) at some point, it is valid
Output must be done with stdout, console.writeline, etc...
The fraction will be put in as x/y, and must output as a/b
The fraction must output the most simplified form. For example, 8/12 -> 6/9 is not valid, the only valid solution is 2/3.

This contest ends on August 9th, 2014 (7 days from posting)
This is a code-golf question, so the shortest code wins

How should we inform the user?

Stdout, console.writeline, etc.

This is really quite a trivial problem. All you do is divide by the gcd (a function that is often built in but would not be hard to write).

@Calvin'sHobbies Yeah, the problem itself is trivial. Doing it in the shortest amount of code isn't as easy.

What do you mean by "If the fraction is already in its most simplified form, you must inform the user"? Should there be a specific message apart from just returning the input? If so, I don't the the accepted answer satisfies this.

I honestly think Python shouldn't use the fractions.py module for this.

Python - 69 48
The first thing to do is to represent it in python's native format for storing fractions, namely the Fraction class.
print(__import__("fractions").Fraction(input()))

Now we simplify... but look! It's already simplified.
Does this count as using a built-in function?  It is not intended specifically for simplifying, and Fraction is a class anyway, not a function.
I didn't call any simplifying function, so it's not my fault if python decides to do it itself.

But the constructor of that class is a function?

@flawr type(fractions.Fraction.__init__) returns wrapper_descriptor rather than function, so you could say it is not a function. This actually just means it is implemented in c, but anything not in class function is not a function, right?

-1: this is a built-in. While it doesn't say "simplify" in the name, it simplifies fractions.

><> (92)
0v
+>>>>>>a*ic4*-:0(?v
v@:{:~^?=2l0  ,a~ <
>:?!v:@%
=1:~<;no-1*4c,n,@:/?
|oooo;!'simplest' /

I know I can get this lower, I'll golf it a bit more in the morning.
Basic explanation:
First two lines, and the latter half of the third, are all for reading numbers. Sadly, ><> has no way to do that, so the parsing takes up half the program.
4th line is a simple iterative gcd calculation. I'm surprised at how well ><> did on byte count for the actual algorithm. If it wasn't for the terrible i/o, it could actually be a reasonable golf language.
Last two lines are just for printing the result and dividing the original numbers by the gcd.

you actually did better that everyone except the golfscript one. nice!

not longer true :-(

GolfScript, 49 characters
'/'/{~}%.~{.@\%.}do;:G({{G/}%'/'*}{;'simplest'}if

Run the two testcases here:
> 8/12
2/3

> 7/12
simplest

JavaScript 101
For once, a solution not using EcmaScript 6
v=prompt().split('/');for(a=v[0]|0,b=v[1]|0;a-b;)a>b?a-=b:b-=a;
alert(a>1?v[0]/a+'/'+v[1]/a:'Reduced')

But with E6 could be 93
[n,d]=prompt().split('/');for(a=n|0,b=d|0;a-b;)a>b?a-=b:b-=a;
alert(a>1?n/a+'/'+d/a:'Reduced')

for([a,b]=[c,d]=prompt().split('/');b;[a,b]=[b,a%b]);alert(a-1?c/a+'/'+d/a:'Reduced'); 86 i hope it's mathematically correct...

PHP>=7.1, 76 Bytes
for([$x,$y]=explode("/",$argn),$t=1+$x;$y%--$t||$x%$t;);echo$x/$t."/".$y/$t;

Online Version

Python 2.7, 124
from fractions import gcd;x,y=map(int,raw_input().split('/'));g=gcd(x,y);print'%d/%d'%(x/g,y/g)if g!=1 else'Already reduced'

Very simple solution, though I know it would be shorter in many other languages.
I used an imported gcd but if it counts as a built-in fraction reducer it could be implemented directly.

Python 2 (82)
A,B=a,b=map(int,raw_input().split("/"))
while b:a,b=b,a%b
print`A/a`+"/"+`B/a`,a<2

Prints a Boolean afterward to say whether the original was in simplest form. Just does the usual GCD algorithm. Most of the characters are spent on input/output.

Wouldn't it be shorter to use Python 3 for input()?

@mbomb007 It's been a while, but I think the 4 chars saved on that are more than lost by Python 3 needing parens around print, the map being unpacked, and maybe integer rather than float division.

Forgot about the division. That alone would make it 'not worth.' What do you mean about map being unpacked?

@mbomb007 My mistake, a,b=map(int,...) doesn't require any extra chars since a,b=... unpacks automatically. The problem you sometimes run into with Python 3 is that map doesn't produce a list but a map object that requires turning into a list before you can do something like slice it. An expression like *l,=map(...) is needed to assign l as a list instead.

C, 94
Just brute force guess and check, for GCD starting at a|b down to 1;
main(a,b,c){scanf("%d/%d",&a,&b);for(c=a|b;--c;)if(a%c+b%c<1)a/=c,b/=c;printf("%d/%d\n",a,b);}

83: c;d;f(a,b){b?f(b,a%b):printf("%d/%d",c/a,d/a);}main(){scanf("%d/%d",&c,&d);f(c,d);}

Vyxal, 0 bytes

Try it Online!
Yes. It really is 0 bytes. It doesn't use any built-in functions, as inputted fractions are simplified by default.
The benefits of using rational numbers internally!

thinks of same answer, scrolls down, sees the top answer and sighs.

ARBLE, 54 bytes
(a/c.."/"..b/c)(a,b,index(range(a+b,1)&nt(a%c+b%c),1))

Explained
(a/c.."/"..b/c)(a,b,index(range(a+b,1)&nt(a%c+b%c),1))
                          range(a+b,1)                  -- All numbers from (a+b) down to 1.
                                      &                 -- Filter
                                       nt(a%c+b%c)      -- Both a and b divisible by the iterator
                    index(                        ,1)   -- Get the first value (Naturally the highest)
(             )(a,b,                                 )  -- Pass a, b, and the gcd of a and b to the stringifier
 a/c.."/"..b/c                                          -- Format as a fraction.
                                                        -- Returns a two argument function.

Takes input as two numbers. Outputs as 1.0/2.0. The trailing .0 can be removed for +2 bytes by replacing (a/c.."/"..b/c) with (a//c.."/"..b//c)
Try it online!

JavaScript (91) (73)
Returns '/' when the fraction is already in it's simplest form. The function g calculates the gcd. BTW: Is there any shorter way for '1==something' where something is a non negative integer?
function s(f){[n,m]=f.split(b='/');g=(u,v)=>v?g(v,u%v):u;return 1==(c=g(n,m))?b:n/c+b+m/c;}
Thanks to @bebe for an even shorter version:
s=f=>([n,m]=f.split(b='/'),c=(g=(u,v)=>v?g(v,u%v):u)(n,m))-1?n/c+b+m/c:f;

use es6 consistently. call your function s=f=>... then assign g when using it (g=...)(n,m) then pass it to c and test if it equals to 1 by c-1?not_equals:equals and try to avoid using return. result: s=f=>([n,m]=f.split(b='/'),c=(g=(u,v)=>v?g(v,u%v):u)(n,m))-1?n/c+b+m/c:f; 73 (returns the simplest form (f) if it cannot be reduced)

Wow thats great! I could not think of a way to pack the shole thing into one statement thats why I used function and return. And thanks for the -1=)

Batch - 198
for /f "tokens=1,2delims=/" %%a in ("%1")do set a=%%a&set b=%%b&set/ac=%%b
:1
set/ax=%a%%%%c%&set/ay=%b%%%%c%
if %x%%y%==00 set/aa/=%c%&set/ab/=%c%
if %c% GTR 0 set/ac=%c%-1&goto 1
echo %a%/%b%

Input is split as a/b, then for every c in b,b-1,...1 we check if a and b are divisible by c, and divide them by c if they are. Then we return a/b

Befunge 93 (192)
&04p~$&14p2       > :24p  v       >34g#v_0"tselpmiS">:#,_@
>134p 24g>        ^+1g42$<>04g`   |    >04g."/",14g.@
^p41/g42p40/g42<         |%g42:g41<
         #     |!%g42:g40<
   0     ^+1g42<

Rebmu (104 characters)
P"/"rSst[a b]paSp AtiA BtiB Ca DbFOiMNcD 1 -1[izADmdCiMDdI[CdvCi DdvDi]]QapAPtsCpTSdIa^e?aCe?bD[Q"Err"]Q

Unmushed:
P"/"
rS
; extract numerator to a, denominator to b
st [a b] pa s p
; convert a,b to integers
AtiA
BtiB
; set c=a, d=b
Ca Db
; loop from min(c,d) to 1
fo i mn c d 1 -1[
    ; check if (c mod i) + (d mod i) is 0
    iz ad md c i md d i [
        ; divide c, d by i
        Cdv c i
        Ddv d i
    ]
]
; set Q to c/d
Qap ap ts c p ts d
; check if a==c and b==d
i a^ e? a c e? b d[
    ; set q to "err"
    Q"err"
]
; print q
Q

PHP 156
meh.
$f=$argv[1];$p=explode('/',$f);$m=max(array_map('abs',$p));for(;$m;$m--)if(!($p[0]%$m||$p[1]%$m)){$r=$p[0]/$m.'/'.$p[1]/$m;break;}echo $r===$f?'reduced':$r;

Run:
php -r "$f=$argv[1];$p...[code here]...:$r;" 9/18;
1/2

prints "reduced" if the fraction is already in its simplest form
works with negative fractions
works with improper fractions (e.g. 150/100 gives 3/2)
kinda works with decimals (e.g. 1.2/3.6 gives 0.75/2.25)
99/0 incorrectly gives 1/0 ?
won't reduce to a whole number (e.g. 100/100 gives 1/1)

Here's an ungolfed version with some testing (modified into function form):
<?php
$a = array(
    '9/18','8/12','50/100','82/100','100/100','150/100','99/100',
    '-5/10','-5/18','0.5/2.5','1.2/3.6','1/0','0/1','99/0'
);
print_r(array_map('r',array_combine(array_values($a),$a)));

function r($f) {
    $p = explode('/',$f);
    $m = max(array_map('abs',$p));
    for ( ; $m; $m-- )
        if ( !($p[0] % $m || $p[1] % $m) ) {
            $r = $p[0]/$m.'/'.$p[1]/$m;
            break;
        }
    return $r === $f ? 'reduced' : $r;
}
/*
Array(
    [9/18] => 1/2
    [8/12] => 2/3
    [50/100] => 1/2
    [82/100] => 41/50
    [100/100] => 1/1
    [150/100] => 3/2
    [99/100] => reduced
    [-5/10] => -1/2
    [-5/18] => reduced
    [0.5/2.5] => 0.2/1
    [1.2/3.6] => 0.75/2.25
    [1/0] => reduced
    [0/1] => reduced
    [99/0] => 1/0
)
*/
?>

Java, 361 349 329 (thanks @Sieg for the int tip)
class P{public static void main(String[]a){String[]e=a[0].split("/");String f="";int g=new Integer(e[0]),h=new Integer(e[1]);if(g>h){for(int i=h;i>=1;i--){if(g%i==0&&h%i==0){f=g/i+"/"+h/i;break;}}}else if(g<h){for(int i=g;i>=1;i--){if(g%i==0&&h%i==0){f=g/i+"/"+h/i;break;}}}else if(g.equals(h)){f="1/1";}System.out.println(f);}}

I know it's not short, but I'm just mesmerized of what I did.
To use it, compile the code and run it passing the arguments through the command-line.

Integers only (I'm not into doubles and the task doesn't require it).
If the fraction is already simplified, returns itself.
Doesn't work with negative fractions.
Dividing by zero? No cookie for you (Returns an empty string).

Ungolfed (if anyone wants to see this mess):
class P{
    public static void main(String[]a){
        String[]e=a[0].split("/");
        String f="";
        int g=new Integer(e[0]),h=new Integer(e[1]);
        if(g>h){
            for(int i=h;i>=1;i--){
                if(g%i==0&&h%i==0){
                    f=g/i+"/"+h/i;
                    break;
                }
            }
        }else if(g<h){
            for(int i=g;i>=1;i--){
                if(g%i==0&&h%i==0){
                    f=g/i+"/"+h/i;
                    break;
                }
            }
        }else if(g.equals(h)){
            f="1/1"; //no processing if the number is THAT obvious.
        }
        System.out.println(f);
    }
}

You really should use int instead of Integer, even in production code. Int is allocated from the stack, while integer is from the heap.

@Sleg Well, I didn't knew that, thank you very much.

Then something you should not use in production. Just calling new Integer(str) will have the same result as Integer.parseInt(str). Also, why not use String f="" (always)?

@Sieg Thanks again, but why is that? I know that new Integer(str) creates a Integer out of a string, but doesn't Integer.parseInt(str) do the same thing? And the thing with String f="", I know that I should use it over String f=new String(), but I don't know why I don't, maybe it's a bad habit :P

Integer.parseInt indeed does the same thing, but with some cached values for faster lookup.

@Sieg Oh, thanks. So new Integer() uses less memory, right?

If the docs are to be trusted, yes. parseInt is faster and preferred though.

Also, new Integer creates an unnecessary heap reservation, which instantly gets GC'd.

Ruby — 112 characters
g is a helper lambda that calculates the GCD of two integers. f takes a fraction as a string, e.g. '42/14', and outputs the reduced fraction or simplest if the numerator and denominator are relatively prime.
g=->a,b{(t=b;b=a%b;a=t)until b==0;a}
f=->z{a,b=z.split(?/).map &:to_i;y=g[a,b];puts y==1?:simplest:[a/y,b/y]*?/}

Some test cases:
test_cases = ['9/18', '8/12', '50/100', '82/100', '100/100',
              '150/100', '99/100', '-5/10', '-5/18', '0/1']

test_cases.map { |frac| f[frac] }

Output:
1/2
2/3
1/2
41/50
1/1
3/2
simplest
-1/2
simplest
simplest

Note, although against the rules, Ruby has Rational support baked in, so we could do
a=gets.chomp;b=a.to_r;puts b.to_s==a ?:simplest:b

Lua - 130 115 characters
10/10 i really tried
a,b=io.read():match"(.+)/(.+)"u,v=a,b while v+0>0 do t=u u=v v=t%v end print(a+0==a/u and"reduced"or a/u.."/"..b/u)

prints "reduced" if fraction is in simplest form
works with negatives
works with improper fractions
presumably works with decimals (1.2/3.6 gives 5.4043195528446e+15/1.6212958658534e+16)
any number/0 gives 1/0
does not reduce to whole numbers

I fully took advantage of Lua's ability to auto convert a string to a number when doing arithmetic operations on a string. I had to add "+0" in place of tonumber for some comparison code.
Sorry, I don't have an ungolfed version, the above is actually how I wrote it

C 135
Accepts input for 2 space-separated integers. Keeps dividing by minimum of a & b down to 1 to find GCD.
int a,b,m;
void main()
{
scanf("%d %d", &a, &b);
m=a<b?a:b;
for (;m>0;m--){if (a%m==0&&b%m==0)break;}
printf("%d/%d",a/m,b/m);
}

Java (200)
The previous best solution in Java still had >300 bytes, this one has 200:
class M {public static void main(String[]args){String[]s=args[0].split("/");int a=Integer.parseInt(s[0]),b=Integer.parseInt(s[1]),c=a,d=b;while(d>0){int g=c;c=d;d=g%d;}System.out.print(a/c+"/"+b/c);}}

This uses the (faster) modulo to determine the gcd instead of iterating all numbers.

You can remove the space after class M

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

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


text:
Quoting Big Brother
Task: Have your program randomly choose one of the following two quotes at runtime and print that one quote, exactly as shown.
1:
Under the spreading chestnut tree
I sold you and you sold me.
There lie they, and here lie we
Under the spreading chestnut tree.

2:
WAR IS PEACE.
FREEDOM IS SLAVERY.
IGNORANCE IS STRENGTH.

Restrictions: The words spreading, chestnut, PEACE, FREEDOM, and STRENGTH must appear in your code. No word from the above two quotes may appear in your code more than once.
Shortest solution wins.

Ok I choosed the first. Honest! http://xkcd.com/221/

@edc65 That's no longer funny.

@MartinBüttner not to be funny, but to suggest a more explicit rule. Reading first time I really tought I could choose a random one and then start to work.

@edc65 Ah I see, the wording used to be different.

PHP 179
Inspired by es1024's answer.
<?=strtr(rand()%2?"0
I 1 232 1 me.
T5 they,35 we
0.
":"WAR4PEACE.
FREEDOM4SLAVERY.
IGNORANCE4STRENGTH.
",["Under the spreading chestnut tree",sold,you," and "," IS ","here lie"]);

Perl (191 184 characters)
$_=$$&1?"0
I12321me6T4they,34we
06":"WAR5PEACE6FREEDOM5SLAVERY6IGNORANCE5STRENGTH6";s/\d/("Under the spreading chestnut tree"," sold ",you," and ","here lie "," IS ",".
")[$&]/ge;print

Thanks @core1024 for tips on golfing this.

You can replace 6 with actual new lines, drop the quotes around "you" and use $$&1 as a random generator :)

Java, 338
I can't get it below 338...
class B{public static void main(String[]a){String b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=".\n",i=" IS ";if(Math.random()>.5)System.out.print(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+h);else System.out.print("WAR"+i+"PEACE"+h+"FREEDOM"+i+"SLAVERY"+h+"IGNORANCE"+i+"STRENGTH"+h);}}

Bit ungolfed:
class B{public static void main(String[]a){String b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=".\n",i=" IS ";
if(Math.random()>.5)System.out.print(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+h);
else System.out.print("WAR"+i+"PEACE"+h+"FREEDOM"+i+"SLAVERY"+h+"IGNORANCE"+i+"STRENGTH"+h);}}

Yes you can http://codegolf.stackexchange.com/questions/6671/tips-for-golfing-in-java.

Thanks for the link! Gonna search for something useful tomorrow.

@Fabinout I've tried a few tricks, but they didn't help. (java.io.PrintStream p=System.out, added 15 bytes to total, static<T>void p(T o){System.out.print(o);}, added 12). Any other suggestions?

use static block instead of a main declaration

Static block *310 CHAR *: class B{static{String b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=".\n",i=" IS ";if(Math.random()>.5)System.out.print(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+h);else System.out.print("WAR"+i+"PEACE"+h+"FREEDOM"+i+"SLAVERY"+h+"IGNORANCE"+i+"STRENGTH"+h);}}

Unfortunately, that trick doesn't work in Java 8. Guess I should have specified that :)

Java 6 is the price to pay for golfing in Java 8)

I know it's been more than 2 years, but you can golf it by printing just once with a ternary if and since you talked about Java 8 in the comment above, you can also replace class with interface and remove the public  before the main-method: interface B{static void main(String[]a){String b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=".\n",i=" IS ";System.out.print(Math.random()>.5?b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+h:"WAR"+i+"PEACE"+h+"FREEDOM"+i+"SLAVERY"+h+"IGNORANCE"+i+"STRENGTH"+h);}} (308 bytes)

Javascript 229 254 256
Edit 1 using new Date as suggested by @Doorknob - still unclear to me how javascript Dates morph to strings or integers or whatever
Edit 2 simplified. A lot.
t=(new Date&1
   ?'0WAR0 IS 0PEACE0.\n0FREEDOM020SLAVERY040IGNORANCE020STRENGTH.'
   :'0Under the spreading chestnut tree0\nI 0sold 0you 0and 04030me.\nT0here lie 0they, 05090we\n010.'
  ).split(0);
for(i=o='';j=t[++i];)o+=t[j|0||i];alert(o)

new Date is shorter than Date.now()

To explain the Date conversion: *> The JavaScript date is  based on a time value that is milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.*, when you & it it's automatically cast to a Number. So you're basically making the random choice based on whether it's an even or odd millisecond since the 1970-01-01T00:00:00.000Z epoch.

@Doorknob could you write a short article for that shorter random number generator in https://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript Haven't seen it there yet and I think it could be quite useful.

@flawr Done

C# (268)(260) (256)
This is executable in LINQPad, using the Dump() method:
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";if(new Random().Next(9)>4)(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+".").Dump();else("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.").Dump();

Ungolfed:
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";

if(new Random().Next(9)>4)
    (b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+".").Dump();
else
    ("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.").Dump();

Update:
Using the ternary operator and 1 extra variable, I was able to cut another 6 characters:
string a,b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";a=new Random().Next(9)>4?(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+"."):("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.");a.Dump();

Ungolfed:
string a,b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";

a=new Random().Next(9)>4 ?
    (b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+".") :
    ("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.");

a.Dump();

Update2:
Thanks to the ingenious suggestion of tsavinho I was able to save 4 more chars by placing braces around the ternary operation:
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";(new Random().Next(9)>4?(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+"."):("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.")).Dump();

Ungolfed:
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";
(new Random().Next(9)>4?
    (b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+"."):
    ("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.")
).Dump();

You could save 4 more characters by removing a and replacing it with brackets like this:
string b="Under the spreading chestnut tree",c="sold ",d="you ",e="and ",f="me.\nT",g="here lie ",h=" IS ";(new Random().Next(9)>4?(b+"\nI "+c+d+e+d+c+f+g+"they, "+e+g+"we\n"+b+"."):("WAR"+h+"PEACE.\nFREEDOM"+h+"SLAVERY.\nIGNORANCE"+h+"STRENGTH.")).Dump();

Python 3 - 228
for x in[b"AB:87078@624>049BA6",b"?;<61;=63;56"][id(id)%3-1]:print("and |FREEDOM|T|IGNORANCE|here lie |STRENGTH|.\n|you |sold |we|I | IS |PEACE|SLAVERY|they, |WAR|me|Under the spreading chestnut tree|\n".split("|")[x-48],end="")

Slightly ungolfed:
# id(id) returns an even number based on memory address of id
# id(id)%3-1 gives -1, 0 or 1
randomNumber = id(id)%3-1

# Word list
words = "and |FREEDOM|T|IGNORANCE|here lie |STRENGTH|.\n|you |sold |we|I | IS |PEACE|SLAVERY|they, |WAR|me|Under the spreading chestnut tree|\n".split("|")

# Byte Literals for Under the chestnut and WAR IS PEACE
# each byte correspond to the word's index in the word list
byteLiterals = [b"AB:87078@624>049BA6", b"?;<61;=63;56"]
choice = byteLiterals[randomNumber]

for x in choice:
    print(words[x-48], end="") # Print each word out

PowerShell 205
("{0}.`nI{1}{2}{3}{2}{1} me.`nT{4}they,{3} {4}we`n{0}."-f"Under the spreading chestnut tree"," sold"," you"," and","here lie "),("WAR","PEACE.`nFREEDOM","SLAVERY.`nIGNORANCE","STRENGTH."-join" IS ")|Random

Uses the -f operator to put strings on the first quote, and the second one is joined by IS, after that it selects a random element of those 2 quotes and prints it...

Easy 5 bytes by swapping out the `ns

JavaScript / jQuery 396
var B={
U:"Under the spreading chestnut tree",
s:"sold ",
y:"you ",
l:"lie ",
a:"and ",
i:"IS ",
b:"</br>"
};
var A={
P:B.U+B.b+"I "+B.s+B.y+B.a+B.y+B.s+"me."+B.b
+"There "+B.l+"they, "+B.a+"here "+B.l+"we."+B.b+B.U,
Q:"WAR "+B.i+"PEACE."+B.b+"FREEDOM "+B.i+"SLAVERY."+B.b
+"IGNORANCE "+B.i+"STRENGTH."
};
$(function(){
var z=(Math.random()<0.5)?A.P:A.Q;
$('#d').append(z);
});

T-SQL, 337 327
Just for fun, I've made another solution in T-SQL, which is one byte shorter than my Java 8 solution:
DECLARE @b char(33)='Under the spreading chestnut tree',@c char(5)='sold',@d char(4)='you',@e char(4)='and',@f char(9)='here lie',@ char='
',@h char(4)=' IS'IF rand()>.5PRINT @b+@+'I '+@c+@d+@e+@d+@c+'me.'+@+'T'+@f+'they, '+@e+@f+'we'+@+@b+'.'ELSE PRINT'WAR'+@h+'PEACE.'+@+'FREEDOM'+@h+'SLAVERY.'+@+'IGNORANCE'+@h+'STRENGTH.'

By declaring the chars one too long, you can add an 'automatic' space, saving up a few bytes.
Using the code in the proposed edit by user PenutReaper, you can indeed shave off 10 bytes.

Using a variable for carriage returns isn't worth it.  Just use literal ones.

JavaScript, 233 bytes
Math.random()>0.5?(a="Under the spreading chestnut tree")+"\nI "+(s="sold")+(y=" you ")+(n="and")+y+s+" me.\nT"+(h="here ")+(l="lie ")+"they "+n+" "+h+l+"we\n"+a+".":["WAR","PEACE.\nFREEDOM","SLAVERY.\nIGNORANCE","STRENGTH."].join(" IS ")

Wrote this without looking at other answers. Makes good use of assignments as expressions.

05AB1E, 119 bytes
“‚â€€ spreading chestnutíÍ““Iïê€î€ƒ€îïê€á.““€Çº¤€»,€ƒ€Îº¤€¦“).ªĆ»‘‡î€ˆ PEACE.
FREEDOM€ˆÃÒRY.
IGNORANCE€ˆ STRENGTH‘)'.«Ω

Try it online!

Python 3, 222 bytes
a,b,c,d,e,f='Under the spreading chestnut tree',' you ',' lie ','and','sold',' IS '
print({f'{a}\nI {e}{b}{d}{b}{e} me.\nThere{c}they, {d} here{c}we\n{a}.',f'WAR{f}PEACE.\nFREEDOM{f}SLAVERY.\nIGNORANCE{f}STRENGTH.'}.pop())

Try it online!

C (gcc), 307 289 271 270 bytes
-37 bytes thanks to ceilingcat
*y=" IS ";main(){int*r[]={"WAR",y,"PEACE.\nFREEDOM",y,"SLAVERY.\nIGNORANCE",y,"STRENGTH.",0,"Under the spreading chestnut tree","\nI"," sold ","you"," and ",r[11],r[10],"me.\n","T","here lie ","they,",r[12],r[17],"we\n",r[8],".",0},z=r;for(z=z/2&8;r[z];)printf(r[z++]);}

Try it online!


text:
Molar masses of compounds
Task
Write a program that takes in a compound made solely of elements with an atomic number less than or equal to 92 (Uranium), and outputs the molar mass of the compound in grams/mole.
Rules and Restrictions

You may not use a function that directly calculates molar masses for you.
Your program must be able to run on an offline machine.
You MAY use a separate data file. Contents of this file must be provided.
Your score is the length of your program in bytes, plus the the length of your data file in bytes, should you choose to use one.
This is code-golf, therefore, lowest score wins.

Input
A string containing the compound. This string may be read through STDIN, passed as an argument, or set to a variable (please specify which). The following are all valid inputs:

CH2 (one Carbon, two Hydrogens)
(CH2)8 (8 Carbons, 16 Hydrogens)
U (1 Uranium)

Your program is not required to function for embedded parentheses (i.e. ((CH3)2N4)4), nor for any compound that contains an element with atomic number greater than 92. If your program does not function for either of the above two cases, it must output Invalid formula for such cases - no undefined behavior.
Output
You should output, to STDOUT or to a variable, the molar mass of the compound in grams/mole. A list of atomic masses of elements is available here (Wikipedia). Your answer should be accurate to the decimal place for compounds containing fewer than 100 atoms (rounded).
If the input is invalid, Invalid formula must be outputted.
Information on calculating the molar mass of a compound in grams/mole (Wikipedia).
Examples
Input                   Output
H2O                     18.015
O                       15.999 (16 acceptable)
C6H2(NO2)3CH3           227.132
FOOF                    69.995
C6H12Op3                Invalid formula
Np                      237 (or Invalid formula)
((C)3)4                 144.132 (or Invalid formula)
CodeGolf                Invalid formula

"to the decimal point" - for how large molecules? The mass of U1000000 is harder to determine to the decimal point than the mass of U2

to the decimal point for molecules with less than 100 atoms. Added this to the question statement.

I also assume I'm allowed to output 13 if the atomic mass is 12.999?

That doesn't sound right @es1024. 13, ok, but 12?

"Your answer should be accurate to the decimal place" does that mean to one decimal place or to the nearest integer?

Sorry for the confusion. If the molar mass is 12.753, 13 is acceptable. To the decimal place means nearest integer is sufficient.

What should the output be if it is impossible to obtain the required accuracy? There are quite a few elements with atomic number less than 92 which don't have any stable isotopes and hence don't have a "proper" value in the table you linked. So the error in the molar mass of e.g. Fr3N is more than one atomic unit.

@PeterTaylor use the mass number of the longest lived isotope (as given on the table). Fr3N would be 223*3+14.007=683.007, so 683 would be a valid answer.

I wrote a program that did the opposite, put it on my PSP, and was allowed to use it on an exam. You give it a mass and it gives you the formula. And I would use the weighted average of atomic masses provided on the periodic table, that would be a better representation of natural molecules.

Bash, 978 708 675 673 650 636 632 631 598 594
211 bytes for the program and 382 bytes for the data.
Input is on STDIN, output is on STDOUT. WARNING: creates files called g and a, if they exist, they will be overwritten!

zcat y>g 2>a
s=(`sed 's/[A-Z][a-z]*/& /g;q'<g`)
p=1.008
v=`sed 's/[0-9]\+/*&/g;s/(/+(0/g'`
r=(`tail -1 g`)
for n in {0..91};{
p=`bc<<<$p+${r[n]}`
v=${v//${s[n]}/+$p}
}
o=`bc<<<0$v 2>a`
echo ${o:-Invalid formula}

Data file
This requires a file called y, which is the zopfli-compressed form of this data (no trailing newline). zopfli is a gzip-compatible compression algorithm and can be decompressed with standard gzip tools. It was run with 1024 iterations (this is probably too much). The last 8 bytes were then removed.
HHeLiBeBCNOFNeNaMgAlSiPSClKArCaScTiVCrMnFeNiCoCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbITeXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcPaThU
0 2.995 2.937 2.072 1.798 1.201 1.996 1.992 2.999 1.182 2.81 1.315 2.677 1.103 2.889 1.086 3.39 3.648 .850 .130 4.878 2.911 3.075 1.054 2.942 .907 2.848 .24 4.613 1.834 4.346 2.904 2.292 4.038 .944 3.894 1.670 2.152 1.286 2.318 1.682 3.054 2.04 3.07 1.836 3.514 1.448 4.543 2.407 3.892 3.050 5.144 .696 3.693 1.612 4.422 1.578 1.211 .792 3.334 .758 5.36 1.604 5.286 1.675 3.575 2.43 2.329 1.675 4.120 1.913 3.523 2.458 2.892 2.367 4.023 1.987 2.867 1.883 3.625 3.788 2.82 1.78 .02 1 12 1 3 1 4.036 1.002 5.991

The base64 of y is (use base64 -d to reproduce the original file):
H4sIAAAAAAACAwTB226DMAwA0G9LvEJQIbVi70LfHPBoJAiSaR729zsnBB2LVw/x0UWNMm1up4IE
+90ZCC1cvsCm2mkscEJ71l56dRept7ulTDY/Lebp5CW19MLVbbAOlSrlgfVH4fIyCihaXPGg49b6
lfPHXzhvxsecxxZ+Wb6TPq7B8O1a2HjH7Aue7p1qZ0ncgsKvz/8WxuRGoigGgfcfxYvA8r7kn9iA
ei6ohAt/+lzuihmD1PFnMrdIV0PeNfOczh3Ylrw8hnHaM6w1WC8V3X4hcYjOfbKlTyz0pewsP5nh
plOUK9mkPzkd4HLiCbktIGyQI5uaUvZzNBrwLhOf9hJij+Jo5WBf6mHLfh2OFqeaxOHbaGAZl5mL
h5UBI3Hlx99GX4llPumDjgw+NIee7uCaRbrZkzluIhJYi2E0ZU2gb5OnYBTSJQMRfv91irmCz4KK
B5Va5J7T7IGjHnR22PeAd+m3F3KW/voz4BMFPGNgxHE0Loq65M6+Pw==

The md5sum is d392b0f5516033f2ae0985745f299efd.
Explanation
The numbers in the file are increments of relative atomic mass (so the relative atomic mass of lithium is 1.008 + 0 + 2.995 + 2.937).
This script works by converting the chemical formula into an arithmetical expression with + and *, replacing each symbol with its relative atomic mass, then feeding the expression to bc. If the formula contains invalid symbols, bc will give a syntax error and output nothing to STDOUT; in that case, the output is Invalid formula.
If STDIN is empty, the output is 0. Nested brackets are supported.
zcat y>g 2>a # Unzip the file y and output result to the file g. Send standard error to file a (there will be an error because the last 8 bytes are missing)
s=(`sed 's/[A-Z][a-z]*/& /g;q'<g`)  # Read from g to sed; append a space after any capital letter optionally followed by a lowercase letter; exit at the end of the first line so the atomic masses are not processed in this way; parse result as space-separated array and save to variable $s
p=1.008 # In the upcoming loop, $p is the value obtained in the previous iteration
v=`sed 's/[0-9]\+/*&/g;s/(/+(0/g'` # Read from standard input to sed; prepend a * after any sequence of digits; replace ( with +(0; save to $v
r=(`tail -1 g`) # Get the last line of file g; parse as space-separated array; save to $r
for n in {0..91};{ # Loop once for each number from 0 to 91; set $n to the current number each iteration
p=`bc<<<$p+${r[n]}` # Concatenate $p, + and the next number from $r; send to bc and evaluate as arithmetic expression; save to $p (i.e. add the next increment from the file to $p)
v=${v//${s[n]}/+$p} # Replace every occurence of the current element symbol with + and $p (i.e. replace each symbol with a + and its relative atomic mass
} # end loop
o=`bc<<<0$v 2>a` # Prepend 0 to $v; send to bc and evaluate as arithmetic expression; redirect any errors on standard error to the file a; save result to $o
echo ${o:-Invalid formula} # If $o is empty (if there was a syntax error), output Invalid formula; otherwise output $o

Example
C6H2(NO2)3CH3  #input
C*6H*2+(0NO*2)*3CH*3  #after line 3
+12.011*6+*1.008*2+(0+14.007+15.999*2)*3+12.011+1.008*3  #after the loop in lines 4-6
0+12.011*6+*1.008*2+(0+14.007+15.999*2)*3+12.011+1.008*3  #given to bc in line 7
227.132 #output as evaluated by bc

You could save a lot by storing the differences between the masses of the elements and calculating on the fly. The minimum and maximmm differences are -1.002 and +6.993 (either side of Pa.) By rearanging the elements in atomic mass order instead of atomic number order, the range becomes 0 to 5.991. When the periodic table was devised, there was much debate about which order was better. (Obviously, from a Chemistry point of view, the atomic number order is better, but they took some time deciding that.)

@steveverrill I thought about that when writing the code, I'll look into it soon

@steveverrill Done, the saving was about 33 chars

Javascript, 1002
Input is in q and output is in a.  I was unsure of what the rules for rounding were, so I truncated to 3 places after the decimal (or fewer, if digits were unavailable from Wikipedia).
H=1.008
He=4.002
Li=6.94
Be=9.012
B=10.812
C=12.011
N=14.007
O=15.999
F=18.998
Ne=20.179
Na=22.989
Mg=24.305
Al=26.981
Si=28.085
P=30.973
S=32.06
Cl=35.45
Ar=39.948
K=39.098
Ca=40.078
Sc=44.955
Ti=47.867
V=50.941
Cr=51.996
Mn=54.938
Fe=55.845
Co=58.933
Ni=58.693
Cu=63.546
Zn=65.38
Ga=69.723
Ge=72.630
As=74.921
Se=78.96
Br=79.904
Kr=83.798
Rb=85.467
Sr=87.62
Y=88.905
Zr=91.224
Nb=92.906
Mo=95.96
Tc=98
Ru=101.07
Rh=102.905
Pd=106.42
Ag=107.868
Cd=112.411
In=114.818
Sn=118.710
Sb=121.760
Te=127.60
I=126.904
Xe=131.293
Cs=132.905
Ba=137.327
La=138.905
Ce=140.116
Pr=140.907
Nd=144.242
Pm=145
Sm=150.36
Eu=151.964
Gd=157.25
Tb=158.925
Dy=162.500
Ho=164.930
Er=167.259
Tm=168.934
Yb=173.054
Lu=174.966
Hf=178.49
Ta=180.947
W=183.84
Re=186.207
Os=190.23
Ir=192.217
Pt=195.084
Au=196.966
Hg=200.592
Tl=204.38
Pb=207.2
Bi=208.980
Po=209
At=210
Rn=222
Fr=223
Ra=226
Ac=227
Th=232.038
Pa=231.035
U=238.028
try{a=eval(q.replace(/(\d+)/g,'*$1').replace(/(\w)(?=[A-Z\(])/g,'$1+'))}catch(e){a="Invalid formula"}

+1 for the idea of using simple variables ... now I can leave my overcomplex answer for future shame

Input is actually in q, though everything else seems fine. +1

You could save some bytes by deleting the trailing zeros: 121.760 = 121.76

Mathematica 9 - 247 227
This is clearly cheating as I'm using a function that directly calculates atomatic masses (but not molar masses!):
r=StringReplace;f[s_]:=Check[ToExpression@r[r[r[s,x:RegularExpression["[A-Z][a-z]*"]:>"ElementData[\""<>x<>"\",\"AtomicWeight\"]+"],x:DigitCharacter..:>"*"<>x<>"+"],{"+*"->"*","+"~~EndOfString->"","+)"->")"}],"Invalid formula"]

Usage: Call the function f with a string containing the formula, the output will be the mass.
Test:
f["H2O"]           (* => 18.0153 *)
f["O"]             (* => 15.9994 *)
f["C6H2(NO2)3CH3"] (* => 227.131 *)
f["FOOF"]          (* => 69.9956 *)
f["C6H12Op3"]      (* => Invalid formula *)
f["Np"]            (* => 237 *)
f["((C)3)4"]       (* => 144.128 *)
f["CodeGolf"]      (* => Invalid formula *)

Mathematica 10 doesn't output a raw number, but a number with a unit, so that may not be acceptable.

@MartinBüttner Thanks, I basically just copied a function from my init file and golfed it a little bit. The golfing could certainly be improved.

Perl - 924
It uses a series of regex substitution operations on the inputted formula to expand the subscripted elements and groups, replace the elements with atomic weights, and transform it into a sequence of additions which it then evaluates.
$_=<>;chop;@g='H1008He4003Li6940Be9012B10810C12011N14007O15999F18998Ne20179Na22989Mg24305Al26981Si28085P30974S32060Cl35450Ar39948K39098Ca40078Sc44955Ti47867V50942Cr51996Mn54938Fe55845Co58933Ni58693Cu63546Zn65380Ga69723Ge72630As74922Se78960Br79904Kr83798Rb85468Sr87620Y88906Zr91224Nb92906Mo95960Tc98Ru101070Rh102906Pd106420Ag107868Cd112411In114818Sn118710Sb121760Te127600I126904Xe131293Cs132905Ba137327La138905Ce140116Pr140907Nd144242Pm145Sm150360Eu151964Gd157250Tb158925Dy162500Ho164930Er167259Tm168934Yb173054Lu174967Hf178490Ta180948W183840Re186207Os190230Ir192217Pt195084Au196967Hg200592Tl204380Pb207200Bi208980Po209At210Rn222Fr223Ra226Ac227Th232038Pa231036U238028'=~/(\D+)([\d\.]+)/g;for$b(0..91){$d=2*$b+1;$g[$d]=$g[$d]>999?$g[$d]/1000:$g[$d]}%h=@g;for$a('(\(((?>[^()]|(?1))*)\))(\d+)','()([A-Z][a-z]?)(\d+)'){for(;s/$a/$2x$3/e;){}}s/([A-Z][a-z]?)/($h{$1}||_).'+'/ge;if(/_/){print'Invalid formula';exit}$_.=0;print eval;

PHP — 793 (583 + 210)
Largely outdistanced by professorfish's answer, who is using a similar method, but hey… The symbols and the masses are gzip-compressed in the file a obtained with the following code:
$symbolsList = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mg', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U'];
$massesList = [1.008, 4.003, 6.94, 9.012, 10.81, 12.011, 14.007, 15.999, 18.998, 20.18, 22.99, 24.305, 26.982, 28.085, 30.974, 32.06, 35.45, 39.948, 39.098, 40.078, 44.956, 47.867, 50.942, 51.996, 54.938, 55.845, 58.933, 58.6934, 63.546, 65.38, 69.726, 72.630, 74.922, 78.96, 79.904, 83.798, 85.468, 87.62, 88.906, 91.224, 92.906, 95.96, 98, 101.07, 102.906, 106.42, 107.868, 112.411, 114.818, 118.710, 121.760, 127.60, 126.904, 131.293, 132.905, 137.327, 138.905, 140.116, 140.908, 144.242, 145, 150.36, 151.964, 157.25, 158.925, 162.5, 164.93, 167.259, 168.934, 173.054, 174.967, 178.49, 180.948, 183.84, 186.207, 190.23, 192.217, 195.084, 196.967, 200.592, 204.38, 207.2, 208.98, 209, 210, 222, 223, 226, 227, 232.038, 231.036, 238.029];

$fileArrayContent = [$symbolsList, $massesList];
$fileStringContent = json_encode($fileArrayContent);

$file = gzopen('a', 'w9');
gzwrite($file, $fileStringContent);
gzclose($file);

The formula should be stored in the $f variable:
$a=json_decode(gzfile('a')[0]);$r=@eval('return '.str_replace($a[0],$a[1],preg_replace(['#(?<=(?!\().)(\(|'.implode('|',$a[0]).')#','#\d+#'],['+${1}','*$0'],$f)).';');echo error_get_last()?'Invalid formula':$r;

Here is the ungolfed and commented version:
// Recover the data stored in the compressed file
$fileStringContent = gzfile('a')[0];
$fileArrayContent = json_decode($fileStringContent);
$symbolsList = $fileArrayContent[0];
$massesList = $fileArrayContent[1];

$formula = preg_replace('#(?<=(?!\().)(\(|'. implode('|', $symbolsList) .')#', '+${1}', $formula); // Add a "+" before each opening paranthesis and symbol not at the beginning of the string and not preceded by an opening paranthesis
$formula = preg_replace('#\d+#', '*$0', $formula); // Add a "*" before each number

$formula = str_replace($symbolsList, $massesList, $formula); // Replace each symbol with its corresponding mass

$result = @eval('return '. $formula .';'); // Evaluate the value without showing the errors
echo error_get_last() ? 'Invalid formula' : $result; // Print the value, or "Invalid formula" if there was an error

I'm beating you by one byte now, I have 673 bytes

@professorfish Indeed! Besides, I've miscounted the file size, which is larger that what I've said before. You're by far the winner, currently ^^!

Javascript (E6) 1231
As a function with the input as argument and returning the output.
Precision: 3 decimal digits
Use regexp to transform the chemical formula in a simple arithmethic expression, with sums and products, replacing:

( with +(
any numeric sequence with '*', then the numeric sequence
any Capital letter followed by letters with '+', then the atomic mass of the corresponding element (if found)

Then the expression is evaluated and the value returned. In case of errors or if value is NaN (or zero) then function returns 'Invalid formula'
Now I see that all other answers use the same method ... oh well here is the javascript version
F=f=>{
  T={H:1.008,He:4.002,Li:6.94,Be:9.012,B:10.81,C:12.011
  ,N:14.007,O:15.999,F:18.998,Ne:20.179,Na:22.989,Mg:24.305
  ,Al:26.981,Si:28.085,P:30.973,S:32.06,Cl:35.45,Ar:39.948
  ,K:39.098,Ca:40.078,Sc:44.955,Ti:47.867,V:50.941,Cr:51.996,Mn:54.938
  ,Fe:55.845,Co:58.933,Ni:58.693,Cu:63.546,Zn:65.38,Ga:69.723,Ge:72.630
  ,As:74.921,Se:78.96,Br:79.904,Kr:83.798,Rb:85.467,Sr:87.62,Y:88.905,Zr:91.224
  ,Nb:92.906,Mo:95.96,Tc:98,Ru:101.07,Rh:102.905,Pd:106.42,Ag:107.868,Cd:112.411
  ,In:114.818,Sn:118.710,Sb:121.760,Te:127.60,I:126.904,Xe:131.293
  ,Cs:132.905,Ba:137.327,La:138.905,Ce:140.116,Pr:140.907,Nd:144.242,Pm:145
  ,Sm:150.36,Eu:151.964,Gd:157.25,Tb:158.925,Dy:162.500,Ho:164.930,Er:167.259
  ,Tm:168.934,Yb:173.054,Lu:174.966,Hf:178.49,Ta:180.947,W:183.84,Re:186.207
  ,Os:190.23,Ir:192.217,Pt:195.084,Au:196.966,Hg:200.592,Tl:204.38,Pb:207.2
  ,Bi:208.980,Po:209,At:210,Rn:222,Fr:223,Ra:226,Ac:227,Th:232.038,Pa:231.035
  ,U:238.028,Np:237,Pu:244,Am:243,Cm:247,Bk:247,Cf:251,Es:252,Fm:257,Md:258
  ,No:259,Lr:266,Rf:267,Db:268,Sg:269,Bh:270,Hs:269,Mt:278
  ,Ds:281,Rg:281,Cn:285,Uut:286,Fl:289,Uup:289,Lv:293,Uus:294,Uuo:294};
  e='Invalid formula';
  try{return eval(f.replace(/([A-Z][a-z]*)|(\d+)|(\()/g,(f,a,b,c)=>c?'+(':b?'*'+b:a='+'+T[a]))||e}
  catch(x){}return e
}

I used almost the same method, but I created the function at least a year ago, so at least I didn't copy you. ;)

Scala, 1077
I see all your solutions in dynamically typed languages with cop-outs like eval or built-in atomic mass function and raise you a statically-typed language solution:
object M{type S=String;type Z=(Int,S)
val d="H  *dHe JVLi inBe!!rB !5\"C !AiN !W!O !l3F \".*Ne\":_Na\"XUMg\"fUAl#%#Si#0iP #OOS #[&Cl$!,Ar$P|K $GxCa$RBSc%(7Ti%G5V %gwCr%s.Mn&4JFe&>)Co&^yNi&\\ECu'2\"Zn'ERGa'seGe(4^As(M#Se(x Br)$$Kr)MLRb)_5Sr)v,Y *%kZr*>LNb*PBMo*ppTc+(TRu+I4Rh+\\ePd,$,Ag,3RCd,cqIn,}LSn-HrSb-i>Te.IJI .B$Xe.peCs/#sBa/RwLa/ccCe/pXPr/y!Nd0>NPm0FTSm1!VEu12\\Gd1jrTb1|aDy2DdHo2^VEr2wATm3+0Yb3W Lu3k@Hf42nTa4L{W 4kfRe5&wOs5QdIr5fqPt6'BAu6;DHg6azTl7,8Pb7J8Bi7]2Po7]FAt7h$Rn9+bFr96@Ra9V8Ac9`tTh:8NPa:-mU :x4".grouped(5).map{s=>(s.take(2).trim,s(2)*8836+s(3)*94+s(4)-285792)}.toMap
def k(n:S):Z={val x=n.takeWhile(_.isDigit);(if(x=="")1 else x.toInt,n drop x.length)}
def o(m:S):Z={if(m(0)==40){val(i,s)=a(m.tail);if(s(0)!=41)???;val(j,t)=k(s.tail);(j*i,t)}else{val l=if(m.size>1&&m(1).isLower)2 else 1;val(i,s)=d(m.take(l))->m.drop(l);val(j,t)=k(s);(j*i,t)}}
def a(m:S)={var(r,s)=(m,0);do{val(y,z)=o(r);r=z;s+=y}while(r!=""&&r(0)!=41);s->r}
def main(q:Array[S]){println(try{val(m,s)=a(io.Source.stdin.getLines.next);if(s!="")???;m/1e3}catch{case _=>"Invalid formula"})}}

I should consider some compression for the data, but for now let's just have the atomic masses in base 94, uncompressed.

Gives me molarmass.scala:5: error: ';' expected but identifier found. def a(m:S)={var(r,s)=(m,0);do{val(y,z)=o(r);r=z;s+=y}while(r!=""&&r(0)!=41)s->r}

Fixed. Also I found out Scala's parser is weird.


text:
sort and restore a set of bytes in optimal form
Challenge
For any given input Y of length >= 1024 bytes:

sort in ascending or descending order -- your choice
generate output Q, where Q = [sorted data] + [restore
information]
restore Y using Q as input

Sorting Example
 input: [2, 5, 119, 0, 1, 223, 0, 118, ...]
output: [0, 0, 1, 2, 5, 118, 119, 223, ...] + [restore information]

Restore Example
 input: [0, 0, 1, 2, 5, 118, 119, 223, ...] + [restore information]
output: [2, 5, 119, 0, 1, 223, 0, 118, ...]

Winning
The program that generates the least amount of information in order to restore to original state wins, however it must work within a reasonable amount of time on modern hardware, less than 10 minutes.
UPDATE 1
You may use any third party libraries that are open-source if you so desire.
UPDATE 2
The [restore information] size is measured in bytes, it's your choice what it contains.
UPDATE 3
In case it's not yet clear, the input Y is a stream of bytes, you shouldn't care what it contains, all you care is to sort the values of the bytes in the order you prefer while also generating the necessary data in order to restore to Y from Q.

Are third party libraries allowed? I'd rather not write my own implementation of arithmetic coding

@James_pic yes, so long as the libs are open-source, I've updated the post.

Is the information amount measured in bytes, characters or values?

@Sieg in bytes, I've updated post.

Can the program be given a flag to differentiate when it should sort or restore? It's impossible to detect otherwise.

@Sieg there are no restrictions as to what you wish to store in the [restore information] part of the sorted output, you may store for example a unique string or series of bytes that will help you determine that. Please keep in mind that the requirements are very loose, you may even require the user to specify the "type of file", is it a file to be sorted or to restored.

This question is way too vague about the evaluation process; since any choice of "restore data" different than "the original list" is bound to have variable length depending on the input, how are we supposed to compare the solutions?

Why specify >= 1024 bytes? That seems like a strange input restriction.

This desperately needs some test cases.

You need to specify some more parameters. The quality of a solution depends hugely on how large entries are compared to the number of list elements. This determines whether it's shorter to refer to an element by its value or its index. Also, the frequency of repetitions determines how unique the unscrambling must be.

Python
The restore information is just the original list.  n bytes of restore information for an n byte list.
def sort(Y):
  return (sorted(Y), Y)

def restore(Q):
  return Q[1]

ha-ha, this is wicked!! I like how you took the simplest approach (:

Indeed, I think this is the most efficient solution in the long run (actually a Huffman encoded version could beat it)

I agree, in the general case I don't think you can beat a (compressed) copy of the original data.

You can certainly beat a compressed copy of the original data. Making a separate copy wastes all the information the sorted list gives you about how many of each byte are in the list.

Well, there are 256^n unsorted lists of bytes.  There are only about choose(n, 256) ~ n^256 sorted lists of bytes.  That's exponential vs. polynomial.  So asymptotically knowing the sorted list doesn't help reconstruct the unsorted list.

Scala + Arithmetic coding
Once we sort the data, all we're left with is the frequencies of the bytes within the original. Conveniently, this is exactly what we need for efficient adaptive arithmetic coding. We use arithmetic coding on the frequencies of the remaining elements of the data. I suspect this is information theoretically optimal, for random data.
I've used nayuki's arithmetic coding library.
import nayuki.arithcode._
import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets.UTF_8

object Unsort {
  def mkTable(data: Array[Byte]) = {
    val frequencyMap = data.groupBy(identity).mapValues(_.size)
    val frequencyArray = (0 to 255).map(i => frequencyMap.getOrElse(i.toByte, 0)).toArray
    new RemainingFrequencies(frequencyArray)
  }

  def sort(data: Array[Byte]) = {
    val freqTable = mkTable(data)
    val output = new ByteArrayOutputStream
    val bitOutput = new BitOutputStream(output)
    val encoder = new ArithmeticEncoder(bitOutput)
    for (b <- data) {
      val i = b.toInt & 0xff
      encoder.write(freqTable, i)
      freqTable.decrement(i)
    }
    encoder.finish()
    bitOutput.close()
    (data.sorted, output.toByteArray)
  }

  def unsort(dataAndMetadata: (Array[Byte], Array[Byte])) = {
    val (data, metadata) = dataAndMetadata
    val freqTable = mkTable(data)
    val input = new ByteArrayInputStream(metadata)
    val bitInput = new BitInputStream(input)
    val decoder = new ArithmeticDecoder(bitInput)
    (for (_ <- 0 until data.length) yield {
      val x = decoder.read(freqTable)
      freqTable.decrement(x)
      x.toByte
    }).toArray
  }

  def main(args: Array[String]) = {
    val stringData = args.reduce(_ + " " +_)
    val data = stringData.getBytes(UTF_8)
    val (sorted, metadata) = sort(data)
    val unsorted = unsort((sorted, metadata))
    val unsortedString = new String(unsorted, UTF_8)
    println(s"""Received "${stringData}"""")
    println(s"""Sorted to ${sorted.toList} + ${metadata.toList}""")
    println(s"""(${sorted.length} bytes of data, ${metadata.length} bytes of metadata)""")
    println(s"""Unsorted to "$unsortedString"""")
  }
}

class RemainingFrequencies(private val frequencies: Array[Int]) extends FrequencyTable {
  override val getSymbolLimit = 256
  override def get(symbol: Int) = frequencies(symbol)
  override def set(symbol: Int, freq: Int) = ???
  override def increment(symbol: Int) = ???
  override def getTotal = frequencies.sum
  override def getLow(symbol: Int) = frequencies.slice(0, symbol).sum
  override def getHigh(symbol: Int) = frequencies.slice(0, symbol + 1).sum
  def decrement(symbol: Int) = frequencies(symbol) -= 1
}

As an example of the output, here's what happens when we run it against the first paragraph of Franz Kafka's Metamorphosis:
Received "One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked."
Sorted to List(32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 44, 44, 44, 44, 44, 44, 45, 46, 46, 46, 46, 71, 72, 72, 79, 83, 84, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 99, 99, 99, 99, 99, 99, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 103, 103, 103, 103, 103, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 107, 107, 107, 107, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 112, 112, 112, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 117, 117, 117, 117, 117, 117, 118, 118, 118, 118, 119, 119, 119, 119, 119, 119, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 122) + List(53, -2, -48, 47, 98, -11, -73, 89, 24, -16, 122, -22, -52, -112, 110, -5, -47, -93, 33, -78, 30, 101, -75, 105, 48, -118, 86, -94, -111, 6, 99, 80, 123, 106, 114, -94, -106, -56, -14, 85, -81, -111, 4, -65, 10, -38, -56, -83, 73, 51, -80, 34, -116, 112, -125, -89, -107, 77, 69, -123, -121, -55, 104, 24, 105, 93, 60, -88, 50, -117, 21, -17, 119, 56, 51, -53, 63, 116, -48, 13, -35, 67, -3, -73, -126, 58, -117, 19, -24, -18, -18, -73, -108, -3, -100, 30, 47, -32, -52, -22, -108, 37, 110, 79, -37, -78, -2, 72, 99, -42, 30, 102, -70, -33, -52, -32, -109, -37, 104, 26, 126, 67, 80, 101, 15, 1, -101, 21, -38, -95, 32, -24, 12, -75, -92, 28, 124, -65, 39, -58, 68, -58, 70, -90, -17, -29, -12, 1, 37, 84, 91, 61, 13, -28, 73, -112, -47, 42, -12, 64, -21, -95, 67, -113, -109, 28, 67, 35, -13, 81, -109, -49, 63, -20, -98, -112, 64, -53, 51, -96, -49, -111, 28, 46, 97, 77, -115, 78, -61, 110, 105, -4, -88, 0, -127, -66, -59, -65, -4, -105, -120, 53, 49, 2, 60, -7, -83, -102, -128, -118, -77, 77, 28, -126, 58, 16, 4, 70, 28, 91, 96, -73, 29, -126, -6, 8, 112, 122, 40, 48, -45, 0, 24, -91, -5, -59, 61, 122, -96)
(468 bytes of data, 239 bytes of metadata)
Unsorted to "One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked."

It's only 468 bytes, but still an interesting test. The metadata used to unsort it is 239 bytes.
When I tested it against 4096 bytes of random data (not shown), the metadata was 3967 bytes.

wow, I wasn't expecting this, very good job! it would be interesting to see the metadata size if, for example, the input would contain random bytes from 0 to 255, I expect somewhere around 80%+ of original data.

@ComputerSaysNo That'd be my expectation as well, for the simple reason that the sorted version tells us very little about the sequence in that case - it tells us there are roughly equal numbers of each character. I'll try it with some random data when I get chance.

Python 2.x - Score ?
I acrually have no idea how to calculate the score in this case. I use bubble sort and log the swaps along the way. Now, these swaps can then be applied in reversed order to get the original list back. Give the program a -r flag when restoring (ie. file.py -r)
I have a feeling the most optimal way in the long run is to just save the indexes for each value. But that isn't fun.
import sys
import binascii

def sort(data):
    swaps = ''
    swapped = True
    while swapped:
        swapped = False
        for i in xrange(len(data)-1):
            if data[i] > data[i+1]:
                temp = data[i]
                data[i] = data[i+1]
                data[i+1] = temp
                swapped = True
                swaps += '1'
            else:
                swaps += '0'
    swaps = swaps[:-len(data)+1]
    swaps += '0'
    while len(swaps) % 8 != 0:
        swaps += '1'
    swaps = int(swaps, 2)
    swaps = binascii.unhexlify('%x' % swaps)
    return ''.join(map(chr, data)) + swaps + binascii.unhexlify('%08x' % len(swaps))

def unsort(data, swaps):
    swaps = bin(int(binascii.hexlify(swaps), 16))[2:]
    swaps = swaps[::-1]
    while swaps[0] != '0':
        swaps = swaps[1:]
    swaps = swaps[1:]
    datalen = len(data) - 2
    i = datalen
    for s in swaps:
        if s == '1':
            temp = data[i]
            data[i] = data[i+1]
            data[i+1] = temp
        i -= 1
        if i < 0:
            i = datalen
    return ''.join(map(chr, data))

if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == '-r':
        data = sys.stdin.read()
        size = int(binascii.hexlify(data[-4:]), 16)
        swaps = data[-size-4:-4]
        data = map(ord, data[:-size-4])
        print unsort(data, swaps)
    else:
        data = map(ord, sys.stdin.read())
        sys.stdout.write(sort(data))
        sys.stdout.flush()

Example:
In:  94731
Out: 13479 ÷╚⌂

-r flag
In:  13479 ÷╚⌂
Out: 94731

this doesn't work for me, with python 2.7.8, I've ran [python test.py < sample.txt] where sample.txt is a text file that contains 1024 bytes, each byte is 0x31 or ASCII '1' and got as output: Traceback (most recent call last):/File "test.py", line 50, in /print "%s + %s" % sort(data)/File "test.py", line 8, in sort/for i in xrange(len(data)-1):/TypeError: object of type 'long' has no len()

@ComputerSaysNo Note that the input format you specified starts with a [ and ends with a ]. I'm not sure what else could cause that.

the '[' and ']' are just for illustration purposes, these characters may or may not be present within the input which is basically a stream of bytes to be sorted, I've modified my sample file to include the chars and added 0x32 or ASCII '2' as the first byte after '[', i.e. '[2111111111...1]' and it doesn't put '2' as last value in the print, would have expected '[111111...12]' as output, yet the output was the same as the input with the [restore info] data.

@ComputerSaysNo You should edit your question. At the moment it doesn't say that the input is a byte stream, yet it shows an example with a normal array/list. I thought the input would be given in similar lists, in similar format.

I've updated the post, however, the question starts with [For any given input Y of length >= 1024 bytes:], I thought it was clear, but I realize now that it's clear only to me, sorry for confusion!

@ComputerSaysNo Working on fixing.

@Sieg I have just deleted my answer. Condolences that your hard work has been outvoted by a non-serious answer which was also approved by OP. Well, this is PPCG afterall... things like this are commonplace. Anw, +1 for you for effort.

@ComputerSaysNo Fixed. Mind informing me if everything works correctly?

@bitpwner Thank you. I don't mind getting outvoted (heck, even I upvoted that answer).

@bitpwner Also, why did you remove your answer?

@Sieg It won't get upvotes at this rate. No point keeping it. I am imagining how a passerby from other stack exchanges will think that it is a poor answer just by mere impression from the votes.

there's still a slight bug in the "restore" part, however, for the most part, it works, there's a bug here "while data[i] != '\0':" you can't assume that the first NULL char is your marker, the file could be made out of 1024+ bytes with value 0x00

@ComputerSaysNo Note that I start from the end of the file, proceeding backwards. ;)

@bitpwner I would let it be anyways.

@ComputerSaysNo All bugs should now be fixed.

Theoretical solution:
Will work, but chances for it to complete within the time limit are pretty low.
Through brute-force search I try to find any random seed that, when used to shuffle of the original indexes, happens to create exactly the ordered list.
Sample output:
Input: [185, 60, 253, 77, 64, 146, 155, 66]
Sorted: [60, 64, 66, 77, 146, 155, 185, 253] 7099

Now if I could just figure out how to speed this up a little... ;)
public class SortRestore {

  public static void main(String[] args) {
    final Random rnd = new Random(123);
    final int[] input = IntStream.iterate(rnd.nextInt(256), s -> rnd.nextInt(256)).limit(2048).toArray();
    System.out.println("Input: " + Arrays.toString(input));
    final int[] sorted = Arrays.copyOf(input, input.length);
    Arrays.parallelSort(sorted);
    System.out.print("Sorted: " + Arrays.toString(sorted) + " ");
    final List<Integer> indexBase = IntStream.range(0, input.length).boxed().collect(Collectors.toList());

    IntStream.rangeClosed(0, Integer.MAX_VALUE).parallel()
            .filter(seed -> {
              final List<Integer> indexes = new ArrayList<>(indexBase);
              Collections.shuffle(indexes, new Random(seed));
              for (int i = 0; i < input.length; ++i) {
                if (input[i] != sorted[indexes.get(i)]) {
                  return false;
                }
              }
              return true;
            }).limit(1)
            .forEach(System.out::println);
  }
}

You'll be limited by the number of bits in your seed. Most RNGs take a fixed size seed - often between 64 and 1024 bits. A 1024 byte input will have 8192 bits, so most RNGs won't have a seed for every possibility

Performs selection sort and records all the swaps.
Input: [15, 18, 1, 6, 2, 16, 13]
Output: [1, 2, 6, 13, 15, 16, 18] [(0, 2), (1, 4), (2, 3), (3, 6), (4, 6)]
Also: list == restore(*sort(list))
def swap(l, indexes):
    l[indexes[0]], l[indexes[1]] = l[indexes[1]], l[indexes[0]]

def sort(l):
    restore = []
    for i in range(len(l)-1):
        m = min(l[i+1:])
        if l[i] > m:
            restore.append((i,l.index(m)))
            swap(l, restore[-1])

    return l, restore

def restore(l, restore):
    restore.reverse()
    for i in restore:
        swap(l,i)
    return l

J
Not sure how this should be scored, but it's a simple deal with J.

/:~ sorts the list.
A.@/:@/: gives the restoration information, an integer less than N! for a list of length N, which can be coded into ceil(log256 N!) bytes or less, using (256#.3&u:)inv, and decoded with (256#.3&u:).
((A.i.@#){]) takes the restoration integer on the left and the sorted array on the right.

The integer is literally a permutation number—that's what the A. is doing, converting between permutations and permutation numbers.
If you need a single program that can convert between the two, you're probably looking at something like:
(/:~;4 u:256#.inv A.@/:@/:) :(]{~i.@#@]A.~256#.3 u:[)

which sorts and gives the restore if it's used with one argument, or takes the restoration on the left and the sorted array on the right to fix it.
For the record, the J equivalent of Python's trivial solution, where the restoration information is the array itself, is the simple (;~/:~) :[.

+1 like your answer, not making much sense of the code logic -- read your comments, but still difficult to parse.


text:
Are Pigs able to fly?
Task
Your task is to write a function or a program in a language of your choice that analyzes a couple of statements and determines whether it can be concluded from those statements that pigs are able to fly.
Input
The input is a String that can be read from STDIN, taken as a function argument or even be stored in a file. The input can be described using the following EBNF:
input = statement , {statement};
statement = (("Pigs are ", attribute) | ("Everything that is ", attribute, "is also ", attribute)), ". ";
attribute = [not], ("able to fly" | singleAttribute);
singleAttribute = letter, {letter};
letter = "a" | "b" | "c" | "d" | "e" | "f" | "g"
       | "h" | "i" | "j" | "k" | "l" | "m" | "n"
       | "o" | "p" | "q" | "r" | "s" | "t" | "u"
       | "v" | "w" | "x" | "y" | "z" ;

Example input (see more examples below):
Pigs are green. Everything that is green is also intelligent. Everything that is able to fly is also not intelligent. Pigs are sweet.

Output
The output can be returned by your function, be written to a file or print to STDOUT. There are 5 different cases to be handled:

The given statements are valid, consistent and have as a logical consequence that pigs can fly. In that case, you must output Yes.
The given statements are valid, consistent and have as a logical consequence that pigs can not fly. In that case, you must output No.
It can not be concluded from the given, valid and consistent statements whether pigs can fly or not. In that case, you must output Maybe.
The given statements are valid, but not consistent (i.e. there's a contradiction in the given statements). Since ex falso quodlibet, we decide to output Yes in that case.
The given statements are not valid, i.e. they are not formatted according to the given EBNF. In that case, you may do whatever you want.

Details

You may assume that the given attributes are independent from each other. So, for example, a pig may be young and old, green, red and blue at the same time without causing any inconsistency. However, a pig may not be 'green' and 'not green' at the same time, that's a contradiction and should be handled as described in (4).
For every attribute, assume that there is at least one object (not necessarily a pig) in the universe that has the given attribute, and one object that doesn't have it.

Example Inputs & Outputs
Input:
Pigs are green. Everything that is green is also intelligent. Everything that is able to fly is also not intelligent.

Output: Since Pigs are green and therefore intelligent, and everything that is able to fly is not intelligent, pigs cannot fly. Output is No.
Input:
Pigs are old. Everything that is not able to fly is also not old.

Output: If pigs were not able to fly, they were also not old. But as they are old, you must output Yes.
Input:
Everything that is sweet is also not old. Everything that is intelligent is also blue.

Output: Maybe.
Input:
Pigs are not able to fly. Everything that is red is also sweet. Everything that is sweet is also not red.

Output: Although the first statement implies that pigs can not fly, the following statements contradict each other and therefore the output must be Yes.
Input:
Pigs are very smart. Pigs are able to fly.

Output: Whatever you want, as the String doesn't match the criteria mentioned above.
Winner
This is code-golf, so the shortest correct answer (in bytes) wins. The winner will be chosen one week after the first correct answer is posted.

why does the third example return yes?

I'm considering writing an answer that translates the input into Prolog code.

The third example is not a contradiction: it can be true if nothing exists that is sweet or red. So you can't use that to conclude anything you want, only that nothing sweet or red exists.

You can only conclude that nothing red exists. Sweet, non-red things are fine.

@amalloy sorry, I meant the fourth example. the one that says yes despite beginning by "pigs are not able to fly". why?

@ammoly: Oups, I totally forgot that. I've added a new paragraph to the details section to clarify.

@xem: I hope the new paragraph added to the details section helps you understand the output? As there is a contradiction in the fourth example, case (4) applies and you therefore have to output 'Yes'.

I was hoping for more examples, just so I can do them myself.

@xem: ex falso quodlibet, look it up on wikipedia as the principle of explosion. If a contradiction exists, then anything can be proven. So if 'god exists' is true and 'god does not exist' is true, anything can be shown to be true, therefore pigs can fly can be proven true.

Perl, 363 353 350 347 343 297 266 264
$_=<>;s/able to fly/X/g;$m=' ?(not )?\b(P|\w+)';$h{$1?N.$2:$2}{$3?N.$4:$4}=$h{$3?$4:N.$4}{$1?$2:N.$2}=1while s/$m.{8}$m\.//;map{%x=0,r($_,$_)}%h;sub r{($a,$b)=@_;$e+=$h{$a}{N.$b};$x{$b}++or$h{$a}{$b}=1,map{r($a,$_)}%{$h{$b}}}print$e|$h{P}{X}?Yes:$h{P}{NX}?No:Maybe

Ungolfed/Explanation:
# Read one line from STDIN
$_=<>;
# Replaces special attribute with X
s/able to fly/X/g;
# Prepare attribute match
$m=' ?(not )?\b(P|\w+)';
# Match "Everything that is A is also B. "
#                        "\bA........ \bB\."
# Match "Pigs are B. "
#     "\bP........\bB\."
while(s/$m.{8}$m\.//)
{
  # Add facts for A => B and !B => !A, where A may equal "P" for "Pigs are"
  # Facts are stored as a hash of hashes %h; keys%h are the source attributes;
  # keys%{$h{$a}} are the attributes that follow from attribute $a
  # A "not attribute" is stored as "Nattribute", while a "attribute" is just stored as "attribute"
  $h{$1?N.$2:$2}{$3?N.$4:$4}=$h{$3?$4:N.$4}{$1?$2:N.$2}=1
}
# For all known source attributes ... (this should really be keys%h but we dont mind the extra hashrefs)
map{%x=0,r($_,$_)}%h;
sub r
{
  ($a,$b)=@_;
  # ... remember that we hit a negation and therefor an inconsistency ...
  # If we check/add $b and find an existing "N$b" that means that attribute $b is supposed to be true and not true at the same time
  # It is cheaper bytewise to just add up all consistency errors (remember each fact has a hard value of 1) than to exit right here
  $e+=$h{$a}{N.$b};
  # ... remember that we processed this attribute for the current source attribute so we prevent loops ...
  $x{$b}++or
  # ... add a new fact and then follow the chains (again omitting keys).
  $h{$a}{$b}=1,map{r($a,$_)}%{$h{$b}}
}
# Did we happen on an inconsistency? Do pigs fly? Dont pigs fly? Maybe (Bitwise or is okay too)
print$e|$h{P}{X}?Yes:$h{P}{NX}?No:Maybe

Would be great if you could tell us how it does work / write some comments!

And another upvote for more comments... anything in particular need more explanation?

Added even more comments ...

@AlanBerndt suggested a postfix while. Since he cant comment and I cant approve. I'd like to say thanks! here.

Haskell, 586 566 547 bytes
I wrote this on the assumption that for every property P there must exist some x and y such that P(x) is true and P(y) is false; without this assumption, the fourth example input wouldn't have a contradiction and would answer "No".
#define X p s q m
#define W where
t=0<1;f=0>1;y="Yes"
l=length;r=filter;h=head;(#)=(,)
u 0=[[]];u n=[x:y|x<-[t,f],y<-u$n-1]
c l=all(==h l)l#and l
X[]|or[fst$c$map(!!(n-1))e|n<-[1..l$h e]]=y|z t=y|z f="No"|t="Maybe"W e=m$u$l s;z m=t#m==(c$map h$q e)
X("Pigs":_:y)=p v((r$(==a).(!!k)).q)m z W((k,v),z,a)=s%y
X(_:_:_:y)=p w q((r(\x->(x!!j/=a)||(x!!k==b))).m)v W((j,u),_:_:z,a)=s%y;((k,w),v,b)=u%z
s%("not":w)=(i,u,not p)W(i,u,p)=s%w
s%(_:"to":_:w)=(0#s,w,t)
s%(w:z)=(maybe(l s,s++[w#l s])(#s)$lookup w s,z,t)
main=interact$p[""#0]id id.words.r(/='.')

This should be compiled with the ghc command line option "-cpp". Input must be terminated by EOF (^D). You can try it online at http://melpon.org/wandbox/, but you cannot set command line options. Instead, you can prefix the program with the language option
{-# LANGUAGE CPP #-}

It works by collecting the set of traits, then filtering the set of trait -> truth valuations using the implications in the input. The result is then tested to ensure that every trait can be validly assigned to both True and False (failure here is the ex falso quodlibet case). Finally, it looks for valuations which match the pig facts, checking the value for "able to fly" in each valuation.
Quite a few bytes were lost to threading state around: the set of traits seen so far, the pig-fact-selector function, and the filtering function determined by the implications. Probably the exact same idea would be much shorter in an impure language.
Edit: Saved several bytes by proud haskeller's  suggestion, then a couple extra by replacing the binding of z and "u%drop 2 z" with a binding to "_ : _ : z" and "u%z", saving 3.
Edit 2: Saved some more. Used the (#)=(,) trick to save 2 bytes and learned about pattern synonyms (https://ghc.haskell.org/trac/ghc/wiki/PatternSynonyms), but the notation was too verbose to get a savings from eliminating the rest of the pairs in this program. Squeezed out some more savings by changing the patterns that the parser searches for. For example: if a sentence doesn't start with Pigs and we have anything left in the parser state, we parse a "Everything that is.." sentence. This saved lots of characters in the patterns for X and %.

Your assumption is correct, I forgot to mention it in the first place but I've now added it to the details section!

You should include the flags in your byte count (see the tag wiki for [tag:code-golf]). Therefore, it's 607 bytes.

Is that really correct? The link only mentions flags related to unicode encodings; meta mentions a similar issue regarding C++ flags -D (an obvious cheat) vs -std=c++11 (selecting a specific language variation, so probably ok). IMO the flags used are for enabling a rather common GHC extension of Haskell98, hence analogous to -std=c++11. Ref: http://meta.codegolf.stackexchange.com/questions/1859/ecmascript-6-and-potential-related-flags/1860#1860

you can replace your second definition of u with u n=(:)<$>[t,f]<*>u(n-1) (although this would require importing Control.Applicative, so in second thought it is worse)

oh you can replace <$> by fmap and <*> by ap to get fmap(:)[t,f]\ap`u(n-1)`. oh wait, apparently not all Control.Monad is in the prelude, and ap isn't.

you do can replace the definition of c with c l=(all(==l!!0)l,and l)

Yeah, so many more golfing tricks would be possible with Control.Monad, Control.Applicative, Data.List etc in the prelude..

i think you would be better off using !!0 for head and cut off the (h=head) definition. by my calculations, the definition costs 7 characters, and changing h to !!0/head would cost 5 characters.

also, you can add the definition (#)=(,) so that pairs could be written without parentheses around them - (3,4) will be written as 3#4. this also gives you -XTupleSections for free. my calculations say this should save you about 4 characters.

also, i noticed you forgot one ( at the pattern at row 9

Python, 547 536 525 521 513 509 497 503 501
m=map
o='not ';R={'':{''}}
S=lambda x,y:filter(len,m(str.strip,x.split(y)))
N=lambda a:[o+a,a[4:]][a[:4]==o]
def C(s):a,c=S(s[19:],'is also');return[(a,c),(N(c),N(a))]
X=lambda A:A&set(m(N,A))and 1/0 or A
for a,c in sum(m(lambda x:[('',x[9:])]if'P'==x[0]else C(x),S(raw_input(),'.')),[]):R.setdefault(a,{a}).add(c)
def F(s):
 i,n={s},{s}
 while 1:
  for r in i:n|=R.get(r,n)
  if X(i)>=n:return i
  i|=n
try:a='able to fly';n=N(a);c={n:'No','':'Maybe'}[''.join({a,n}&m(F,R)[0])]
except:c='Yes'
print c

For each a -> b in the input, we add the given clause and its negation not b -> not a  to the set of clauses and then compute the set of propositions that are ->-reachable from any proposition using a fixpoint loop. Whenever we encounter a contradiction, we throw (and later catch) a ZeroDivisionError and print Yes.
Finally, we check if 'able to fly' (and/or its negation) is reachable from the 'is pig' proposition '' and print the appropriate response.
EDIT: This is buggy, fixing it. Fixed.

you should be able to save 2 bytes by putting the try block on the same line as try:

@undergroundmonorail: thanks for spotting that! changed it.

Ruby 1.9.3 (365 364 362)
h='able to fly'
i="(not )?(#{h}|\\w+)"
o=->s{n=Regexp.new(i+" (is also|are) "+i).match s
[[n[2],!n[1]],[n[5],!n[4]]]}
c=e=!z=[]
w=->r{z.member?(r)||(z<<(a,b=r)
c|=a[0]==b[0]&&a[1]!=b[1]
w[[[b[0],!b[1]],[a[0],!a[1]]]]
z.map{|q|q[1]==r[0]&&w[[q[0],r[1]]]})}
y=->x{z.member?([[p='Pigs',!e],[h,x]])}
f=->x{x.split(?.).map{|s|w[o[s]]}
c|y[!e]?'Yes':y[e]?'No':'Maybe'}

Usage
The code above defines a function f, which takes one parameter representing the textual input and returns Yes, No, or Maybe.
For example:
f['Pigs are old. Everything that is not able to fly is also not old.']
=> "Yes"

Online test: http://ideone.com/fxLemg
The ungolfed code (including unit tests) is available here.

*are available (under header "online test"). Plurals, my good friend.

@StanStrum Thanks! I modified the text - I mean the code is available and it also includes unit tests.