text:
Advanced Code Golf - Write a small HTTP server
Your challenge is to write a code-golf HTTP server that accepts GET requests. It obviously doesn't have to be fully featured, but it must serve files from a directory.
Rules:

The HTTP server must listen on TCP port 36895 (0x901F)
It must serve files from /var/www on *NIX systems (e.g. Linux), or C:\hgolf on Windows.
You may ignore all incoming HTTP headers except the GET itself.
If the HTTP method is not GET, you must send back a status code of "405 Not Supported" and a body of "405 Not Supported".
If the file does not exist, you must send back a status code of "404 File Not Found" and a body of "404 File Not Found".
If the file exists but could not be read for some reason, you must send back a status code of "500 Server Error" and a body of "500 Server Error".
If the user requests / or any other existing directory root (e.g. /foo/ where a directory foo exists in /var/www/), respond with a blank page.
Your response must contain at least the minimum headers to allow the content to be displayed on Firefox 8.0 and Internet Explorer 8.0
You must respond with the Content-Type header set, but you only have to support extensions html => text/html and txt => text/plain. For any other file extension, Send application/octet-stream as the content type.
Your code must be able to transfer both ASCII and binary data, though you do not explicitly have to distinguish between the two.
You may not use 3rd party libraries.
You may not use in-built classes or features designed to process HTTP requests (e.g. HttpListener in C#)
If your code will only work on a specific OS due to the socket APIs you've used, please state this.

Solutions must include an image showing it serving a HTML page to a browser.
If you've got any questions, please feel free to ask! :)

This should include a big caveat: do not expose any of these solutions to a public network interface! Since the aim is code golf rather than security, they will be dangerously insecure. (E.g. I expect that all of them would allow .. in the path as a way of breaking out of the defined document root).

Someone always invents a better fool.

@PeterTaylor So I should stop using my solution to serve my blog? :-O

is the http module in Node.js ok?

@Markasoftware You may not use in-built classes or features designed to process HTTP requests (e.g. HttpListener in C#)

Ruby, 383 characters
require 'socket'
v=TCPServer.new 36895
while c=v.accept
h="200 OK";m="";t=""
(c.gets=~/GET (\S*)/)?File.directory?(s='C:/hgolf'+$1)?0:File.exist?(s)?(h+="\r\nContent-Type: "+(s=~/\.txt$/?"text/plain":s=~/\.html$/?"text/html":"application/octet-stream");t="IO.copy_stream(s,c)"):(h=m="404 File Not Found"):(h=m="405 Not Supported")
c.puts "HTTP/1.1 #{h}\r\n\r\n"+m
eval(t)
c.close
end

The restructuring of the code to pack the essential logic into one line which makes the code shorter. Nevertheless, I hope this version can be golfed a little bit further.

Note: I didn't yet implement the "500 Server Error" because I couldn't find an appropriate structure (maybe packaging everything into begin/rescue/end but reading the file is done after the header was sent).

Do you have a screenshot of it in action? :)

@Polynomial Added a screenshot.

Without 500 Server Error it doesn't fit requirements so it should not be accepted.

Bash+netcat: 354 characters

Two script files are used.
No URL decoding, thus file names with spaces and special characters not supported.
Single threaded, so concurrent requests may fail.
Tested on Linux, works nicely with Firefox and Opera.

webserver.sh (33 characters):
while :;do nc -lp36895 -e./w;done

w (321 characters):
read m p v
p=/var/www$p
t=text/plain
[[ -r $p ]]||s='500 Server Error'
[[ -e $p ]]||s='404 Not Found'
[[ $m != GET ]]&&s='405 Not Supported'
[[ $s||-d $p ]]||case ${p##*.} in
txt);;html)t=text/html;;*)t=application/octet-stream;;esac
echo "$v ${s-200 Ok}
Content-Type:$t
"
[[ $s ]]&&echo $s||{ [[ -d $p ]]&&echo||cat $p;}

Sample run:
bash-4.2$ ./webserver.sh

Sample visit (Firefox 19.0):

Netcat - it'll do anything!

Curious... whenever I try this nc tells me that the -e option is not supported. Any ideas?

You probably have nc from BusyBox. I use GNU netcat.

What about text/plain?

What you mean @ugoren? Files with .txt extension and error pages are both served as text/plain. See here some tests: http://pastebin.com/ErNtvQzx (Ignore the read errors, they are usual reactions of the client netcat.)

Sorry, my mistake. I missed saw that text/plain is missing in the case, but didn't see it at the top.

You scared me, @ugoren. I thought I missed a bug. I moved the text/plain separately to ensure that error pages and “directory index” pages also have Content-Type response header.

webserver.sh can be golfed to for((;;)){ nc -lp36895 -e./w;} (30 chars)

Indeed. I read your related tip but had no time to apply it in my posts. Thank you, @professorfish.

Haskell, 636
import Data.List;import Network;import System.Directory;import System.IO
main=listenOn(PortNumber 36895)>>=l;l s=(n s`catch`\_->u())>>l s
n s=do(h,_,_)<-accept s;z h>>=q.words>>=hPutStr h;hClose h
q("GET":p:_)=d$"/var/www"++p;q _=c"405 Not Supported"
d p=doesFileExist p>>=f p;e x|x=u$s""""|1<3=c"404 File Not Found"
f p x|x=t p`catch`\_e->c"500 Server Error"|1<3=doesDirectoryExist p>>=e
t p=fmap(s$"\nContent-Type: "++g p)$z=<<openBinaryFile p ReadMode
r s h b=["HTTP/1.0 ",s,h,"\n\n",b]>>=id
g p|b".html"p="text/html"|b".txt"p="text/plain"|1<3="application/octet-stream"
s=r"200 OK";c s=u$r s[]s;u=return;b=isSuffixOf;z=hGetContents

Files are streamed lazily, so serving large files does not use much memory, but this also means that only errors at the start of transmission (e.g. permission errors) result in a 500 Server Error.

Tested on Ubuntu 10.10. Can be ported to Windows by changing the /var/www to C:/hgolf and changing main= to main=withSocketsDo$, since the sockets library on Windows requires explicit initialization.
Ungolfed version:
import Data.List
import Network
import System.Directory
import System.IO

root = "/var/www"

main = do
    s <- listenOn (PortNumber 36895)
    loop s

loop s = (next s `catch` \e -> return ()) >> loop s

next s = do
    (h, _, _) <- accept s
    hGetContents h >>= serve >>= hPutStr h
    hClose h

serve req =
    case words req of
        ("GET" : path : _) -> deliver (root ++ path)
        _ -> complain "405 Not Supported"

deliver path = do
    isFile <- doesFileExist path
    if isFile
        then transfer path `catch` (\e -> complain "500 Server Error")
        else do isDir <- doesDirectoryExist path
                if isDir
                    then return $ response "200 OK" [] ""
                    else complain "404 File Not Found"

transfer path = do
   body <- hGetContents =<< openBinaryFile path ReadMode
   return $ response "200 OK" ["Content-Type: " ++ guessType path] body

response status headers body =
  concat [unlines $ ("HTTP/1.0 " ++ status) : headers, "\n", body]

complain status = return $ response status [] status

guessType path
    | ".html" `isSuffixOf` path = "text/html"
    | ".txt"  `isSuffixOf` path = "text/plain"
    | otherwise                 = "application/octet-stream"

Python 2, 525 510 493 (bending the rules 483) chars
from socket import*
from os.path import*
a=socket(2,1)
a.bind(("",80))
a.listen(5)
while 1:
 c,_=a.accept();i=c.recv(512).split("\n")[0].split();z=i[1][1:];m=i[2]+(i[0]!="GET"and"405 Not Supported\n\n"*2or exists(z)-1and"404 File Not Found\n\n"*2or"200 OK\n")
 if(len(m)>16)+isdir(z)<1:
    try:f=open(z,"rb");m+="Content-Type: "+{".txt":"text/plain","html":"text/html"}.get(z[-4:],"application/octet-stream")+"\n\n"+f.read()
    except:m=i[2]+"500 Server Error\n\n"*2
 c.send(m);c.close()

I stated that I only need 483 chars if I bend the rules because the last ;c.close() could be omitted. This is because the moment the next client gets accepted, the socket gets closed anyway. This will of course increase waiting time somewhat (Firefox will only display the page when the next client connects, Chrome will display it before, but will continue to load), but the rules do not require me to respond to the request immediately, only to do so at some point.
I am not certain whether this will work on Unixes because I used send instead of sendall and send does not guarantee to actually send everything it is fed. It does work on Windows.

You are also bending the rules by serving the current directory instead of C:\hgolf (8 characters) on port 80 instead of 36895 (3 characters).

Groovy, 507 500 489 485
for(ServerSocket s=new ServerSocket(36895);;){t=s.accept()
o=t.outputStream
o<<"HTTP/1.1 "
e='\r\n'*2
d={o<<"$it$e$it"}
p=t.inputStream.newReader().readLine().split()
if(p[0]!='GET')d'405 Not Supported'else{f=new File('/var/www/',p[1])
if(!f.exists())d'404 File Not Found'else if(f.isFile()){x=f.name=~/\.(.*)/
o<<"200 OK\r\nContent-Type: ${[html:'text/html',txt:'text/plain'][!x?:x[0][1]]?:'application/octet-stream'}$e"
try{o.bytes=f.bytes}catch(t){d"500 Server Error"}}}
o.close()}

Added the image download to show binary files are working properly - had a few issues with them to begin with.
Can anyone suggest a shorter way to read the input?

Erlang (escript) 575
Very dirty Erlang escript. There have to be one blank line at beginning of file to work well:
$ cat hgolf.erl

main(_)->{ok,L}=gen_tcp:listen(36895,[]),s(L).
s(L)->{ok,S}=gen_tcp:accept(L),receive{tcp,S,"GET "++R}->[F|_]=string:tokens("/var/www"++R," "),case case file:read_file_info(F)of{ok,{_,_,regular,read,_,_,_,_,_,_,_,_,_,_}}->a;{ok,_}->"500 Server Error";_->"404 File Not Found"end of a->h(S,"200 OK\r\nContent-Type: "++case lists:reverse(F)of"lmth."++_->"text/html";"txt."++_->"text/plain";_->"application/octet-stream"end,[]),file:sendfile(F,S);E->h(S,E,E)end;_->E="405 Not Supported",h(S,E,E)end,gen_tcp:close(S),s(L).
h(S,H,B)->gen_tcp:send(S,["HTTP/1.1 ",H,"\r\n\r\n",B]).

How to run
$ escript hgolf.erl

Edit:
I have squeezed out 20 chars. case is surprisingly shorter than function with even one argument and three clauses.

btw you could post that thing in this question, too (http://codegolf.stackexchange.com/questions/31647/)

VB.NET, 7203

You can define any port and any base directory using --port and --base, respectively.
No, this isn't really a golfing solution. But being VB.NET, there's really no point anyway. On the plus side, this one has lots more features.
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Text.RegularExpressions

Public Module Server
    Private Const READ_BUFFER_SIZE As Integer = 1024

#Region "Content-Type Identification"
    Private ReadOnly ContentTypes As New Dictionary(Of String, String) From {
            {".htm", "text/html"},
            {".html", "text/html"},
            {".js", "text/javascript"},
            {".css", "text/css"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            {".jpeg", "image/jpeg"},
            {".gif", "image/gif"}
        } 'Feel free to add more.

    ''' <summary>
    ''' Retrieves the Content-Type of the specified file.
    ''' </summary>
    ''' <param name="filepath">The file for which to retrieve the Content-Type.</param>
    Private Function GetContentType(ByVal filepath As String) As String
        Dim ext As String = IO.Path.GetExtension(filepath)

        If ContentTypes.ContainsKey(ext) Then _
            Return ContentTypes(ext)

        Return "text/plain"
    End Function
#End Region

#Region "Server Main()"
    Public Sub Main(ByVal args() As String)
        Try
            'Get a dictionary of options passed:
            Dim options As New Dictionary(Of String, String) From {
                {"--port", "8080"},
                {"--address", "127.0.0.1"},
                {"--base", String.Empty}
            }

            For i As Integer = 0 To args.Length - 2
                If args(i).StartsWith("-") AndAlso options.ContainsKey(args(i)) Then _
                    options(args(i)) = args(i + 1)
            Next

            'Get the base directory:
            Dim basedir As String = Path.Combine(My.Computer.FileSystem.CurrentDirectory, options("--base"))

            'Start listening:
            Dim s As New TcpListener(IPAddress.Parse(options("--address")), Integer.Parse(options("--port"))) 'Can be changed.
            Dim client As TcpClient

            s.Start()

            Do
                'Wait for the next TCP client, and accept the connection:
                client = s.AcceptTcpClient()

                'Read the data being sent to the server:
                Dim ns As NetworkStream = client.GetStream()
                Dim sendingData As New Text.StringBuilder()
                Dim rdata(READ_BUFFER_SIZE - 1) As Byte
                Dim read As Integer

                Do
                    read = ns.Read(rdata, 0, READ_BUFFER_SIZE)
                    sendingData.Append(Encoding.UTF8.GetString(rdata, 0, read))
                Loop While read = READ_BUFFER_SIZE

                'Get the method and requested file:
#If Not Debug Then
                Try
#End If
                If sendingData.Length > 0 Then
                    Dim data As String = sendingData.ToString()

                    Dim headers() As String = data.Split({ControlChars.Cr, ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries)
                    Dim basicRequestInfo() As String = headers(0).Split(" "c)
                    Dim method As String = basicRequestInfo(0)
                    Dim filepath As String = basicRequestInfo(1).Substring(1)
                    Dim actualFilepath As String = Path.Combine(basedir, Uri.UnescapeDataString(Regex.Replace(filepath, "\?.*$", "")).TrimStart("/"c).Replace("/"c, "\"c))
                    Dim httpVersion As String = basicRequestInfo(2)

                    'Set up the response:
                    Dim responseHeaders As New Dictionary(Of String, String)

                    Dim statusCode As String = "200"
                    Dim statusReason As String = "OK"
                    Dim responseContent() As Byte = {}

                    'Check the HTTP version - we only support HTTP/1.0 and HTTP/1.1:
                    If httpVersion <> "HTTP/1.0" AndAlso httpVersion <> "HTTP/1.1" Then
                        statusCode = "505"
                        statusReason = "HTTP Version Not Supported"
                        responseContent = Encoding.UTF8.GetBytes("505 HTTP Version Not Supported")
                    Else

                        'Attempt to check if the requested path is a directory; if so, we'll add index.html to it:
                        Try
                            If filepath = String.Empty OrElse filepath = "/" Then
                                actualFilepath = Path.Combine(basedir, "index.html")
                                filepath = "/"
                            ElseIf Directory.Exists(actualFilepath) Then
                                actualFilepath = Path.Combine(actualFilepath, "index.html")
                            End If
                        Catch
                            'Ignore the error; it will appear once again when we try to read the file.
                        End Try

                        'Check the method - we only support GET and HEAD:
                        If method = "GET" Then
                            'Make sure nobody's trying to hack the system by requesting ../whatever or an absolute path:
                            If filepath.Contains("..") Then
                                statusCode = "403"
                                statusReason = "Forbidden"
                                responseContent = Encoding.UTF8.GetBytes("403 Forbidden")
                                Console.WriteLine("Access to {0} was forbidden.", filepath)
                            ElseIf Not File.Exists(actualFilepath) Then
                                statusCode = "404"
                                statusReason = "Not Found"
                                responseContent = Encoding.UTF8.GetBytes("404 Not Found")
                                Console.WriteLine("A request for file {0} resulted in a 404 Not Found. The actual path was {1}.", filepath, actualFilepath)
                            Else
                                Try
                                    'Read the requested file:
                                    responseContent = File.ReadAllBytes(actualFilepath)

                                    'Get the requested file's length:
                                    responseHeaders.Add("Content-Length", responseContent.Length.ToString())

                                    'And get its content type too:
                                    responseHeaders.Add("Content-Type", GetContentType(actualFilepath))
                                Catch
                                    'Couldn't get the file's information - assume forbidden.
                                    statusCode = "403"
                                    statusReason = "Forbidden"
                                    responseContent = Encoding.UTF8.GetBytes("403 Forbidden")
                                End Try
                            End If
                        ElseIf method = "HEAD" Then
                            'Make sure nobody's trying to hack the system by requesting ../whatever or an absolute path:
                            If filepath.Contains("..") Then
                                statusCode = "403"
                                statusReason = "Forbidden"
                                responseContent = Encoding.UTF8.GetBytes("403 Forbidden")
                                Console.WriteLine("Access to {0} was forbidden.", filepath)
                            ElseIf Not File.Exists(actualFilepath) Then
                                statusCode = "404"
                                statusReason = "Not Found"
                                responseContent = Encoding.UTF8.GetBytes("404 Not Found")
                                Console.WriteLine("A request for file {0} resulted in a 404 Not Found.", filepath)
                            Else
                                Try
                                    'Get the requested file's length:
                                    responseHeaders.Add("Content-Length", New FileInfo(actualFilepath).Length.ToString())

                                    'And get its content type too:
                                    responseHeaders.Add("Content-Type", GetContentType(actualFilepath))
                                Catch
                                    'Couldn't get the file's information - assume forbidden.
                                    statusCode = "403"
                                    statusReason = "Forbidden"
                                    responseContent = Encoding.UTF8.GetBytes("403 Forbidden")
                                End Try
                            End If
                        Else
                            'Unknown method:
                            statusCode = "405"
                            statusReason = "Method Not Allowed"
                        End If

                        'Prepare the response:
                        Dim response As New List(Of Byte)

                        'Prepare the response's HTTP version and status:
                        response.AddRange(Encoding.UTF8.GetBytes("HTTP/1.1 " & statusCode & statusReason & ControlChars.CrLf))

                        'Prepare the response's headers:
                        Dim combinedResponseHeaders As New List(Of String)
                        For Each header As KeyValuePair(Of String, String) In responseHeaders
                            combinedResponseHeaders.Add(header.Key & ": " & header.Value)
                        Next
                        response.AddRange(Encoding.UTF8.GetBytes(String.Join(ControlChars.CrLf, combinedResponseHeaders.ToArray())))

                        'Prepare the response's content:
                        response.Add(13)
                        response.Add(10)
                        response.Add(13)
                        response.Add(10)
                        response.AddRange(responseContent)

                        'Finally, write the response:
                        ns.Write(response.ToArray(), 0, response.Count)
                    End If
                End If
#If Not Debug Then
                Catch ex As Exception
                    Console.WriteLine("Serious error while processing request:")
                    Console.WriteLine(ex.ToString())
                    Dim errorResponse() As Byte = Encoding.UTF8.GetBytes("HTTP/1.1 500 Internal Server Error" & ControlChars.CrLf & ControlChars.CrLf & "500 Internal Server Error")
                    ns.Write(errorResponse, 0, errorResponse.Length)
                End Try
#End If

                'And at last, close the connection:
                client.Close()
            Loop
        Catch ex As SocketException
            Console.WriteLine("SocketException occurred. Is the socket already in use?")
            Console.ReadKey(True)
        End Try
    End Sub
#End Region

End Module

I even decided to put it on GitHub :) https://github.com/minitech/DevServ

Haha, yeah, VB.NET isn't exactly the golfer's language of choice. Still nice though.

VB.NET can be golfed; there are quite a few tricks you can use.

@Joey: Yes, but there's no way I can compete with the current answers. I would take the comments out first :)

@minitech I've golfed your answer a little and posted it (https://codegolf.stackexchange.com/a/21757/15022), and if you want, copy the code from that and I'll delete my answer.

@minitech On line 46 of the code on Github, you have For i As Integer = 0 To args.Length - 2. If you add Step 2 to the end of that line, you increase the counter by two instead of 1.

C# (869)

using E=System.Text.Encoding;using System.IO;class C{static void Main(){var l=new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(16777343,36895));l.Start();while(0<1){using(var c=l.AcceptTcpClient()){try{string v="200 OK",r="",t="text/plain",p;var s=c.GetStream();var b=new byte[c.ReceiveBufferSize];s.Read(b,0,b.Length);var h=E.UTF8.GetString(b).Split();b=null;try{if(h[0]=="GET"){p="/var/www"+h[1];if(File.Exists(p)){b=File.ReadAllBytes(p);t=p.EndsWith(".txt")?t:p.EndsWith(".html")?"text/html":"application/octet-stream";}else if(!Directory.Exists(p)){v=r="404 Not Found";}}else{v=r="405 Not Supported";}}catch(IOException){v=r="500 Server Error";}b=b??E.UTF8.GetBytes(r);var m=E.UTF8.GetBytes("HTTP/1.1 "+v+"\r\nContent-Type:"+t+";charset=utf-8\r\nContent-Length:"+b.Length+"\r\n\r\n");s.Write(m,0,m.Length);s.Write(b,0,b.Length);}catch(IOException){}}}}}

Ungolfed
using System.Text;
using System.IO;

class C {
    static void Main() {
        var listener = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(16777343,36895));
        listener.Start();

        while (true){
            using (var client = listener.AcceptTcpClient()) {
                try {
                    string responseCode = "200 OK", responseBody = "", contentType = "text/plain", path;
                    var stream = client.GetStream();

                    var bytes = new byte[client.ReceiveBufferSize];
                    stream.Read(bytes,0,bytes.Length);

                    var requestHeaders = Encoding.UTF8.GetString(bytes).Split();
                    bytes = null;

                    try{
                        if(requestHeaders[0] == "GET"){
                            path = "/var/www" + requestHeaders[1];

                            if (File.Exists(path)) {
                                bytes = File.ReadAllBytes(path);
                                contentType = path.EndsWith(".txt") ? contentType : path.EndsWith(".html") ? "text/html" : "application/octet-stream";
                            } else if (!Directory.Exists(path)){
                                responseCode = responseBody = "404 Not Found";
                            }
                        } else {
                            responseCode = responseBody = "405 Not Supported";
                        }
                    } catch(IOException) {
                        responseCode = responseBody = "500 Server Error";
                    }
                    bytes = bytes ?? Encoding.UTF8.GetBytes(responseBody);

                    var responseHeader=Encoding.UTF8.GetBytes("HTTP/1.1 " + responseCode + "\r\nContent-Type:" + contentType + ";charset=utf-8\r\nContent-Length:" + bytes.Length + "\r\n\r\n");
                    stream.Write(responseHeader, 0, responseHeader.Length);
                    stream.Write(bytes, 0, bytes.Length);
                } catch(IOException) {
                    // If a client disconnects in the middle of a request (e.g. by refreshing the browser) an IOException is thrown.
                }
            }
        }
    }
}

Node.js - 636
Only tested on Linux, won't work on Windows.
a=require
b=a('fs')
function c(){g+=o+h+i+j+f+f+o+f}
a('net').createServer(function(d){d.on('data',function(e){f='\r\n'
g='HTTP/1.1 '
h=f+'Content-Type: '
i='text/'
j='plain'
if(k=/^GET (\S+)/.exec((e+'').split(f)[0])){k=k[1]
l=k.slice(k.lastIndexOf('.')+1)
m='www'+k
if(b.existsSync(m)){if(b.lstatSync(m).isDirectory()){g+='200 OK'+h+i+j+f}else{try{n=b.readFileSync(m)
g+='200 OK'+h
if(l=='txt')g+=i+j
else if(l=='html')g+=i+l
else g+='application/octet-stream'
g+=f+f+n}catch(_){o='500 Server Error'
c()}}}else{o='404 File Not Found'
c()}}else{o='405 Not Supported'
c()}
d.write(g)
d.end()})
d.on('error',function(){})}).listen(36895)

Python 3 - 655
from socket import*
import re
import threading
def x(c):
    u=str(c.recv(1024))
    if not'GET'in u:conn.sendall(t("HTTP/1.1 405 Not Supported"))
    u=re.search('GET [^\s]+ HTTP/1.1',u).group(0).split(" ")[1];u="/index.html" if u == "/" else u;e=u.split(".")[1]
    try:c.sendall(t("HTTP/1.1 200 OK\nContent-Type: "+({'txt':'text/plain','html':'text/html'}[e]if e in'txthtml'else'application/octet-stream')+"\n\n")+open("."+u,'rb').read())
    except:c.sendall(t("HTTP/1.1 404 File Not Found\n\n404 File Not Found"))
t=lambda s: bytes(s,'utf8')
s=socket(AF_INET,SOCK_STREAM)
s.bind(('',36895))
s.listen(10)
while 1:threading.Thread(target=x,args=[s.accept()[0]]).run()

afaik you can use 1-space indentation (rather than 4) to save 15 chars

Scala, 653 characters
import java.net._
import java.io._
object I extends App{val l=new ServerSocket(36895)
while(true){var (s,e,c,b)=(l.accept,"200 OK","text/html","")
var h=io.Source.fromInputStream(s.getInputStream).getLines.next.split(" ")
if(h(0)!="GET"){e="405 Not Supported"
b=e}else{var f=new File("/var/www"+h(1))
if(!f.isDirectory){if(f.exists){var q=h(1).split("\\.").last
if(q=="txt")c="text/plain"else if(q!="html")c="application/octet-stream"
try b=io.Source.fromFile(f).mkString catch{case _=>e="500 Server Error";b=e}}else{e="404 File Not Found"
b=e}}}
var o=new PrintWriter(s.getOutputStream)
o.print("HTTP/1.1 "+e+"\nContent-Encoding:"+c+"\n\n"+b)
o.close}}

A screenshot of it running on my MacBook:

Not great, but I'll have a go at squashing it a bit when I've got some time later.

Got a screenshot of it in action?

@Polynomial Yeah sorry, was in a bit of a rush to go somewhere earlier.

VB.Net (3504 characters):
Imports System.IO:Imports System.Net:Imports System.Net.Sockets:Imports System.Text:Imports System.Text.RegularExpressions:Module x:Dim s=1024,ct As New Dictionary(Of String,String)From{{".htm","text/html"},{".html","text/html"},{".js","text/javascript"},{".css","text/css"},{".png","image/png"},{".jpg","image/jpeg"},{".jpeg","image/jpeg"},{".gif","image/gif"}}:Function b$(f$):Dim ext$=Path.GetExtension(f$):Return If(ct.ContainsKey(ext$),ct(ext$),"text/plain"):End Function:Sub Main(a$()):Try:Dim z As New Dictionary(Of String,String)From{{"--port","8080"},{"--address","127.0.0.1"},{"--base",""}}:For i As Integer=0 To a.Length-2:If a$(i).StartsWith("-")AndAlso z.ContainsKey(a$(i))Then:z(a$(i))=a$(i+1):Next:Dim b$=Path.Combine(My.Computer.FileSystem.CurrentDirectory,z("--base")),s As New TcpListener(IPAddress.Parse(z("--address")),Integer.Parse(z("--port"))),c As TcpServer:s.Start():Do:c=s.AcceptTcpServer():Dim ns As NetworkStream=c.GetStream():Dim sd As New Text.StringBuilder(),rd(s-1)As Byte,r As Integer:Do:r=ns.Read(rd,0,s):sd.Append(Encoding.UTF8.GetString(rd,0,r)):Loop While r=s:Try:If sd.Length>0 Then:Dim dd$=sd.ToString(),h$()=dd$.Split({ControlChars.Cr,ControlChars.Lf},StringSplitOptions.RemoveEmptyEntries),br$()=h$(0).Split(" "c),mt$=br$(0),f$=br$(1).Substring(1),af$=Path.Combine(b$,Uri.UnescapeDataString(Regex.Replace(f$,"\?.*$","")).TrimStart("/"c).Replace("/"c,"\"c)),hv$=br$(2),rh As New Dictionary(Of String,String),sc$="200",sr$="OK",rc()As Byte={}:If hv$<>"HTTP/1.0"AndAlso hv$<>"HTTP/1.1"Then:sc$="505":sr$="HTTP Version Not Supported":rc=Encoding.UTF8.GetBytes("505"&sr$):Else:Try:If f$=String.Empty OrElse f$="/"Then:af$=Path.Combine(b$,"index.html"):f$="/":ElseIf Directory.Exists(af$)Then:af$=Path.Combine(af$,"index.html"):End If:Catch:End Try:If mt$="GET"Then:If f$.Contains("..")Then:sc$="403":sr$="Forbidden":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("{0} forbidden.",f$):ElseIf Not File.Exists(af$)Then:sc$="404":sr$="Not Found":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("{0} resulted in 404 Not Found. Path {1}.",f$,af$):Else:Try:rc=File.ReadAllBytes(af$):rh.Add("Content-Length",rc.Length&""):rh.Add("Content-Type",b$(af$)):Catch:sc$="403":sr$="Forbidden":rc = Encoding.UTF8.GetBytes(sc$&" "&sr$):End Try:End If:ElseIf mt$="HEAD"Then:If f$.Contains("..")Then:sc$="403":sr$="Forbidden":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("{0} forbidden.",f$):ElseIf Not File.Exists(af$)Then:sc$="404":sr$="Not Found":rc=Encoding.UTF8.GetBytes(sc$&" "&sr$):Console.WriteLine("404 Not Found: {0}",f$):Else:Try:rh.Add("Content-Length",New FileInfo(af$).Length&""):rh.Add("Content-Type",b$(af$)):Catch:sc$="403":sr$="Forbidden":rc = Encoding.UTF8.GetBytes(sc$&" "&sr$):End Try:End If:Else:sc$="405":sr$="Method Not Allowed":End If:Dim rr As New List(Of Byte):rr.AddRange(Encoding.UTF8.GetBytes("HTTP/1.1 "&sc$&sr$&ControlChars.CrLf)):Dim cr As New List(Of String):For Each h As KeyValuePair(Of String,String)In rh:cr.Add(h.Key&": "&h.Value):Next:rr.AddRange(Encoding.UTF8.GetBytes(String.Join(ControlChars.CrLf,cr.ToArray()))):rr.Add(13):rr.Add(10):rr.Add(13):rr.Add(10):rr.AddRange(rc):ns.Write(rr.ToArray(),0,rr.Count):End If:End If:Catch ex As Exception:Console.WriteLine("Error:"):Console.WriteLine(ex.ToString()):Dim e()As Byte=Encoding.UTF8.GetBytes("HTTP/1.1 500 Internal x Error"&ControlChars.CrLf &ControlChars.CrLf &"500 Internal x Error"):ns.Write(e,0,e.Length):End Try:c.Close():Loop:Catch:End Try:End Sub:End Module

Golfed from @minitech's answer.

Lua 5.1 in 435 434 bytes
s=require'socket'.bind('*',36895)while{}do
c=s:accept()u=c:receive'*l':match'GET (.*) HTTP'f,_,e=io.open('/var/www'..u,'rb')d=z
x=z if f then d,_,x=f:read'*a'end
h=u and(x==21 and''or(e==2 and'404 File Not Found'or d
and('200 OK\r\nContent-Type:'..(({txt='text/plain',html='text/html'})[u:match'%.(.-)$']or'application/octet-stream'))or'500 Server Error'))or'405 Not Supported'c:send('HTTP/1.1 '..h..'\r\n\r\n'..(d
or h))c:close()end

...and the proof...


text:
Implement a Graphing Calculator
There have been many questions involving calculators; however, it does not appear that any involve implementing a graphing calculator.
The Challenge
You are to write a complete program that takes multiple formulas as input from STDIN and graphs them to STDOUT. Input will take the form f1(x)=x^2-x-1. There will be an f followed by a number 0-9 (inclusive), followed by (x)=, followed by the formula to graph. Your program should be able to take input, graph, take more input, graph, etc.
This is code golf.
Your graph should have the X-axis range from -5 to 5, with a resolution of at least one point every 1/2 unit. Y-axis requirements are the same. This may seem like a small range compared to modern calculators, but it will most likely be trivial in increase this. The graph should have the axis drawn on them, with tick marks in the form of + on the integers.
The formula should be evaluated with the normal order of operation. There will not be any vertical asymptotes/undefined regions in these formulas. The variable will always be x.  If two formulas are entered with the same equation number, the oldest one should be erased and replaced with the new formula. Blank formulas should evaluate to zero. Since it is likely that the formula will not always give a nice multiple of 1/2, you are to round to the nearest 1/2.
When a formula is graphed, its line should be formed out of the number of the formula. When a line crosses an axis, the axis should be drawn on top. When two lines cross each other, it does not matter which is shown.
Example Input
f1(x)=x+1

Output
          +       1
          |      1
          +     1
          |    1
          +   1
          |  1
          + 1
          |1
          +
         1|
+-+-+-+-+-+-+-+-+-+-+
       1  |
      1   +
     1    |
    1     +
   1      |
  1       +
 1        |
1         +
          |
          +

Input
f2(x)=(x^2)^0.25

Output
          +       1
          |      1
          +     1
          |    1
          +   1
          |  1
2222      + 1    2222
    222   |1  222
       22 + 22
         2|2
+-+-+-+-+-+-+-+-+-+-+
       1  |
      1   +
     1    |
    1     +
   1      |
  1       +
 1        |
1         +
          |
          +

Input
f1(x)=-x

(note, it is acceptable for your program to reject this input and only except 0-x or x*-1, but this should be documented)
Output
1         +
 1        |
  1       +
   1      |
    1     +
     1    |
2222  1   +      2222
    2221  |   222
       22 + 22
         2|2
+-+-+-+-+-+-+-+-+-+-+
          |1
          + 1
          |  1
          +   1
          |    1
          +     1
          |      1
          +       1
          |        1
          +         1

Perl, 177 characters (+1 command line switch)
perl -nE 's!\^!**!g;s!x!(\$k/2-6)!g;s/\d.*=/;/;$f[$&]=$_;my%a;for$k(@x=2..22){$i=0;$a{int 12.5-2*eval}[$k-2]=$i++for@f}$p="|";$$_[10]=$p^=W,$a{12}=[$p."-+"x10],say map$_//$",@$_ for@a{@x}'

Per this meta thread, I believe this should count as 178 characters in total.
Like the Ruby solution, I'm also using eval and replacing ^ with **.
The input parsing is both incredibly fragile and incredibly robust at the same time: f1(x)= can be written as f 1 ( x ) = or foo 1 bar = or even just 1=, but very strange things could happen if you replaced the f with something that isn't a valid, side-effectless Perl statement.  You have been warned.
Other details of interest include the way the vertical axis is drawn, which exploits the fact that the bitwise XOR of the characters + and | is W.  Obviously, this won't work on EBCDIC systems.
The output is rendered into a hash of arrays, not an array of arrays — it turns out that it takes fewer chars to explicitly truncate the hash keys to integers and then loop over a hash slice than it takes to ensure that an array isn't indexed with negative values.  I could shave off two more characters if it weren't for the annoying way Perl's int truncates negative values towards zero, which forced me to number the output rows from 2 to 22 instead of 0 to 20 in order to avoid rounding artifacts at the top edge of the output area.
I do make use of Perl's liberal string-to-number conversion in the input parsing, where I use the entire string 1(x)= as an array index (it gets converted to just 1).
I could also save three more characters (and make the parsing slightly more robust) by replacing s/\d.*=/;/;$f[$&]=$_ with /\d.*=/;$f[$&]=$', but then I'd have to spend the same number of extra characters to write $' as $'\'' in a single-quoted shell string.  I suppose technically I wouldn't have to count those, but it feels sort of like cheating.

Ruby, 200 characters
f={}
r=0..20
(f[gets[1]]=$_[6..-1].gsub /\^/,'**'
s=r.map{' '*21}
f.map{|n,k|r.map{|y|x=y*0.5-5
v=(2*eval(k)).round
v.abs<11&&y!=10&&s[10-v][y]=n
s[y][10]='+|'[y%2]
s[10][y]='+-'[y%2]}}
puts s)while 1

A plain ruby implementation using the standard evaluator for expressions (^ will be replaced so that the examples given above work fine). It is not very robust and assumes the input exactly as specified in the question.

On the fifth line, could you change y*0.5 to y/2 and get rid of two characters? I don't know Ruby, so I may not be right.

@PhiNotPi Unfortunately this won't work. y/2 does integer division.

Can you use loop{} instead of ()while 1?

Found this via the link on the side bar to the right hand side. This is pretty well done. I had some fun trying to get this smaller, but I only found 9 bytes, one byte relying upon the rational literals introduced in ruby 2.1 (?).

Shaved another 4 bytes to 186. https://pastebin.com/3E1PjsXB

Python 2: 320 characters
N=20
r=range(N+1)
d={}
while(1):
 l=raw_input()
 d[l[1]]=l[6:].replace('^','**')
 g=[[' ']*(N+1) for i in r]
 for n,f in d.items():
  for x in r:
   v=N/2+int(round(2*eval(f.replace('x','(%f)'%(x/2.0-N/4)))))
   if 0<=v<=N:g[N-v][x]=n
 for i in r:
  g[i][N/2]='+|'[i%2]
  g[N/2][i]='+-'[i%2]
 for l in g:print''.join(l)

Could probably be made shorter, but I'm a bit of a newbie at this :)
Making N a variable wastes 9 chars but I like it better that way.

source: Stack Exchange

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

sort: votes


text:
Write a code golf problem in which Java wins
Write a code golf task such that

The only input (if any) required by the task is text from standard input, and the only output required by the task is text to standard output.
There is exactly one correct output string of characters for every possible legal input as defined by the task.
Each possible legal input is less than 10000 characters long.
Each correct output is less than 10000 characters long.
The shortest program (that StackExchange users manage to write) that successfully completes the task for every input is in Java.

The task with the shortest associated Java program wins.

oh..... adding more constraints to Java again ;)

Receive XML as input, output a stacktrace.

48 characters
Task: Ignore any input. Always produce exactly the following output:
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
    at M.<init>(M.java:1)
    at M.<clinit>(M.java:1)

Solution:
enum M{M;System x;{x.setErr(x.out);int y=1/0;}}

Save as M.java, compile with javac M.java and run with java M. It also produces an error message on standard error, but that doesn't violate any of the rules.

I had a similar idea.

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


text:
Decompose a String
Challenge
You are to write the shortest complete program that takes a string as input from STDIN and decomposes it as far as possible, and prints the composition to STDOUT.
To decompose a string, your program finds a substring (of length greater than 1) within the original string, the repetitions of which take up a much of the string as possible. It then creates several new strings, one of which is that substring and the others are the original, split apart at where the substring occurred. You then repeat this process of finding a substring whose repetitions take up as much of those strings as possible.
The end of input is reached when there is a newline (/n).
Output should consist of each substring in the order that it is found, followed by two newlines, followed by everything left at the end of decomposition sorted from longest to shortest, all separated by line breaks.
Example
input
Happy birthday to you! Happy birthday to you! Happy birthday to somebody! Happy birthday to you!

The longest repeated substring is Happy birthday to you!; however, the substring Happy birthday to (with a space after the "to") takes up more space because there is one more repetition of it. The Happy birthday to is outputted. You then end up with several new strings.
Happy birthday to (with space at the end)
you!  (with space)
you!  (with space)
somebody!  (with space)
you!

Here, the substring you!is repeated the most. Even though it is not repeated within any individual string, it is repeated multiple  times throughout all of the strings. The you! is outputted.  Now you have
Happy birthday to (with space)
you!
   (lone space character)
   (lone space)
somebody! (with space)

Here, the substring y(with space) is repeated the most. The y is outputted.  Now you have
Happ
birthda
to (with space)
y (with space)
you!
   (lone space character)
   (lone space)
somebody! (with space)

As far as I can tell, there are no more substrings of length > 1 (the spaces are only one character). You then output each substring that you found, followed by what is above.
Total Output
Happy birthday to
you!
y

somebody!
birthda
Happ
you!
to
y

There should be two lines of just a space at the end, but those are not being displayed. There should also be a space after that single y.

What about y  (with space at end)? Might be worth writing a reference implementation to generate a few more test cases.

Nice catch. I'm going to fix that, and I should probably write a reference implementation.

Ruby, 232 characters
i=[gets.chop]
while l=((0..-2+n=(v=i*'').size).map{|s|(s+1..n).map{|m|c=v[s..m]
u=[i.map{|t|t.split(c)},c].flatten
v.size>(w=(u*'').size)&&[w,c,u]}}.flatten(1)-[false]).sort[0]
puts l[1]
i=l[2]
end
puts
i.sort_by!{|k|-k.size}
puts i

This code reflects my first idea towards the problem. Actually it took much more characters than I thought initially. Nevertheless I still hope to find a shorter solution using a different approach.

If you allow for the weak definition of a substring, then here's a trivial solution.
R, 9 characters (10 with \n)
d=scan()
d

But I suspect you mean strict substring, in which case parroting back the input string will not suffice :-)
R, not yet condensed
d <- "Happy birthday to you! Happy birthday to you! Happy birthday to somebody! Happy birthday to you!"
#d=scan()
# Shorten things
l=list
# Break up into consituent parts
e=strsplit(d,"")[[1]]
g=l()
for(i in 1:nchar(d)) g[[i]]=embed(e,i)
g=lapply( g, function(x) apply(x,1,paste,collapse="") )
# Find max coverage (function takes each element of the g list and returns max X its length) (if type=2 then returns the string instead)
m=function(x,t=1) {
  r=rle(sort(x))
  w=which.max(r$l)
  if(all(r$l[w]<2)) return(0)
  v=r$v[w]
  switch(t,r$l[w]*nchar(v),v)
}
m(g[[which.max(sapply(g,m))]],2)

Which returns " ot yadhtrib yppaH !uoy ot yadhtrib yppaH".
Easy enough to reverse and to iterate this over the remaining string, but I'm going to hold off pending clarification of whether overlapping substrings are allowed.  I suspect not from the example, but this one has more coverage (82 characters) if so.


text:
Resolve quadratic equation
Challenge:
Write the smallest program (in characters) that resolves quadratic equations
i.e. ax² + bx + c = 0
Rules:
Given 3 numbers in R comma-delimited on STDIN: a,b,c (a != 0),
print on STDOUT the 2 roots in C, one per line.
R stands for real numbers, C for complex numbers.
Examples:
Input         Output

1,0,0         r1=0     also accepted: r1=(-0-sqrt(0))/2
              r2=0

1,2,1         r1=-1    also accepted: r1=(-2-sqrt(0))/2
              r2=-1

1,1,1         r1=(-1-isqrt(3))/2  also accepted: r1=(-1-sqrt(-3))/2 or r1=-0.5-0.866i
              r2=(-1+isqrt(3))/2

What does isqrt mean? Are there any constraints on the output format (e.g. canonical forms) or is any expression which resolves to the roots valid?

@Peter Taylor: isqrt stands for i * squareRoot(3). The output have to be on 2 lines as shown in the output column of examples.

But would r1=(-2-sqrt(0))/2 be an acceptable output line? How about r1=(-1-sqrt(-3))/2 ?

@Peter Taylor: I see what you mean, yes both output are acceptable.

I implemented this using a Casio fx-7000G - http://www.rskey.org/detail.asp?manufacturer=Casio&model=fx-7000G - (not sure the extact model). I remember there being only 32 steps for a program and the version I came up with was 31 (including the data entry).

R, 19 chars
polyroot(scan(n=3))

or more strictly following the I/O requirements in 58 chars:
r=polyroot(rev(scan(sep=",")));cat("r1=",r[1],"\nr2=",r[2])

edit: reversed coefficients

Great, now just format the output correctly too...

cat(paste("r",1:2,"=",polyroot(rev(scan(se=",",qui=T))),sep=""),sep="\n") You need to rev the coefficients (two of the three examples were palindromic, so it wasn't obvious).  Also, added quiet=TRUE to scan to suppress "Read 3 items" and shortened all arguments to minimum possible (which was se instead of sep for scan.

J, 21
J's got a verb to do exactly that: p.  It does complex to complex, but your problem is a subset of that.
echo"0>{:p.|.".1!:1[3

As always with J solutions here, I/O and formatting take up 90% of the solution.

Whoever downvoted this: why? If it's buggy, post a comment. If you have a problem with "challenges" which are solved in 1 character in a language which is used in the real world then downvote the question, not the answer.

@J B: Nice one, +1

It looks really nice, but I don't know if it follow the contest rules (load from stdin and output r1=)

@JBernardo: it follows the rules strictly as far as STDIN goes.  STDOUT is a bit more relaxed, but acceptable IMHO: it assumes interactive J, and outputs in a format different from the example, but that's in line with my interpretation of word "example"'s meaning.

Oh, I hadn't noticed the poster required one answer per line.  That at least I can fix easily.

There, fixed.  Noticed along the way that commas are already a perfectly acceptable vector separator, so that's a lot of useless characters down the drain. \o/

Could you perhaps post the output for those of us that don't have J?

@Tommy: J is freely available at jsoftware.com, but I'll edit anyway.

Python 3, 79 chars
a,b,c=eval(input())
d=(b*b-4*a*c)**.5/2/a
x=-b/2/a
print('r1=',x+d,'\nr2=',x-d)

Python's imaginary unity is j and not i. I used Python 3 because the power operator works also on negative numbers.
BTW, is it really needed to write r1= ... and r2= ... ?

+1, It's OK for j instead of i. r1= is part of the challenge.

Nine years later, with the new walrus operator, the formula can be shortened to [p:=b/2+(b*b/4-a*c)**.5/a,b-p], and with formatting strings, the output can just be 'r1='+str(p:=b/2+(b*b/4-a*c)**.5/a)+f'\nr2={b-p}' (walrus operator doesn't work inside formatting strings), saving you 4 characters.

Perl, 96 87 Characters
($a,$b,$c)=eval<>;$_=abs($_=$b*$b-4*$a*$c)**.5/2/$a.i x($_<0);$b/=-2*$a;die"r1=$b+$_
r2=$b-$_"

The line break is intentional, as is a space.
Edit: By reformatting output, I can shorten this to:
($a,$b,$c)=eval<>;$_="sqrt(".($b*$b-4*$a*$c)."))/".2*$a;$b*=-1;die"r1=($b+$_
r2=($b-$_"

Perl, 76 characters (+1 command line switch)
perl -pe '($a,$b,$c)=eval;$d=($b/=-$a)**2-4*$c/$a;$_="-+";s!.!r@+=($b$&sqrt($d))/2\n!g'

Replacing the \n with a literal newline allows a further trivial one-character reduction.
Sample input / output:
1,0,0
r1=(0-sqrt(0))/2
r2=(0+sqrt(0))/2
1,2,1
r1=(-2-sqrt(0))/2
r2=(-2+sqrt(0))/2
1,1,1
r1=(-1-sqrt(-3))/2
r2=(-1+sqrt(-3))/2
1,0,-1
r1=(0-sqrt(4))/2
r2=(0+sqrt(4))/2
2,1,1
r1=(-0.5-sqrt(-1.75))/2
r2=(-0.5+sqrt(-1.75))/2

Yeah, it's not exactly Wolfram Alpha, but I believe it should qualify as acceptable output.

Perl, 101 chars
First stab:
perl -E 'my($x,$y,$z)=pop=~/\d+/g;printf"r%d=(%+d%ssqrt(%d))/%d\n",++$p,-$y,$_,$y**2-4*$x*$z,2*$x for qw/- +/;' 1,2,1

The last $x in printf should be $x*2, and last double quote " a single one '

@M42 : Right. Bitten by the Windows "" issue again.

D (160 chars)
import std.complex;import std.stdio;void main(){real a,b,c;readf("%f,%f,%f",&a,&b,&c);Complex!real j=sqrt(b*b-4*a*c)/2/a,i=-b/2/a;write("r1=",i+j,"\nr2=",i-j);}


text:
What's the ugliest line of R code that still parses?
The goal is to produce a single line of R code that:

Does as little as possible
In as many characters as possible (max of 100 characters)
And is as ugly as possible (where "ugly" can be taken to mean inefficient computational strategies, extraneous characters such as a terminating semicolon, and so forth).

Do your worst, gentlefolk!
Objective criteria for winning
The winning answer will be judged according to the following point scale (the answer with the most points wins):

Generate a sequence from 0 to 10 (100 points)
In as many characters (N) as possible

0 points if N=100
N-100 points if N<100 (i.e. lose a point for every character under 100)
2(100-N) points if N>100 (i.e. lose two points for every character over 100)

Using as many negative examples from the R Inferno as possible

6 points per cited example
Each example only counts once.  This is so because a "heretic imprisoned in [a] flaming tomb" can only be so imprisoned one time.  Thus two global assignments in your line of code only net you 6 points.

Not an objective winning criteria. See the FAQ.

FAQ you @dmckee :) the criteria are pretty objective

I have attempted to make the criteria even more explicit.  If criteria 3 is still not objective enough, I could eliminate it, although I rather like it.

I don't understand the new scoring system at all. Objective 2 is to be as long as possible (subject to max of 100 characters), and you give fewer points for being closer to 100 (and specify points for programs longer than 100??!); objective 3 is to be as ugly as possible, and you give more points for uglier programs. So are points supposed to be good or bad?!

@PeterTaylor Edited to point out that both Objective #2 formulae produce negative points.  Points are good: "The answer with the most points wins".

72 96 characters.
`c`<-function(...){list(...)[[-1]];}->>`c`;`[`=0;`]`=10;c(c,c)(c,c)(c,invisible)(`[`[]:`]`[])[];

Ugliness:

Reusing a standard function name
Using symbols as variable names
Global assignment
Right assignment
Self-redefinition of function
Unnecessary trailing semicolon(s)
Unnecessary sub-scripting numbers
Unnecessary quoting of variable name
Leaves the workspace in a state which will almost certainly break any subsequent code run

Generates the sequence 0-10 (thanks to Andrie for the idea to do that).
output:
 [1]  0  1  2  3  4  5  6  7  8  9 10

That is truly demented.  This is the first time I've used that word as a compliment.  On the other hand, it is an excellent piece of work for someone to de-obfuscate and learn from a careful critique.  Good work.

Brilliant.  Off the top of my head, uglinesses numbers 3,4,5,8,9 are in the Inferno.  So that's 96+6*5=126 points by the grading criteria.

Brilliant solution. Added one more ugliness + 100 char. Replace all the " with single quotes. Having embedding issues. "<-"("c",function(...){list(...)[[-1]];}->>"c");"["=0;"]"=10;c(c,c)(c,c)(c,invisible)("["[]:"]"[])[]

Generate a sequence from 0 to 10.
100 characters
{.=0;for(`~1` in c(1,2,3,4,5,6,7,8,9,10)){.=c(., `~1`,recursive=F)};print(unname(.[drop=T]));rm(.)}
 [1]  0  1  2  3  4  5  6  7  8  9 10

100 characters:
Generate a sequence from 1 to 10.
Note that the numbers 2-10 are NOT in the code... - Bonus points? :-)
Also note that it uses lapply for maximum performance :)
unlist(lapply(LETTERS[-(11:26)],function(x) as.integer(charToRaw(x))-as.integer(charToRaw('A'))+1L))
#[1]  1  2  3  4  5  6  7  8  9 10

100 characters
assign("a",1:10);b<<-paste(c(a),collapse=";");unlist(lapply(strsplit(b,";")[[1]],function(c)c[[1]]))

Not sure if lapply on strsplit is a negative example but it sure should be.
Returns as a character:
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

I(cumsum(Reduce("sum", replicate(paste0(as.integer(T),as.integer(T)), T), accumulate=1-F) - T >0))

should have slightly less than 100 characters and somehow produce 0:10

I count 98 via nchar, counting spaces.  Although on my system replicate can't take a character vector as a length argument.

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


text:
Most destructive "forgot-to-enter-insert-mode" sequence in Vim
Pretend you have an arbitrary text file (which you may choose).
Give the sequence of keystrokes that is most destructive (*) if it was intended to be inserted to the text, but instead was entered in normal mode (i.e. i/a was not pressed). You may not enter visual mode and not quit Vim.
Destructive is defined as follows: The ratio of changed/deleted characters by the number of necessary keystrokes.
You get bonus points if your changes cannot be undone by a fixed number of undos.

Example: Input file without line breaks. Input sequence: dfs.

The [code-golf] tag means fewest characters wins. You challenge is more complicated than that, so I've changed the tagging.

: 0,0 w
:r

ruins everything no undo

I don't understand how it ruins everything! when I run this script it duplicates content of my file and undo works fine! could you explain? Thanks :)

@saeedn :0,0 w should write lines 0 to 0 and :r would then read it (now empty) back in, I don't really have a vim to test it though

Well, first of all, : 0,0 w writes a partial buffer, so (my) Vim refuses to save it, I have to say w! instead of w. So far so good, now :r does not reopen the file. Instead, you have to say :e which will read in the file from the filesystem. However, although with this modifications it does change the buffer, the buffer is far from empty. It contains the first line (because you saved "0,0"). At least undoing does not work.

:set ul=-1
ggdG
:w

This clears contents of file and saves it. No undo is possible because undolevel is set to a negative number, which disables undo operation.
Edit: It's better to write :g/^/d instead of ggdG, because in the latter case you can use p (put) to roll-back the changes.

ggdG could be replaced by: %d

@kenorb Yes, that's shorter, but it also has the problem of ggdG, that can be inverted by putting (p), so :g/^/d seems still a better option :)

@saeedn :%d_ is shorter than :g/^/d and also solves the put problem.

Also, outside of the possible context of writing this answer, I'm not sure if anyone would ever accidentally type those keystrokes in, thinking they were in insert mode. ;)

:set ul=-1
:%s///g
:r!head -c1G</dev/urandom
:w

Disables undo
Deletes characters
Reads 1G of data from /dev/urandom
Saves

Bending the rules, because I am adding characters (a character that isn't there and now is, means a character was changed). I can add as much characters as I want so this score is theoretically infinite.

5 bytes:
:bd!

followed by a press of enter.
Throws away the current state of the file you're editing from memory, so all unsaved changes in that file are lost.  If you have other files open, they are not affected.  This does not quit vim even if you have only one file open.


text:
Find minimum difference between numbers in array
STDIN: Array of integers
STDOUT: Smallest difference (the difference between the closest two numbers in the array).
Rules: Given an array of positive integers find the difference between the closest two numbers in the array. Performance should be taken into consideration.
Example:
STDIN: [55, 99, 6, 29, 1, 523, 3]
STDOUT: 2 (e.g. 3-1)
Scoring: Although somewhat informal, the shortest, most efficient (performance wise) will win. Creativity will also be taken into consideration.

While [tag:fastest-algorithm] questions are allowed, the scoring for this question appears that combined with a subjective metric of "creativity", making this challenge lack an objective winning criterion.

To close voters: this should not be closed as "needs details or clarity", but instead "does not have an objective winning criteria", as although the spec is bare-bones and could do with some explanation (and updating to modern rules), the main issue is with the missing winning criteria

Indeed. Sorry, I misclicked and used the wrong close reason.

The R language
23 characters,  O(n log n)
min(diff(sort(scan())))

Example:
> min(diff(sort(scan())))
1: 55 99 6
4: 29 1 523 3
8:
Read 7 items
[1] 2

...The [1] 2 shows the result 2. (the [1] is to keep track of where in the result vector your are since in R all values are vectors - in this case of length 1)

well done, although not very creative! :p useful functions though.

Mathematica, 23
Min@Differences@Sort@#&

JavaScript, 127 characters
This is a function that takes the array as a string. It may be O((n-1)²/2+n/2-1/2). I have no idea.
function(s){s=eval(s);a=Math.abs;m=a(s[i=0]-s[j=1]);for(;i<s.length;j=++i)for(;++j<s.length;)m=(v=a(s[i]-s[j]))<m?v:m;return m}

it's just O(n^2) time complexity

use sort and you can eliminate the inner loop s=eval(s).sort;m=a(s[i=0]-s[1]);for(i=2;i<s.length;i++)m=(v=a(s[i]-s[i-1]))<m?v:m;

Scala, O(n log n)
Script that reads from STDIN (113 chars)
val s=Console.readLine.split(",").map(_.toInt).sortBy(i=>i)
if(s.size<2)0 else s.tail.zip(s).map(x=>x._1-x._2).min

Function (94 chars)
def m(l:Seq[Int])=if(l.size<2)0 else{val s=l.sortBy(i=>i);s.tail.zip(s).map(x=>x._1-x._2).min}

APL, 16/18 characters
x←⎕⋄⌊/2-/(x[⍒x])

Or with explicit output:
x←⎕⋄⎕←⌊/2-/(x[⍒x])

Example:
      x←⎕⋄⌊/2-/(x[⍒x])
⎕:
      55 9 6 29 1 523 3
2

Explanation:

First expression:

x←⎕: Get the input array ( ⎕ ) and assign it ( ← ) to x.

⋄: Expression separator.
Second expression, right to left:

(x[⍒x]): Sort the input. ⍒x returns the set of indices needed to sort x in descending order, which is used to index x ( x[...] ).
2-/: Splits ( / ) the input array into pairs ( 2 ) and finds the difference ( - ) between each pair.
⌊/: Reduce ( / ) the array using the floor function ( ⌊ ).

I used Dyalog APL for this.

you can shorten by two characters ⌊/2-/(x[⍒x←⎕])

actually by 4 ⌊/2-/x[⍒x←⎕]

J, 28
<./&(}.-}:)@/:~&.(".&stdin)_

Very straightforward J, drawn down by I/O and parsing.  For those who don't read J fluently:

& and @ compose verbs
<. / yields a vector's minimum
( }. - }: ) performs pairwise substraction
/: ~ sorts up
&. performs dark magic so that the next two are used both in the input and output directions
". parses/presents J data
stdin takes care of I/O
_ is a dummy argument to stdin

O(n) space and time
C++ (1644 chars)
Reads from stdin
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

int radix(int const& a, int const& r) {return (a >> (r << 3)) & 0xFF;}

template <int R_>
int radix(int const& a) {return radix(a, R_);}

template <typename It_, typename Cont_>
void distribution(It_ first, It_ const& last, Cont_& d_vector, int const& r) {
        d_vector.resize(256, 0);
        std::fill(d_vector.begin(), d_vector.end(), 0);
        for(; first != last; ++first)
                d_vector[radix(*first, r)]++;
}

template <typename It_, typename Cont_>
void split(It_ first, It_ const& last, Cont_& d_vector, Cont_& slots, int const& r) {
        int cnt = 0;
        for(int i=0; i<256; cnt += d_vector[i++])
                std::swap(d_vector[i], cnt);

        slots.resize(cnt, 0);
        for(; first != last; ++first)
                slots[d_vector[radix(*first, r)]++] = *first;
}

int main(int argc, char* const argv[]) {
        std::istream_iterator<int> in(std::cin);
        std::istream_iterator<int> end;
        std::vector<int>           numbers;

        /// Read numbers
        std::copy(in, end, std::back_inserter(numbers));

        /// Sanity checks
        if(1 >= numbers.size()) {
                std::cerr << "not enough numbers" << std::endl;
                return -1;
        }

        /// Sort the numbers 4 times using different radix
        std::vector<int> d_vector(256, 0);
        std::vector<int> slots;
        for(int r=0; r<4; ++r) {
                distribution(numbers.begin(), numbers.end(), d_vector, r);
                split(numbers.begin(), numbers.end(), d_vector, slots, r);
                numbers.swap(slots);
        }

        /// Compute the min difference
        int prev = numbers[1];
        int min  = prev-numbers[0];
        for(std::size_t i=2; i<numbers.size(); ++i) {
                min = std::min(min, numbers[i]-prev);
        }
        std::cout << min << std::endl;
        return 0;
}

+1 for the radix sort... although, technically, if we're allowed to assume a maximum value for the inputs, I can use the pigeonhole principle to make any of the given solution run in O(1) time and space. (Read up to M inputs, where M is the maximum input value. If there are more inputs, ignore them and output 0; otherwise use the original code, which now runs in bounded time and space since the input length is bounded.)

I get the impression that radix sort is best able to beat quicksort when there are duplicate values in the input. The interesting thing is that this golf challenge allows us to immediately exit with 0 (zero difference) if there is a duplicate. Hence, I think that populating an std::set is a reasonable algorithm. It mightn't be very fast, but it's worst-case performance is reasonable. Extra: Don't forget that the number of keys in radix sort will need to be of the order log n anyway (assuming no duplicates in the input), and hence it won't be significantly faster than quicksort. Am I right?

I like this, although you could have golfed it somewhat. :p

K, 15
......
{min@1_-':x@<x}

 APL 14
(original...21 chars)
{⌊/|{(0≠⍵)/⍵},⍵∘.-⍵}⎕

(edit new shorter...15 chars)
{⌊/|0~⍨,⍵∘.-⍵}⎕

(edit again...14 chars)
⌊/|0~⍨,y∘.-y←⎕

assuming no two numbers are the same
⍝ y←⎕     bring in input
⍝ y∘.-y   create subtraction table of array y against array y
⍝ 0~⍨     remove zeros (from same element against itself
⍝                       on diagonal)
⍝ |       absolute value
⍝ ⌊/      reduce with minimum

D (124 chars) O(n log n) time complexity
void main(){int[]a;int b;while(readf("%d ",&b))a~=b;b=~0>>>1;sort!(d,c){d-=c;c=d<0?-d:d;b=b<c?b:c;return d;}(a);writeln(b);}

using the comparator to keep a running min while sorting

Haskell, 71 characters, O(n log n)
import List;f x=zipWith(-)(tail x)x
main=readLn>>=print.minimum.f.sort

Python 2.6, 56 48 characters, O(n log n)
New version utilizing min, diff, and sort from numpy.  Inspired by Tommy's answer.
from numpy import*
print min(diff(sort(input()))

Original version.  Inspired by Zachary Vance's answer.
a=sorted(input())
print min(y-x for x,y in zip(a,a[1:]))

C# 180 Characters
using System;using System.Linq;class P{static void Main(int[]a){Action<int[]> b=Array.Sort;b(a);a=a.Select((c,d)=>(a.Length>d+1?a[d+1]-c:-1)).ToArray();b(a);Console.Write(a[1]);}}

Readable:
using System;
using System.Linq;
class P
{
    static void Main(int[]a)
    {
        Action<int[]> b = Array.Sort;
        b(a);
        a = a.Select((c, d) => (a.Length > d + 1 ? a[d + 1] - c : -1)).ToArray();
        b(a);
        Console.Write(a[1]);
    }
}

Java
public static int minDifference(int[] A) {
    Arrays.sort(A);
    if (A.length > 1) {
        int d = Math.abs(A[0] - A[1]);
        for (int i = 0; i <= A.length; i++) {
            if (i + 1 < A.length) {
                int t = Math.abs(A[i] - A[i + 1]);
                if (t < d) d = t;
            }
        }
        return d;
    }
    return -1;
}

-1 is returned when an array is too short

Mathematica 39
Sort standard input,subtract each element n from each element n+1, take the absolute value of those differences, and find the minimum of those.
Min[Abs[RotateLeft@# - #] &[Sort@Input[]]]

Perl, 49 characters, O(n log n)
say+(sort{$a-$b}map$a*1-($a=$_),sort{$b-$a}<>)[1]

The input should be on separate lines; the output is printed after input ends.  (I can also make it parse comma-separated input on one line by using the -naF, command line switches and replacing <> with @F.)  The say command is available since Perl 5.10.0 with the -E switch or with use 5.010; per meta its use is allowed at no extra cost.
This uses the same sort-and-diff trick as almost everyone else, with a slight twist to deal with the fact that Perl has no built-in diff command.  It first sorts the input in descending order, substracts each number from the previous one in the list and re-sorts the result in ascending order.  This leaves one negative value (zero minus the largest input) in front of the list, so the code actually outputs the second smallest value.  Of course, this only works as long as the input contains at least one positive number, but fortunately the spec says that all input values must be positive.
(Also, the latest version plays silly tricks with expression evaluation order to shave off a few more chars: apparently $a-($a=$_) always evaluates to 0, but $a*1-($a=$_) ends up saving the previous value of $a on stack before changing it, avoiding the need to store it in a separate variable.  With Perl, there ain't no such thing as "undefined behavior"... :)

J, 10 chars
<./2-/\\:~

It doesn't include explicit input/output, but appending a list to the end like <./2-/\\:~1,2,3 or <./2-/\\:~1 2 3 works as one would expect. I'm not too familiar with J's explicit I/O, unfortunately.
Explanatory refactoring:
sort_down =: \:~
pair_sub =: 2&(-/\)
min =: <./
min pair_sub sort_down 1 2 3

pair_sub is slightly altered, since J has some rules for precedence and verb composition that makes pair_sub =: 2-/\ give an error and pair_sub =: 2&-/\ give a different output when used in the sentence min pair_sub sort_down 1 2 3 as compared to <./2-/\\:~ 1 2 3.

I usually use ".1!:1[1 for taking a single line of input.

Java O(n)
public int minimumDifference(int[] arr) {
    int minimum = 0;

    if (null != arr) {
        int length = arr.length;
        if (length == 1) {
            minimum = arr[0];
        }
        if (length == 2) {
            minimum = Math.abs(arr[0] - arr[1]);
        } else if (length > 2) {
            int minimumSoFar = arr[0];
            int secondMinimumSoFar = arr[0];
            for (int i = 0; i < length; i++) {
                if (arr[i] < minimumSoFar) {
                    minimumSoFar = arr[i];
                }
                if (arr[i] > minimumSoFar && arr[i] < secondMinimumSoFar) {
                    secondMinimumSoFar = arr[i];
                }
            }
            minimum = secondMinimumSoFar - minimumSoFar ;
        }
    }
    return minimum;
}

Python 3.1.3, 77 chars
a=sorted(eval(input()))
print(min([abs(x-y)for x,y in zip(a[::2],a[1::2])]))

Can't you replace abs(x-y) with y-x?

Looks like this would give an incorrect answer with input of [1,3,4,6] because you are striding by 2, which will pair the first with the second items, then the third with the fourth, but does not consider the pair of the second and the third.