text:
418: I'm a teapot
As we all should know, there's a HTTP status code 418: I'm a teapot.
Your mission, should you choose to accept it, is to use your creativitea and write the smallest possible server that responds with the above status code to any and every HTTP request made to it.
Standard loopholes apply, including

Fetching the desired output from an external source
This includes doing an HTTP request to fetch the page with the
question and extracting a solution from that page. This was mildly
amusing back in 2011, but now is derivative and uninteresting.

Meaning you cannot simply redirect the request to another server to have it return the response.
Your server can do anything (or nothing) while no HTTP request is made to it as long as it replies with the correct response once a HTTP request is made.

How much use can we make of external libraries? (e.g. using express for a node.js server)

Should we take the “HTTP” in “any and every HTTP request” literally? I mean, if the request is not HTTP request (or even no request at all, so the client just connects and says nothing), should the server still reply or not?

Is it strictly HTTP when the server immediately sends a response without waiting for the request? (As most of the answers here are doing.)

to each and every http request?  Surely just ones to a coffee: URI?

May we assume we already have root privileges? (e.g. bind() to port 80 is ok)

@MartinBüttner All libraries are welcome, as many languages have such functionality built-in.

@DigitalTrauma Yes, you can assume escalated privileges for your server.

@manatwork Responding to non-HTTP requests is undefined behavior, meaning your program can do anything (or nothing). As long as it replies with the correct response once a HTTP request is made.

@billpg See the comment above.

Most of the answers below do not output the required newlines to signal the end of HTTP response; most browsers would just treat them as prematurely terminated connection.

@LieRyan Feel free to point out the error to the related answers.

Would be something like a config line in httpd.conf ok?

@Knerd I'm leaning on the no side, you're not writing a program, you're simply configuring one.

omg. With the IOT coming around, this status code may have an actual reason to exist!

creativitea? iron druid? :D

@Pietu1998 https://gist.github.com/red-green/474a370f7c3273403827 mine is better

@Luminous It was created for Internet Teapots, and those now exist, so...

@wizzwizz4 HTeaTeaPot

@mbomb007 Hyper Tea Transfer Pot.

Upvoted for creativitea

GNU Awk: 69 characters
A server itself (endlessly serves one request at a time), no library used.
Send 418 to everybody who connects (82 69 characters):
BEGIN{while(s="/inet/tcp/80/0/0"){print"HTTP/1.1 418\n"|&s
close(s)}}

Send 418 to everybody who sends something (93 80 characters):
BEGIN{while(s="/inet/tcp/80/0/0"){s|&getline
print"HTTP/1.1 418\n"|&s
close(s)}}

Send 418 to everybody who sends a valid HTTP GET request (122 109 characters):
BEGIN{while(s="/inet/tcp/80/0/0"){s|&getline
if(/^GET \S+ HTTP\/1\.[01]$/)print"HTTP/1.1 418\n"|&s
close(s)}}

But .. how to connect ? ;)

The same way you connect to any web server. Browser, netcat, telnet, wget, curl, another GNU awk script, … Theoretically it listens on localhost:80, but for that 1) no web server, Skype or other program should use port 80; 2) you have to be super user to open ports below 1024. So for testing is easier to edit the port number in the script to something like 8080 (s="/inet/tcp/8080/0/0") then connect to that. http://pastebin.com/zauP7LMA

I see. Cool. Awk noob here :)

You could possibly save a byte by using smaller port like 8, which is unassigned.

@HannesKarppila, that's correct. But given that all other solutions which explicitly specify a port (excepting the Haskell answer's port 8888) uses port 80, I better keep it like this for comparability.

Bash (33)
nc -lp80 -q1<<<"HTTP/1.1 418
";$0

Are the two newlines necessary?  Seems to work OK with only one for me.  Also by my count the above is 34 bytes - I'm guessing your editor is adding an unnecessary newline or \0 to the end of your file - you can truncate this and it still works.   s='echo HTTP/1.1 418|nc -lp80 -q1;$0' ; echo ${#s} gives 33 for me

@DigitalTrauma: You are right - the final newline is added automatically in here strings: Why does a bash here-string add a trailing newline char? ------ But I see two possible problems: 1. The script expects that it is stored in one of the $PATH directories or that it is called with a path (recursion by $0). ----- 2. HTTP requires that lines are terminated by \r\n not only \n. Here string should be $"HTTP/1.1 418\r\n\r" (longer readable form). ------ And finally: The script could be shorter: The -q1 parameter is not necessary.

@DigitalTrauma, @pabouk: The output needs end with two newlines. So one of the newlines was unnecessary (because of the here-string), but the echo variant does not work (at least Firefox won't recognize it as a 418). However, the \rs aren't needed. The spec says it should be \r\n\r\n, but at least Firefox and Chrome will accept \n\n, so it seems to be in the spirit of golfing not to include them. The -q1 parameter was necessary on my system, because the browser will not close the connection by itself. $0 works fine if the script is made executable and called in that manner.

@marinus Interesting - I was testing with wget which seems to be fine with just one newline

@pabouk - Interesting snippet here http://www.w3.org/Protocols/HTTP/OldServers.html: "Lines should be regarded as terminated by the Line Feed, and the preceeding Carriage Return character ignored"

Regarding -q1: I think that the problem you observed could be related to persistent connections officially defined in HTTP/1.1. I think you should try to use HTTP/1.0 instead. This could work without -q1. ------ Regarding $0 recursion: as the script does not have the shebang sequence and requires root privileges, I called it sudo bash scriptname. This does not work if the directory is not in the $PATH. ------ I did a mistake in my previous comment. The bash code for CR is $'\r' not $"\r".

@pabouk: making this executable and calling it sudo ./scriptname.sh works perfectly fine over here. As for the -q1, Firefox doesn't close the connection even with HTTP/1.0, so nc doesn't end and any further requests will fail.

According to the HTTP specifications, HTTP responses must end in \r\n, so you have to use CRLF instead of LF, adding a byte.

PHP - 85 bytes
<?for($s=socket_create_listen(80);socket_write(socket_accept($s),"HTTP/1.1 418
"););

Saved with Windows-Style (CR-LF) line endings, requires php_sockets enabled.
I actually used this as my error code for the Hard Code Golf: Create a Chatroom challenge, but no one noticed.

Browser-Friendly version
<?for(socket_getsockname($s=socket_create_listen(80),$n);$t="I'm a teapot";socket_write($c=socket_accept($s),"HTTP/1.0 418 $t
Content-Length: $l

<title>418 $t</title>
$t
The requested resource is not suitable for brewing coffee.
$n:80"))$l=124+strlen($n);

Start the script in the CLI, and point your browser at http://localhost.

+1 for user firendlyness / I'm a teapot :-)

Node.js (LiveScript)
http module - 66
require(\http)createServer (->&1.writeHead 418;&1.end!) .listen 80

Inspired by Qwertiy's answer.
net module - 76
require(\net)createServer (->it.write 'HTTP/1.1 418\r\n';it.end!) .listen 80

Ruby + Rack, 19 bytes
run->e{[418,{},[]]}

Must be saved as config.ru, and run with the rackup command.
Or if you prefer "pure" Ruby:
Rack::Handler::WEBrick.run->e{[418,{},[]]}

42 bytes + -rrack flag = 48 bytes

Bash+BSD general commands, 29
Borrowing back a little bit from other answers:
nc -lp80<<<"HTTP/1.1 418
";$0

Works for me with wget.
First answer to use nc, 38
for((;;)){
nc -l 80 <<<HTTP/1.1\ 418
}

I'm assuming root privileges - run as follows:
sudo bash ./418.sh

This also assumes that nc is installed

@ub3rst4r Correct - That is why I stated "BSD general commands", which may be considered as a "library" from the point of view of shell scripting.  From the OP: "All libraries are welcome"

A response must end with a newline, see w3.org/Protocols/HTTP/Response.html

@Nit - Yes - bash "here strings" will automatically be appended with a newline

How about nc -l 80 <<<HTTP/1.1\ 418;$0

The spaces around 80 are not necessary but there is a different problem: HTTP headers section should be terminated by two newlines.

@pabouk - My version of nc seems to expect space between -l and 80; -lp80 can also be used, though doesn't save anything.  My expectation was the same about the space after 80, but my bash (4.3.11) doesn't like it.  Try fold -w 1<<<abc vs fold -w 1 <<<abc - the 1<<<abc is parsed first as a redirection before the rest of the command is expanded.

@pabouk As for the two newlines, I think this is necessary when content follows, but I think any sensible user agent should be able to handle error header followed by end of connection with just one newline.  At least wget, curl and chrome Postman REST client seem to be OK.  I couldn't really tell what firefox was doing.

@pabouk Ok, in the interests of compliance, I've put in 2 newlines.  I was able to save back one byte by using -lp80<<< which seems to help the previous bash redirect problem

Sorry for the confusion with the two spaces. I did not notice that you did not use the -p switch :) I tested the code with Firefox and without two newlines the status code is not recognized.

Ruby (nc system command) - 35
loop{`nc -l 80 <<<"HTTP/1.1 418"`}

DigitalTrauma should get the credit for the idea of using nc, however Ruby can make an infinite loop with fewer characters than Bash :)
Ruby (TCPServer) - 75
require'socket'
s=TCPServer.new 80
loop{(s.accept<<'HTTP/1.1 418
').close}

That newline is intentional -- the actual newline character is one character shorter than "\n".
Ruby (WEBrick HTTPServer) - 87
require'webrick'
(s=WEBrick::HTTPServer.new).mount_proc(?/){|_,r|r.status=418}
s.start

A response must end with a newline, see http://www.w3.org/Protocols/HTTP/Response.html

@DigitalTrauma, I was going to use that, but then realized the backslash needs to be escaped with another backslash, so it would have been the same number of characters anyway :)

@TreyThomas Oh I see - so Ruby needs an extra level of escape here

Node.js, 72
require('http').createServer((q,s)=>s.writeHead(418)+s.end()).listen(80)

Response:
HTTP/1.1 418 I'm a Teapot
Date: Thu, 01 Apr 2021 16:12:59 GMT
Connection: keep-alive
Transfer-Encoding: chunked

0

Node.js, 80 with ES5 syntax only
require('http').createServer(function(q,s){s.writeHead(418);s.end()}).listen(80)

The response is
HTTP/1.1 418 I'm a teapot
Date: Wed, 19 Nov 2014 21:08:27 GMT
Connection: keep-alive
Transfer-Encoding: chunked

0

I find it just awesome that node supports that error code natively ^^

You can use arrow functions to lower your byte count.

@ophact, yep, updated.

@Qwertiy wow didn't expect a response so quickly on a 6-year old answer

ServerResponse#writeHead() returns itself, so it can be chained with ServerResponse#end(): s.writeHead(418).end(). -2 to both codes!

Python 3 106
s=__import__('socket').socket(2,1)
s.bind(('',80))
s.listen(9)
while 1:s.accept()[0].send('HTTP/1.1 418\n')

Based on hallvabo's comment in Tips for golfing in Python, from socket import*;s=socket(AF_INET,SOCK_STREAM) is shorter.

@manatwork Thanks, is there a shorter way to infinite loop? I didn't find one in the tips...

while 1:s.accept()[0].sendall(bytes('HTTP/1.1 418\n','UTF8')) – unless I missed something. (By the way, feel free to count newlines a single characters, as the language allows them. That way you loose nothing by separating the commands by newlines instead of ;.)

You can cut off 2 characters by assuming port 80 is accessible, according to the question owner's comment. One ugly thing which may break portability, but may be acceptable here: use the constants' values directly s=socket(2,1) (at least those are their values on my Linux).

The documentation says for listen()'s parameter that “the maximum value is system-dependent (usually 5)”. So instead of 10, 9 is more that enough and 1 character shorter. And instead of bytes('HTTP/1.1 418\n','UTF8') a literal b'HTTP/1.1 418\n' is enough. Or if you make the code Python 2, then the b bytesprefix is not needed anymore. And the shorter send() also seems to be enough.

106: s=__import__('socket').socket(2,1);s.bind(('',80));s.listen(9) while 1:s.accept()[0].send('HTTP/1.1 418\n')

import socket;s=socket.socket(2,1) and s=__import__('socket').socket(2,1) both have 34 bytes

Haskell - 142 bytes
import Network
import System.IO
main=listenOn(PortNumber 8888)>>=f
f s=do{(h,_,_)<-accept s;hPutStr h"HTTP/1.1 418\r\n";hFlush h;hClose h;f s}

R, 80 characters
Never did socket programming with R before, but I'll give it a try:
repeat{s=socketConnection(,80,T,open="r+");cat("HTTP/1.1 418\n",file=s);close(s)}

Here socketConnection opens a socket: first argument should be the host, the default being localhost we can skip it here; the second argument is the port which has no default, then argument server when specified TRUE creates the socket, if FALSE it just connects to an existing one. T is, by default, equals to TRUE, in R.
Edit: As suggested in a suggested edit by @AlexBrown, this could be shorten into 69 characters:
repeat cat("HTTP/1.1 418\n",file=s<-socketConnection(,80,T))+close(s)

According to the HTTP specifications, HTTP responses must end in \r\n, so you have to add two bytes.

Tcl (>= 8.5), 78 bytes
Edit - added in an extra newline (total of 2 newlines) for the sake of compliance.
socket -server {apply {{c - -} {puts $c "HTTP/1.1 418
";close $c}}} 80
vwait f

A response must end with a newline, see w3.org/Protocols/HTTP/Response.html

@Nit - Yes, Tcl puts will automatically append a newline, unless the -nonewline option is given. https://www.tcl.tk/man/tcl/TclCmd/puts.htm

Powershell, 398
$Listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse("10.10.10.10"), 80)
$Listener.Start()
while($true)
{
    $RemoteClient = $Listener.AcceptTcpClient()
    $Stream = $RemoteClient.GetStream()
    $Writer = New-Object System.IO.StreamWriter $Stream
    $Writer.Write("HTTP/1.1 418 I'm a Teapot`nConnection: Close`n`n")
    $Writer.Flush()
    $RemoteClient.Close()
}

258
$l=New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse("10.10.10.10"),80);$l.Start();while($true){$r = $l.AcceptTcpClient();$s = $r.GetStream();$w = New-Object System.IO.StreamWriter $s;$w.Write("HTTP/1.1 418`n`n");$w.Flush();$r.Close()}

Shell + socat, 60
socat tcp-l:80,fork exec:'printf HTTP/1.1\\ 418\\ T\r\n\r\n'

echo -e HTTP/1.1 418 T\r\n\r is shorter.

The \\ T isn't even needed.

Julia 0.6, 86 73 bytes
s=listen(80)
while 1<2
c=accept(s)
write(c,"HTTP/1.1 418

")
close(c)
end

I don't think you need the actual "I'm a teapot" part -- the response code should be enough.

Yes, I noticed it. But as that won't help much on Julia's score I kept it complete. But probably would be better to remove it to facilitate comparison of languages.

According to the HTTP specifications, HTTP responses must end in \r\n, so this is invalid. You can fix it at no cost, however, by replacing the first LF with a CR.

Node.js koa, 61 Bytes
require('koa')().use(function*(){this.status=418}).listen(80)

Response:
HTTP/1.1 418 I'm a teapot
X-Powered-By: koa
Content-Type: text/plain; charset=utf-8
Content-Length: 12
Date: Thu, 20 Nov 2014 07:20:36 GMT
Connection: close

I'm a teapot

Requires node v0.11.12 +
Run as:
node --harmony app.js

What's function*?

That's a generator function, part of the ECMAScript 6, Harmony proposal.

MATLAB, 97 86 bytes
Not really a serious contender in terms of absolute byte-count, but I'd like to post it because I didn't think it would be possible to write a fully functional webserver using a mathematical tool. Note the use of property shortening: 'Ne','s' internally expands to 'NetworkRole', 'server'.
t=tcpip('0.0.0.0','Ne','s');while 1
fopen(t)
fprintf(t,'HTTP/1.1 418\n')
fclose(t)
end

According to the HTTP specifications, HTTP responses must end in \r\n, so you have to add two bytes.

@Makonede Instead of commenting on every single answer here you could've left a single comment on the OP if the \r\n is required. Either way, I strongly feel this is not worth digging up a seven year old challenge for...

Perl, 78
use Web::Simple;sub dispatch_request{sub{[418,[],[]]}}__PACKAGE__->to_psgi_app

run as plackup whatever.pl.

If you want a plack application, then just sub{[418,[],[]]} should be sufficient. (16 characters.)

Of course you're right! It's not like I'm using any of the framework, why load it? :)

@tobyink feel free to submit it as your own though :)

Go, 162 bytes
package main
import "net/http"
func main(){http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request){w.WriteHeader(418)})
http.ListenAndServe(":80", nil)
}

Python 2.7/Django, 94 bytes
(added from default boilerplate from django-admin.py startproject)
In urls.py:
import django.http.HttpResponse as r;urlpatterns=patterns(url(r'^*$',lambda q:r(status=418)))

node.js with CoffeeScript (76)
require("connect")().use((q,s,n)->s.writeHead 418;s.end();return;).listen 80

Just compile it to JavaScript, then you need to run npm install connect. After that start it with node server.js

Factor, 101 141 bytes
[ utf8 <threaded-server> readln 10 base> >>insecure [ "HTTP/1.1 418\r" print flush ] >>handler [ start-server ] in-thread start-server drop ]

Return 418 to everyone who connects.

C# + OWIN 251 240
I was really hoping it'd be shorter, but the long namespaces ruined that plan. Requires the Microsoft.Owin.SelfHost package available on NuGet.
using Owin;class P{static void Main(){Microsoft.Owin.Hosting.WebApp.Start
("http://localhost");while(0<1);}public void Configuration(IAppBuilder a){a.Run(c=>{c.Response.StatusCode=418;return System.Threading.Tasks.Task.FromResult(0);});}}

node.js with connect (78)
require('connect')().use(function(q,s,n){s.writeHead(418);s.end()}).listen(80)

You need to run npm install connect first. Then start it with node server.js

You can do this with minimal effort using a .htaccess file and php.
All the accesses to your server will return the status 418.
Below is the code:
.htaccess (28 bytes)
RewriteRule .* index.php [L]

PHP (38 19 bytes)
<<?header(TE,1,418);

Thanks to @primo for saving me a bunch of bytes!

I have tested this and confirm it returns the desired result!

By the way, "Pedido" means "Request" and "Resposta" means "Answer".

-1, this is not a complete program. It relies on an external web server.

@nyuszika7h Actually, it relies on Apache with PHP installed as a module. Your argument is both valid and invalid. Apache only redirects the accesses to the PHP file, the PHP file takes care of the code.

@nyuszika7h If we go down on that layer, then you can't even use the console to run your PHP code. Apache is the starter. The trigger that fires the bullet. Running the PHP file from the console, would make the console the trigger.

You're relying on having Apache already running, and I don't think it will work without changing the default configuration either. I don't care what you say, there's no way I can see this as being valid. But you should ask @Nit, as it's their question.

@nyuszika7h If it was invalid, the OP would have said already.

.htaccess is not even code, it's just a limited configuration file. If this is valid (which apparently it is, judging by the fact that the OP hasn't said anything) then I'll eat my hat. Seriously though.

@nyuszika7h Which seasoning you will wish sir? And according to your comment, then my char count should be reduced to 38 bytes, since that is the only programming part with real code.

That alone isn't valid, someone else already tried that.

@nyuszika7h Any evidence to support your statement?

Revision history of said post. But if that isn't enough, I'm sure @Nit will be glad to confirm that the original version of that was invalid.

@nyuszika7h That's just an edit log. Nothing important to see there.

The comments were deleted because they're obsolete. That's just how Stack Exchange works. Like I said, I'm sure the OP (or the person who wrote that answer) will be glad to confirm.

@nyuszika7h Let me tell you a story. A few days ago, I answered a question on stackoverflow (the rules are almost the same, you will see). And one user decided to "bash" me and the OP, both for our low reputation and me for answering it and the OP for asking it. And then, all the comments where deleted. I posted on meta (I can provide a link)  asking what I could do in case of such a situation. Their answer was that without comments, there is nothing that can be done. Here is the same case: if you want me to delete this answer, prove me it is invalid. Deleted comments aren't enough evidence.

Let us continue this discussion in chat.

Old question, but I just noticed that <?header(TE,1,418); will also return status 418 (6 bytes shorter than <?header("HTTP/1.1 418");).

Java 7, 208 bytes
import java.net.*;class R{public static void main(String[]a)throws Exception{for(ServerSocket s=new ServerSocket(80);;){Socket p=s.accept();p.getOutputStream().write("HTTP/1.0 418\n".getBytes());p.close();}}}

This question needed a java answer.
poke@server ~
$ curl -i localhost:80
HTTP/1.0 418

Where is status message?

@Qwertiy I think this question only asks for status code which I interpret as the integer, so it follows that the status message/reason is not strictly required.

Not me to deside, but I think it should be with status text.

Get Java 8 already >_>

Here it is as a lambda for 148 bytes

According to the HTTP specifications, HTTP responses must end in \r\n, so you have to add two bytes.

05AB1E + ncat, 75 74 69 62 44 42 bytes
-12 thanks to ovs.
'‚«™’ÿ.¬•"n—Ä -k¯à80<<<'HTTP/1.1 418
'"’.E

Your ISP must be AT&T for this to work, as it abuses AT&T's automatic conversion of \n to \r\n in HTTP requests.
'‚«™’...’.E  # trimmed program
         .E  # evaluate...
    ’...’    # "ÿ.shell\"ncat -klp80<<<'HTTP/1.1 418\n'\""...
             # (implicit) with ÿ replaced by...
'‚«          # "system"...
   ™         # in title case...
         .E  # as Elixir code

====================

System.shell"..."  # trimmed program
System.shell       # execute shell command...
            "..."  # literal

====================

ncat -klp80<<<'...'  # trimmed program
ncat                 # host web server...
     - l             # that listens to requests...
     -k              # forever...
     -  p            # on port...
         80          # literal...
ncat                 # that returns response input...
           <<<       # with...
              '...'  # literal...
           <<<       # as input

Side note: I do not know Elixir at all so if there are ways to improve the Elixir code please let me know.
05AB1E (legacy) + ncat, 64 54 52 bytes
’__£Ø__('ï´').‚«("n—Ä -k¯à80<<<'HTTP/1.1 418\n'")’.E

’...’.E  # trimmed program
     .E  # evaluate...
’...’    # "__import__('os').system(\"ncat -klp80<<<'HTTP/1.1 418\n'\")"...
     .E  # as Python code

====================

__import__('os').system("...")  # trimmed program
__import__('os').system(     )  # execute shell command...
                        "..."   # literal

====================

ncat -klp80<<<'...'  # trimmed program
ncat                 # host web server...
     - l             # that listens to requests...
     -k              # forever...
     -  p            # on port...
         80          # literal...
ncat                 # that returns response input...
           <<<       # with...
              '...'  # literal...
           <<<       # as input

That's pretty cool, I didn't know 05AB1E also supported running as Elixir code, TIL.

@Etheryte Yeah, 05AB1E is actually written in Elixir, that's why this was added.

In the new version .E can evaluate single Elixir expressions, you don't need to write a full program. Did you test the current version? For me I couldn't get it to work, but this should work with the newest Elixir version.

@ovs Thanks for the tip about System.shell! About the comment: I am aware of that, however the nc needs to run infinitely, thus I made a recursive function. (Doesn't seem to be a better way of making an infinite loop in Elixir)

I found a way to do it without defining a module: Try it online! (Taken from this SO answer)

nginx - 35
events{}http{server{return 418;}}

Throw that in nginx.conf, start nginx.
Not sure if this uses standard loopholes "Using built-in functions to do the work" or "Interpreting the challenge too literally." Oops, looks like OP won't like this answer.

Would it still work if you dropped the ;?

+4/-4: well done on controversy :D

Python 3 + Flask, 64 80 76 75 bytes
from flask import*
a=Flask("");a.route("/")(lambda:abort(418));a.run("",80)

I don't know much Flask, so I'm not entirely sure if this works. Please let me know in the comments if there's some problem with this. Ungolfed version:
from flask import Flask, abort

app = Flask(__name__)

@app.route("/")
def index():
    abort(418)

app.run("127.0.0.1", 80)

Simply binds the path "/" to a function that aborts with error code 418.
Thanks to Makonede for pointing out that I didn't start the server and giving a modification to make the solution 80 76 75 bytes. The 80 was from using app instead of a. Oops! The 76 was from (a:=Flask("")) instead of a=Flask("");a.

You never started the server. Working 80 byte solution: from flask import*;(app:=Flask('')).route('/')(lambda:abort(418));app.run('',80)

wait i'm dumb why use app when you can use a lol. Saves 4 bytes

@Makonede Oops! I didn't catch that either, hehe.

Also -1 without :=: a=Flask('');a.route('/')(lambda:abort(418));a.run('',80)

@Makonede Oops. Right again, Makonede!

Python 3 + ncat, 55 53 bytes
import os;os.system("ncat -klp80<<<'HTTP/1.1 418\n'")

Your ISP must be AT&T for this to work.
import os;os.system("...")  # trimmed program
import                      # import module named...
       os                   # variable
          os.system(     )  # run shell command...
                    "..."   # literal

====================

ncat -klp80<<<'...'  # trimmed program
ncat                 # host web server...
     - l             # that listens to requests...
     -k              # forever...
     -  p            # on port...
         80          # literal...
ncat                 # that returns response input...
           <<<       # with...
              '...'  # literal...
           <<<       # as input

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


text:
Compute the specificity of a CSS selector
Today, your task is to write a program (or a function) that accepts a string and outputs (or returns) four integers.

Input
The input string is a CSS3 selector, and can contain basically any Unicode character.

Output
The output represents the CSS specificity of this selector.

The first number is always 0 (because it's used for inline styles, and this exercise doesn't apply to inline styles)
The second number is the number of ids (#foo) present in the selector.
The third number is the number of classes (.foo), attributes ([bar]) and pseudo-classes present in the selector.
The fourth number is the number of elements (biz)  and pseudo-elements present in the selector.

Notes:

Universal selector (*) isn't counted anywhere
The pseudo-elements ::before and ::after can also be written with a single ":" (legacy notation)
Input can use the :not(selector) pseudo-class. The selector inside doesn't count, even if it contains ids, classes, elements, ...)
The "bricks" of the selector are separated by combinators (spaces/tabs, +, >, ~, ex: body > div+a ~*), but they can also be cumulated (ex: div#foo.bar[baz]:hover::before)
You also have to handle CSS escape sequences ( \ followed by 1 to 6 hexadecimal numbers, followed by a space), and escaped special characters (\ followed by any of these: !"#$%&'()*+,-./:;<=>?@[\]^`{|}~) properly. Those escapes can be part of any brick of the selector (id, class, etc).
You don't need to do anything particular if you receive an invalid selector or a CSS4 selector. Don't bother implementing a CSS3 selector validator.
Here are a few links to learn more about CSS specificiy:

CSS-tricks article: http://css-tricks.com/specifics-on-css-specificity/
A tool (incomplete) that counts it: http://specificity.keegan.st/

Examples

// Universal

*                       => 0,0,0,0

// ID

#id                     => 0,1,0,0

// Class

.class                  => 0,0,1,0

// Attributes

[foo]                   => 0,0,1,0
[foo="bar"]             => 0,0,1,0
[foo~="bar"]            => 0,0,1,0
[foo^="bar"]            => 0,0,1,0
[foo$="bar"]            => 0,0,1,0
[foo*="bar"]            => 0,0,1,0
[foo|="bar"]            => 0,0,1,0
[ foo  =  bar ]         => 0,0,1,0
[foo  =  'bar']         => 0,0,1,0

(NB: brackets [] can contain anything except an unescaped "]")

// Pseudo-classes

:root                   => 0,0,1,0
:nth-child(n)           => 0,0,1,0
:nth-last-child(n)      => 0,0,1,0
:nth-of-type(n)         => 0,0,1,0
:nth-last-of-type(n)    => 0,0,1,0
:first-child            => 0,0,1,0
:last-child             => 0,0,1,0
:first-of-type          => 0,0,1,0
:last-of-type           => 0,0,1,0
:only-child             => 0,0,1,0
:only-of-type           => 0,0,1,0
:empty                  => 0,0,1,0
:link                   => 0,0,1,0
:visited                => 0,0,1,0
:active                 => 0,0,1,0
:hover                  => 0,0,1,0
:focus                  => 0,0,1,0
:target                 => 0,0,1,0
:lang(fr)               => 0,0,1,0
:enabled                => 0,0,1,0
:disabled               => 0,0,1,0
:checked                => 0,0,1,0
:not(selector)          => 0,0,1,0

(NB: the keyword after ":" can be anything except a pseudo-element)

// Elements

body                    => 0,0,0,1

// Pseudo-elements

:before                 => 0,0,0,1
:after                  => 0,0,0,1
::before                => 0,0,0,1
::after                 => 0,0,0,1
::first-line            => 0,0,0,1
::first-letter          => 0,0,0,1

(NB: parenthesis () can contain anything except an unescaped ")" )

(to be continued)

If you have questions or need examples or test data, please ask in the comments.
Shortest code (in bytes) wins.
Good luck!

Please add examples (ideally covering all the quirks in the notes).

The list of tests looks really good, but some examples that go beyond a single 1 would be great. (Btw, I think this is actually a pretty good challenge, but an exhaustive list of test cases seems vital to make it work well.)

JavaScript ES6 453 430 bytes
a=>(s){var n=z=[],c=[0,0,0,0],e=s.split(/[\s\+\>\~]+/);return e.forEach((s)=>{n=n.concat(s.replace(/\((.*)\)/,"").split(/(?=\[|::|\.)/))}),n.forEach((s)=>{if(0==s.indexOf("::"))return z.push(s);var n=s.split(/(?=:)/);z=z.concat(n[0].split(/(?=[\#])/)),/before|after/.test(n[1])?z.push(":"+n[1]):n[1]&&z.push(n[1])}),z.forEach((s)=>{/^[a-z]+$/gi.test(s)||"::"==s[0]+s[1]?c[3]++:-1!=":.[".indexOf(s[0])?c[2]++:"#"==s[0]&&c[1]++}),c}

Update: improved code, now it handles :not and :before/:after selectors better, nevertheless haven't tested CSS escape sequences.

Python3, 226 bytes:
lambda s:[0,(c:=(x:=sub('(?<=\:not)\(.*?\)|\\.*?\\\\|(?<=\[).*?(?=\])','',s)).count)('#'),c('.')+c('[')+sub('::|(?:\:after)|(?:\:before)','',x).count(':'),len(findall('^\w+|[\s\>\+,]\w+|::|\:after|:before',x))]
from re import*

The test cases included in the link below are derived from the sample selectors in the original question along with the most complex selectors from Code Golf's own source.
Try it online!

source: Stack Exchange

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

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

sort: votes


text:
Find the largest fragile prime
Consider the function Remove(n, startIndex, count) that removes count digits from the number n starting from the digit at position startIndex. Examples:
Remove(1234, 1, 1) = 234
Remove(123456, 2, 3) = 156
Remove(1507, 1, 2) = 07 = 7
Remove(1234, 1, 4) = 0

We will call the prime number X fragile if every possible Remove operation makes it non-prime. For example, 80651 is a fragile prime because all of the following numbers are not prime:
651, 51, 1, 0, 8651, 851, 81, 8, 8051, 801, 80, 8061, 806, 8065

Goal
Write a program that finds the largest fragile prime. Edit: removed the time limit because there was a relatively fair way to circumvent it.
The score is the fragile prime number found by your program. In the event of a tie, the earlier submission wins.
Rules

You may use any language and any third-party libraries.
You run the program on you own hardware.
You may use probabilistic primality tests.
Everything is in base 10.

Leading entries

6629 digits by Qualtagh (Java)
5048 digits by Emil (Python 2)
2268 digits by Jakube (Python 2)

Edit: I've added my own answer.

28164 digits by Suboptimus Prime, based on Qualtagh's algorithm (C#)

Even if I don't hard code the answer, I could start searching at a point very close to a large fragile prime. Obviously, nobody wants to start searching at 1. What's stopping me from doing this? Exactly how close can I start my search before I get called out for basically hard-coding the answer? I love the challenge by the way.

@Rainbolt You may start searching from any number you want, but you are not allowed to use numbers found by running your program for more than 15 minutes. Obviously, I can't enforce this rule, but hopefully everyone will play fair.

@SuboptimusPrime You could instead remove the time limit altogether, because I believe at some point that will be so rare that it'll be a feat to find the next one anyway. (Similar to http://codegolf.stackexchange.com/questions/41021/find-highest-scoring-matrix-without-property-x)

Related

@SuboptimusPrime Fair enough. I'm kind of leaning towards hoping everyone plays fair now, because as some folks pointed out in the chat, its been done at least twice before, and it worked. Leave it to the downvoters to beat up anyone who tries to cheat.

@MartinBüttner Not everyone can keep their PC's running for hours or days, so they will be at a disadvantage if I remove the time limit. I want to make this challenge more accessible for everyone.

You're still leaving at a disadvantage those who have slower computers

@JanDvorak True, but I don't think I can do anything about it. That's a universal problem for all optimization challenges I guess.

@SuboptimusPrime Well, you could test all submissions yourself (that's what people do for fastest-code challenges).

@MartinBüttner I've based my rules on this question. If I'll test all submissions myself than other people would have to optimize their programs for my hardware, which doesn't look like a good idea to me. And I'm still unsure about that time limit rule. I'll remove it if there will be enough demand for it.

I finally realized that the time limit was pointless. You could run the program repeatedly on the consecutive intervals of numbers, 15 minutes at a time. That would effectively remove the time limit without cheating, because the rules allow you to start searching from any number you want.

It took me an embarrassingly long time to realize that "Write a program that finds the largest fragile prime" did not mean "There exists a largest fragile prime. Write a program that finds it." I guess I've done too much Project Euler. :-P

"You may use probabilistic primality tests." So if I have a number p, and 2**(p-1) % p = 1, I can claim p is prime?

@feersum You may use any algorithm you want but it has to produce the correct result, so it's probably better to use something more reliable than 2**(p-1) % p = 1.

I don't get it. If the result has to be correct, how is it then OK if it may be incorrect?

@feersum I'm veryfing all the answers with a probabilistic test that has a very low possibility of error. You answer has to pass this test to be accepted.

So the result need not be correct, if someone can guess which algorithm you are using ;)

@feersum I'm using 40 random miller-rabin tests as a primality test. I don't think it's possible to adjust any algorithm to pass 40 random tests :)

Java - 3144 3322 6629 digits
6 0{3314} 8969999
6 0{6623} 49099

This solution is based on FryAmTheEggman's answer.

The last digit is 1 or 9.
If the last digit is 1 then a previous one is 0, 8 or 9.
If the last digit is 9 then a previous one is 0, 4, 6 or 9.
...

What if we dig deeper?
It becomes a tree structure:
                        S
             -----------------------
             1                     9
    ------------------         ----------------
    0           8    9         0    4    6    9
---------     -----
0   8   9      ...

Let's call number R right composite if R and all its endings are composite.
We're gonna iterate over all right composite numbers in breadth-first manner:
1, 9, 01, 81, 91, 09, 49, 69, 99, 001, 801, 901 etc.
Numbers starting with zero are not checked for primality but are needed to build further numbers.
We will look for a target number N in the form X00...00R, where X is one of 4, 6, 8 or 9 and R is right composite. X cannot be prime. X cannot be 0. And X cannot be 1 because if R ends with 1 or 9 then N would contain 11 or 19.
If XR contains prime numbers after "remove" operation then XYR would contain them too for any Y. So we shouldn't traverse branches starting from R.
Let X be a constant, say 6.
Pseudocode:
X = 6;
for ( String R : breadth-first-traverse-of-all-right-composites ) {
  if ( R ends with 1 or 9 ) {
    if ( remove( X + R, i, j ) is composite for all i and j ) {
      for ( String zeros = ""; zeros.length() < LIMIT; zeros += "0" ) {
        if ( X + zeros + R is prime ) {
          // At this step these conditions hold:
          // 1. X + 0...0 is composite.
          // 2. 0...0 + R = R is composite.
          // 3. X + 0...0 + R is composite if 0...0 is shorter than zeros.
          suits = true;
          for ( E : all R endings )
            if ( X + zeros + E is prime )
              suits = false;
          if ( suits )
            print R + " is fragile prime";
          break; // try another R
                 // because ( X + zeros + 0...0 + R )
                 // would contain prime ( X + zeros + R ).
        }
      }
    }
  }
}

We should limit zeros quantity because it may take too long to find a prime number in form X + zeros + R (or forever if all of them are composite).
The real code is quite verbose and can be found here.
Primality testing for numbers in long int range is performed by deterministic variant of Miller test. For BigInteger numbers a trial division is performed first and then BailliePSW test. It's probabilistic but quite certain. And it's faster than Miller-Rabin test (we should do many iterations for such big numbers in Miller-Rabin to gain enough accuracy).
Edit: the first attempt was incorrect. We should also ignore branches starting with R if X0...0R is prime. Then X0...0YR wouldn't be fragile prime. So an additional check was added. This solution seems to be correct.
Edit 2: added an optimization. If ( X + R ) is divisible by 3 then ( X + zeros + R ) is also divisible by 3. So ( X + zeros + R ) cannot be prime in this case and such R's may be skipped.
Edit 3: it was not necessary to skip prime digits if they're not in the last or first position. So endings like 21 or 51 are ok. But it doesn't change anything much.
Conclusions:

My last answer was checking for being fragile for 100 minutes. The search of the answer (checking all preceding variants) took about 15 minutes. Yes, it makes no sense to restrict search time (we can start searching from the target number, so time would be zero). But it could be meaningful to restrict checking time like in this question.
The answer 60...049099 has digit 4 in the middle. If the "remove" operation touches it, the number becomes divisible by 3. So we should check remove operations in left and right sides. Right side is too short. Left side length is almost n = length( N ).
Primality tests like BPSW and Miller-Rabin use constant quantity of modular exponentiations. Its complexity is O( M( n ) * n ) according to this page, where M( n ) is multiplication complexity. Java uses Toom-Cook and Karatsuba algorithms but we'll take scholar algorithm for simplicity. M( n ) = n2. So primality testing complexity is O( n3 ).
We should check all numbers from length = 6 to 6629. Let's take min = 1 and max = n for commonality. The whole check complexity is O( 13 + 23 + ... + n3 ) = O( ( n * ( n + 1 ) / 2 )2 ) = O( n4 ).
Emil's answer has the same checking asymptotics. But the constant factor is lower. Digit "7" is standing in the middle of the number. Left side and right side can be almost equal. It gives ( n / 2 )4 * 2 = n4 / 8. Speedup: 8X. Numbers in the form 9...9Y9...9 can be 1.7 times longer than in the form X0...0R having the same checking time.

Thanks for the credit, but your algorithm is vastly more complex than mine! Great work, and welcome to PPCG! :)

@FryAmTheEggman: thank you for the idea! It's inspiring.

Your analysis of check complexity is very interesting, but search compexity is probably important too. I think that your algorithm requires significantly less primality tests of large numbers (compared to Emil's) to find a large fragile prime. And you can speed up primality tests by using a native library. I'm using Mpir.NET, and checking your number for being a fragile prime takes just a few minutes.

Python 2 - 126 1221 1337 1719  2268 digits
999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999799999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999

'9' * 1944 + '7' + '9' * 323

There are at about len(n)^2 resulting numbers of Remove(n, startIndex, count). I tried to minimize those numbers. If there are lots of digits next to each other are the same, lots of these resulting numbers can be ignored, because they appear multiple times.
So I took it to the extreme, only 9s and a little prime in the middle. I also took a look at the fragile prime under 1 million, and saw, that there are such fragile prime. Searching for numbers with 2 9s at the end works really good, not sure why. 1 number, 3, or 4 9s at the end results in smaller fragile primes.
It uses the pyprimes module. I'm not sure, if it is any good. It uses the miller_rabin test, so it's probabilistic.
The program find this 126-digit fragile prime in about 1 minute, and for the rest of the time it searches without success.
biggest_found = 80651

n = lambda a,b,c: '9'*a + b + '9'*c

for j in range(1000):
   for digit in '124578':
      for i in range(2000):
         number = int(n(i,digit,j))
         if is_prime(number):
            if (number > biggest_found):
               if all(not is_prime(int(n(i,digit,k))) for k in range(j)):
                  biggest_found = number
                  print(i+j+1, biggest_found)
            break

edit:
Just saw, that you removed the time limit. I will run the program over night, maybe some really big fragile primes appear.
edit 2:
Made my original program faster, so but still no solution with more than 126 digits. So I jumped on the train and searched for x 9s + 1 digit + y 9s. The advantage is, that you have to check O(n) numbers for primality, if you fixe y. It finds a 1221 rather quickly.
edit 3:
For the 2268 digit number I use the same program, only divided the work on multiple cores.

"in about 1 minutes" - sorry, have to report a pluralization "bug". :P

The probabilistic nature of the miller-rabin is what was biting me for my last few entries. You might want to verify with another algorithm as well.

Why do you only check that the numbers formed from removing digits from the end are composite? Why not check the numbers formed by removing digits from the front?

Because I checked these before in the 'for i'-loop. Here I append 9s at the beginning, and make a prime check. When I find the first prime number of this form, I know, that all numbers with less 9s at the beginning are not prime. And after checking for removing 9s at the end, I stop (break), because now, every number has a prime number in it and is therefore not prime.

Ah, very clever.

Python 2.7 - 429623069 99993799
No optimizations whatsoever, so far. Just using some trivial observations about fragile primes (thanks to Rainbolt in chat):

Fragile primes must end in 1 or 9 (Primes are not even, and the final digit must not be prime)
Fragile primes ending in 1 must start with 8 or 9 (the first number can't be prime, and 11, 41 and 61 and are all primes)
Fragile primes ending in 9 must start with 4,6 or 9 (see reasoning for 1, but only 89 is prime)

Just trying to get the ball rolling :)
This technically runs slightly over 15 minutes, but it only checks a single number in the extra time.
is_prime is taken from here (isaacg used it here) and is probabilistic.
def substrings(a):
    l=len(a)
    out=set()
    for i in range(l):
        for j in range(l-i):
            out.add(a[:i]+a[len(a)-j:])
    return out

import time

n=9
while time.clock()<15*60:
    if is_prime(n):
        if not any(map(lambda n: n!='' and is_prime(int(n)), substrings(`n`))):
            print n
    t=`n`
    if n%10==9 and t[0]=='8':n+=2
    elif n%10==1 and t[0]!='8':n+=8
    elif t[0]=='1' or is_prime(int(t[0])):n+=10**~-len(t)
    else:n+=10

Just a note, when I start this with n=429623069 I get up to 482704669. The extra digit really seems to kill this strategy...

Not bad for a start! Although it seems that is_prime performs a full deteterministic check for 32-bit values, which is a little bit excessive. I think is_prime method may work faster if you'll comment out the full trial division part.

@SuboptimusPrime Oh, thanks. I didn't even look at it :P

@SuboptimusPrime I think the full deterministic check is faster for small values because the author defined steps to take in between candidate factors. Thanks again for the idea, but it seems much faster when leaving that in :)

Small correction to your answer: 91 = 13x7, so 91 is composite, and fragile primes ending in 1 can actually start with 9.

@SuboptimusPrime Quite right, dunno how I messed that up. The value I posted should still be valid, as I was just skipping some possible values.

Python 2, 828 digits 5048 digits
[encoded data, 5048 characters]
155*'9'+'7'+4892*'9'

As @Jakube pointed out, the first prime I submitted was not actually fragile due to a bug in my code. Fixing the bug was easy but it also made the algorithm significantly slower.
I limited myself to an easily searchable subset of the fragile primes, namely those that only consist of the digit 9 and exactly one digit 7.
def fragile_prime_generator(x, b_max):
  bs, cs = set(), set()
  prime = dict()

  def test_prime(b,c):
    if (b,c) not in prime:
      prime[(b,c)] = is_prime(int('9'*b+`x`+'9'*c))
    return prime[(b,c)]

  def test_frag(b,c):
    for b2 in xrange(b):
      if test_prime(b2,c):
        bs.add(b2)
        return False
    for c2 in xrange(c):
      if test_prime(b,c2):
        cs.add(c2)
        return False
    return True

  a = 1
  while len(bs)<b_max:
    for b in xrange(min(a, b_max)):
      c = a-b
      if b not in bs and c not in cs and test_prime(b,c):
        bs.add(b)
        cs.add(c)
        if test_frag(b,c): yield b,c
    a += 1
  print "no more fragile primes of this form"

for b,c in fragile_prime_generator(7, 222):
  print ("%d digit fragile prime found: %d*'9'+'%d'+%d*'9'"
          % (b+c+1, b, x, c))

I used the same is_prime function (from here) as @FryAmTheEggman.
Edit:
I made two changes to make the algorithm faster:

I try to skip as many primality checks as possible and only go back when a potential fragile prime is found to make sure it's really fragile. There's a small number of duplicate checks, so I crudely memoized the prime checking function.
For the numbers of the form b*'9' + '7' + c*'9' I limited the size of b. The lower the limit, the less numbers have to be checked, but chances increase to not find any large fragile prime at all. I kind of arbitrarily chose 222 as the limit.

At a few thousand digits a single prime check already can take my program a few seconds. So, I probably can't do much better with this approach.
Please feel free to check the correctness of my submission. Due to the probabilistic primality check my number could theoretically not be prime, but if it is, it should be fragile. Or I've done something wrong. :-)

Your found prime is not fragile. If you call Remove(n,83,838) [Remove everything except the first 82 digits], you'll end up with a prime.

Ah, thanks @Jakube. I was trying to be too clever. Turns out I was skipping more primality checks then I should have. I'm on my way to fix it.

Checked it again, now your results are correct.

Your 5048 digit number is, indeed, a fragile prime according to my program.

@SuboptimusPrime: Great, thanks for checking!

C#, 10039 28164 digits
6 0{28157} 169669

Edit: I've made another program based on Qualtagh's algorithm with some minor modifications:

I'm searching for the numbers of the form L000...000R, where L is
left composite, R is right composite. I allowed the left composite
number L to have multiple digits, although this is mostly a stylistic
change, and it probably doesn't affect the efficiency of the
algorithm.
I've added multithreading to speed up the search.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using Mpir.NET;

class Program
{
    const int PrimeNotFound = int.MaxValue;

    private static BitArray _primeSieve;
    private static HashSet<Tuple<int, int>> _templatesToSkip = new HashSet<Tuple<int, int>>();

    static void Main(string[] args)
    {
        int bestDigitCount = 0;
        foreach (Tuple<int, int> template in GetTemplates())
        {
            int left = template.Item1;
            int right = template.Item2;
            if (SkipTemplate(left, right))
                continue;

            int zeroCount = GetZeroCountOfPrime(left, right);
            if (zeroCount != PrimeNotFound)
            {
                int digitCount = left.ToString().Length + right.ToString().Length + zeroCount;
                if (digitCount >= bestDigitCount)
                {
                    string primeStr = left + " 0{" + zeroCount + "} " + right;
                    Console.WriteLine("testing " + primeStr);
                    bool isFragile = IsFragile(left, right, zeroCount);
                    Console.WriteLine(primeStr + " is fragile: " + isFragile);

                    if (isFragile)
                        bestDigitCount = digitCount;
                }

                _templatesToSkip.Add(template);
            }
        }
    }

    private static int GetZeroCountOfPrime(int left, int right)
    {
        _zeroCount = 0;

        int threadCount = Environment.ProcessorCount;
        Task<int>[] tasks = new Task<int>[threadCount];
        for (int i = 0; i < threadCount; i++)
            tasks[i] = Task.Run(() => InternalGetZeroCountOfPrime(left, right));
        Task.WaitAll(tasks);

        return tasks.Min(task => task.Result);
    }

    private static int _zeroCount;

    private static int InternalGetZeroCountOfPrime(int left, int right)
    {
        const int maxZeroCount = 40000;
        int zeroCount = Interlocked.Increment(ref _zeroCount);
        while (zeroCount <= maxZeroCount)
        {
            if (zeroCount % 1000 == 0)
                Console.WriteLine("testing " + left + " 0{" + zeroCount + "} " + right);

            if (IsPrime(left, right, zeroCount))
            {
                Interlocked.Add(ref _zeroCount, maxZeroCount);
                return zeroCount;
            }
            else
                zeroCount = Interlocked.Increment(ref _zeroCount);
        }

        return PrimeNotFound;
    }

    private static bool SkipTemplate(int left, int right)
    {
        for (int leftDiv = 1; leftDiv <= left; leftDiv *= 10)
            for (int rightDiv = 1; rightDiv <= right; rightDiv *= 10)
                if (_templatesToSkip.Contains(Tuple.Create(left / leftDiv, right % (rightDiv * 10))))
                    return true;

        return false;
    }

    private static bool IsPrime(int left, int right, int zeroCount)
    {
        return IsPrime(left.ToString() + new string('0', zeroCount) + right.ToString());
    }

    private static bool IsPrime(string left, string right, int zeroCount)
    {
        return IsPrime(left + new string('0', zeroCount) + right);
    }

    private static bool IsPrime(string s)
    {
        using (mpz_t n = new mpz_t(s))
        {
            return n.IsProbablyPrimeRabinMiller(20);
        }
    }

    private static bool IsFragile(int left, int right, int zeroCount)
    {
        string leftStr = left.ToString();
        string rightStr = right.ToString();

        for (int startIndex = 0; startIndex < leftStr.Length - 1; startIndex++)
            for (int count = 1; count < leftStr.Length - startIndex; count++)
                if (IsPrime(leftStr.Remove(startIndex, count), rightStr, zeroCount))
                    return false;

        for (int startIndex = 1; startIndex < rightStr.Length; startIndex++)
            for (int count = 1; count <= rightStr.Length - startIndex; count++)
                if (IsPrime(leftStr, rightStr.Remove(startIndex, count), zeroCount))
                    return false;

        return true;
    }

    private static IEnumerable<Tuple<int, int>> GetTemplates()
    {
        const int maxDigitCount = 8;
        PreparePrimeSieve((int)BigInteger.Pow(10, maxDigitCount));
        for (int digitCount = 2; digitCount <= maxDigitCount; digitCount++)
        {
            for (int leftCount = 1; leftCount < digitCount; leftCount++)
            {
                int rightCount = digitCount - leftCount;
                int maxLeft = (int)BigInteger.Pow(10, leftCount);
                int maxRight = (int)BigInteger.Pow(10, rightCount);

                for (int left = maxLeft / 10; left < maxLeft; left++)
                    for (int right = maxRight / 10; right < maxRight; right++)
                        if (IsValidTemplate(left, right, leftCount, rightCount))
                            yield return Tuple.Create(left, right);
            }

        }
    }

    private static void PreparePrimeSieve(int limit)
    {
        _primeSieve = new BitArray(limit + 1, true);
        _primeSieve[0] = false;
        _primeSieve[1] = false;

        for (int i = 2; i * i <= limit; i++)
            if (_primeSieve[i])
                for (int j = i * i; j <= limit; j += i)
                    _primeSieve[j] = false;
    }

    private static bool IsValidTemplate(int left, int right, int leftCount, int rightCount)
    {
        int rightDigit = right % 10;
        if ((rightDigit != 1) && (rightDigit != 9))
            return false;

        if (left % 10 == 0)
            return false;

        if ((left + right) % 3 == 0)
            return false;

        if (!Coprime(left, right))
            return false;

        int leftDiv = 1;
        for (int i = 0; i <= leftCount; i++)
        {
            int rightDiv = 1;
            for (int j = 0; j <= rightCount; j++)
            {
                int combination = left / leftDiv * rightDiv + right % rightDiv;
                if (_primeSieve[combination])
                    return false;

                rightDiv *= 10;
            }

            leftDiv *= 10;
        }

        return true;
    }

    private static bool Coprime(int a, int b)
    {
        while (b != 0)
        {
            int t = b;
            b = a % b;
            a = t;
        }
        return a == 1;
    }
}

Old answer:
8 0{5436} 4 0{4600} 1

The are a few notable patterns for fragile primes:
600..00X00..009
900..00X00..009
800..00X00..001
999..99X99..999

where X can be 1, 2, 4, 5, 7 or 8.
For such numbers we only have to consider (length - 1) possible Remove operations. The other Remove operations produce either duplicates or obviously composite numbers. I tried to search for all such numbers with up to 800 digits and noticed that 4 patterns come up more frequently than the rest: 8007001, 8004001, 9997999 and 6004009. Since Emil and Jakube are using the 999X999 pattern, I decided to use 8004001 just to add some variety.
I've added the following optimizations to the algorithm:

I start searching from numbers with 7000 digits and then increment
length by 1500 every time a fragile prime is found. If there is no
fragile prime with a given length then I increment it by 1. 7000 and
1500 are just arbitrary numbers that seemed appropriate.
I'm using multithreading to search for the numbers with different length at the same time.
The result of each prime check is stored in a hash table to prevent duplicate checks.
I'm using Miller-Rabin implementation from Mpir.NET, which is very fast (MPIR is a fork of GMP).

using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Mpir.NET;

class Program
{
    const string _template = "8041";

    private static ConcurrentDictionary<Tuple<int, int>, byte> _compositeNumbers = new ConcurrentDictionary<Tuple<int, int>, byte>();
    private static ConcurrentDictionary<int, int> _leftPrimes = new ConcurrentDictionary<int, int>();
    private static ConcurrentDictionary<int, int> _rightPrimes = new ConcurrentDictionary<int, int>();

    static void Main(string[] args)
    {
        int threadCount = Environment.ProcessorCount;
        Task[] tasks = new Task[threadCount];
        for (int i = 0; i < threadCount; i++)
        {
            int index = i;
            tasks[index] = Task.Run(() => SearchFragilePrimes());
        }
        Task.WaitAll(tasks);
    }

    private const int _lengthIncrement = 1500;
    private static int _length = 7000;
    private static object _lengthLock = new object();
    private static object _consoleLock = new object();

    private static void SearchFragilePrimes()
    {
        int length;
        lock (_lengthLock)
        {
            _length++;
            length = _length;
        }

        while (true)
        {
            lock (_consoleLock)
            {
                Console.WriteLine("{0:T}: length = {1}", DateTime.Now, length);
            }

            bool found = false;
            for (int rightCount = 1; rightCount <= length - 2; rightCount++)
            {
                int leftCount = length - rightCount - 1;
                if (IsFragilePrime(leftCount, rightCount))
                {
                    lock (_consoleLock)
                    {
                        Console.WriteLine("{0:T}: {1} {2}{{{3}}} {4} {2}{{{5}}} {6}",
                            DateTime.Now, _template[0], _template[1], leftCount - 1,
                            _template[2], rightCount - 1, _template[3]);
                    }
                    found = true;
                    break;
                }
            }

            lock (_lengthLock)
            {
                if (found && (_length < length + _lengthIncrement / 2))
                    _length += _lengthIncrement;
                else
                    _length++;
                length = _length;
            }
        }
    }

    private static bool IsFragilePrime(int leftCount, int rightCount)
    {
        int count;
        if (_leftPrimes.TryGetValue(leftCount, out count))
            if (count < rightCount)
                return false;

        if (_rightPrimes.TryGetValue(rightCount, out count))
            if (count < leftCount)
                return false;

        if (!IsPrime(leftCount, rightCount))
            return false;

        for (int i = 0; i < leftCount; i++)
            if (IsPrime(i, rightCount))
                return false;

        for (int i = 0; i < rightCount; i++)
            if (IsPrime(leftCount, i))
                return false;

        return true;
    }

    private static bool IsPrime(int leftCount, int rightCount)
    {
        Tuple<int, int> tuple = Tuple.Create(leftCount, rightCount);
        if (_compositeNumbers.ContainsKey(tuple))
            return false;

        using (mpz_t n = new mpz_t(BuildStr(leftCount, rightCount)))
        {
            bool result = n.IsProbablyPrimeRabinMiller(20);

            if (result)
            {
                _leftPrimes.TryAdd(leftCount, rightCount);
                _rightPrimes.TryAdd(rightCount, leftCount);
            }
            else
                _compositeNumbers.TryAdd(tuple, 0);

            return result;
        }
    }

    private static string BuildStr(int leftCount, int rightCount)
    {
        char[] chars = new char[leftCount + rightCount + 1];
        for (int i = 0; i < chars.Length; i++)
            chars[i] = _template[1];
        chars[0] = _template[0];
        chars[leftCount + rightCount] = _template[3];
        chars[leftCount] = _template[2];
        return new string(chars);
    }
}

While I was trying to verify your first answer, you have already posted a new one)). Checking already took 24 hours. The answer seems to be correct. I can't believe that Java's BigInteger is so much slower than native implementations. I thought about 2, 3 or even 10 times slower. But 24 hours against several minutes is too much.

@Qualtagh To be fair, the 10039 digit number took 35 hours to find due to the inferior algorithm:) My current program takes about 3 minutes to find your 6629 digit number, and 6 hours to find the 28164 digit one.

Your first answer is correct. Verified! Verification took 48 hours. And I won't even try to verify the second answer)). I'm wondering why is BigInteger so slow comparing to MPIR. Is it only JVM/native difference? I set a "-server" flag, so expect the code to be JIT-compiled. Algorithms of modular exponentiation differ: both Java and MPIR use 2k-ary sliding window, but k=3 is fixed in Java and MPIR chooses k according to the size of the exponent. Is MPIR using parallel computations on several cores or probably GPU capabilities? Java's BigInteger doesn't.

@Qualtagh I'm pretty sure MPIR is only using one CPU core. I've added multithreading myself which resulted in nearly 4 times faster search on a quad-core CPU. I didn't compare the internal implementation of MPIR and Java BigInteger, but I guess that MPIR is using better algorithms for multiplication and modular division. Also, it's probably better optimized for 64-bit CPUs (see the benchmark in this blog post).

Wow, that's an interesting point. I didn't think about x64. One more idea: Java's BigInteger is immutable though it uses MutableBigInteger for some operations inside. Probably immutability leads to performance loss. But it shouldn't matter that much. Yes, MPIR has FFT and other fast multiplication algorithms that Java lacks of. Though I don't know if they are used in modular exponentiation.

MPIR is indeed single core and it doesn't use GPU. It's a highly optimized and fine tuned mix of C and assembler code. There's an MPIR version that uses only C (for portability reasons), but the C+ASM version is notably faster. The MPIR version I'm using for MPIR.Net is C+ASM using the K8 (1st gen x64) instruction set, because I wanted MPIR.Net to run on all x64 PCs. The versions for later instruction sets weren't noticeably faster in my crypto benchmark, but that may of course differ for other operations.

Haskell - 1220 1277 digits fixed for really reals
99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997999999999999999999999999999999999999999999999999999999999999999999999

9{1150} 7 9{69}

Better one  - 1277 digits
9{871} 8 9{405}

Haskell code
downADigit :: Integer -> [Integer]
downADigit n = f [] 1 where
     f xs a | nma /= n = f (((n `div` a10)*a + nma):xs) a10
            | otherwise = xs where
        a10 = a * 10
        nma = n `mod` a

isFragile = all (not . isPrime') . downADigit
findNextPrime :: Integer -> Integer
findNextPrime n | even n = f (n + 1)
                | otherwise = f n where
    f n | isPrime' n  = n
        | otherwise = f (n + 2)

primesFrom n = f (findNextPrime n) where
    f n = n:f (findNextPrime $ n + 1)

primeLimit = 10000

isPrime' n | n < primeLimit = isPrime n
isPrime' n = all (millerRabinPrimality n) [2,3,5,7,11,13,17,19,984,7283,6628,8398,2983,9849,2739]

-- (eq. to) find2km (2^k * n) = (k,n)
find2km :: Integer -> (Integer,Integer)
find2km n = f 0 n
    where
        f k m
            | r == 1 = (k,m)
            | otherwise = f (k+1) q
            where (q,r) = quotRem m 2

-- n is the number to test; a is the (presumably randomly chosen) witness
millerRabinPrimality :: Integer -> Integer -> Bool
millerRabinPrimality n a
    | a <= 1 || a >= n-1 =
        error $ "millerRabinPrimality: a out of range ("
              ++ show a ++ " for "++ show n ++ ")"
    | n < 2 = False
    | even n = False
    | b0 == 1 || b0 == n' = True
    | otherwise = iter (tail b)
    where
        n' = n-1
        (k,m) = find2km n'
        b0 = powMod n a m
        b = take (fromIntegral k) $ iterate (squareMod n) b0
        iter [] = False
        iter (x:xs)
            | x == 1 = False
            | x == n' = True
            | otherwise = iter xs

-- (eq. to) pow' (*) (^2) n k = n^k
pow' :: (Num a, Integral b) => (a->a->a) -> (a->a) -> a -> b -> a
pow' _ _ _ 0 = 1
pow' mul sq x' n' = f x' n' 1
    where
        f x n y
            | n == 1 = x `mul` y
            | r == 0 = f x2 q y
            | otherwise = f x2 q (x `mul` y)
            where
                (q,r) = quotRem n 2
                x2 = sq x

mulMod :: Integral a => a -> a -> a -> a
mulMod a b c = (b * c) `mod` a
squareMod :: Integral a => a -> a -> a
squareMod a b = (b * b) `rem` a

-- (eq. to) powMod m n k = n^k `mod` m
powMod :: Integral a => a -> a -> a -> a
powMod m = pow' (mulMod m) (squareMod m)

-- simple for small primes
primes :: [Integer]
primes = 2:3:primes' where
    1:p:candidates = [6*k+r | k <- [0..], r <- [1,5]]
    primes'        = p : filter isPrime candidates
    isPrime n      = all (not . divides n)
                                   $ takeWhile (\p -> p*p <= n) primes'
    divides n p    = n `mod` p == 0
isPrime :: Integer -> Bool
isPrime n | n < 2 = False
          | otherwise = f primes where
            f (p:ps) | p*p <= n = if n `rem` p == 0 then False else f ps
                     | otherwise = True

main = do
    print . head $ filter isFragile (primesFrom $ 10^1000)

I think you can remove everything except the last 3...

it ends in 5 if i remove the last 3 so is divisible by 5

No I mean removing everything until you have just the last 3 left, which is prime.

doh. you are right. just a sec.

Still not fragile. 61 (removing the first 1000 digits) is prime

@Optimizer No, it don't match the lengths of 9s in the front or the back so a single remove could not make them match.

@JohnMeacham My program suggests that this number turns into prime if you remove 386 digits from the left.

@JohnMeacham Oh, forgot that removal is in range ..

@SuboptimusPrime Hmm.. pari/gp seems to think it is composite.

@JohnMeacham My program also think's it's prime. And so does WolframAlpha: http://goo.gl/YmXW4q

strange, pari/gp is supposed to be quite good. I'll dig up some other CAS software and try to figure out what is going on.

Sure you are checking the same number? Because I just checked it again with pari/gp and it also says prime.
We are talking about the number with 410 9s, than a 7 and than 253 9s = 10^664 - 1 - 2*10^253.

Okay, I wrote a C program using openssl's crypto library to verify the primes. It looks like there were some spurious ones misidentified, I should have pumped up my probabalistic prime tester for how huge of numbers i am testing. A chance in a few hundred million of misidentifying a prime suddenly becomes relevant when working with a thousand digit numbers. :) I guess it makes me feel better that Maple had the same bug and ran into it on a measely 350 digit number.

Verified, the new number is a fragile prime.

Please, verify your numbers before posting. If you remove the left 1256 digits from your 1276-digit number, you'll get 99999994999999999999, which is prime.

erf. cut-n-paste wrong line by one, 1277 was the verified one.

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


text:
CSS attribute selector efficient "greater than selector" code
The goal is to find a way better than the current best known way of encoding the index of a child HTML element, so that encoded indices have the following property.
if (index_i >= index_p) {
  assert(encoding(index_i).indexOf(encoding(index_p)) == 0);
}

if (index_i < index_p) {
  assert(encoding(index_i).indexOf(encoding(index_p)) !== 0);
}

The current best known way of doing this is with a form of unary encoding (without the usual trailing zero. So, for example, when index_p = 10:

encoding(index_p) == "11111111111" true
index_i = 9; encoding(index_i) == "1111111111" true
"11111111111".indexOf("1111111111") !== 0 true
"1111111111".indexOf("11111111111") == 0 true

Application
An application of this is being able to use document.querySelectorAll for obtaining all child elements "greater than" a certain index, via utilisation of the "starts with" attribute selector, ^=.
For example, if we have a set of 100 div elements, and each div element has been given an attribute ei equal to its encoded index value. If our goal is to obtain a list of the last 51 of div elements, one way to do this is to request:
document.querySelectorAll('div[ei^='+Array(50).join("1")+']');
However, if we have interesting numbers of divs (1000, 10000), then we use a lot of memory storing these attribute indexes. So we get the typical "memory" vs "speed" tradeoff for setting up this indexing system.
The question is : is there a way to do the same thing, using an encoded index, such that it is shorter than this pseudo-unary version?
Motivation
One motivation that contributes to this question post here is the following subtle point: the elements may not necessarily be in the indexed order.
This unusual occurrence is by no means something that one would expect in ordinary use of the DOM, but if we are absolutely positioning the elements based on their indices, and we are swapping, inserting and deleting the elements, then it is possible to have a meaningful piece of HTML where document order is actually not related to the rendering order that ends up meaning something to somebody. And in such a case, we may still need to look at a range of elements, such as, all elements with an index larger than 72, and with an indexing method with properties like those described above, then we can use the starts with attribute selector to gather together this set.

Why limitation on starts with and other types are disallowed?

@Qwertiy sure if you can see a way to achieve this goal with other types of selector that would work too.

This could be an interesting challenge, but as it currently stands, there is no winning criterion, and it is unclear what you are asking.  I am voting to close it until it is fixed.  If this is not meant to be a challenge, but instead a programming question, you should ask for help at Stack Overflow.

You could always try something of the form
<tag h="111" t="11111" o="1">

where you use your unary encoding for each of the hundreds (h), tens (t) and ones (o) attributes.
A greater-than CSS selector would then look like
tag[h^="1111"],tag[h="111"][t^="111111"],tag[h="111"][t="11111"][o^="1"] { ... }

but frankly, if your tags are just retaining some property that persists in spite of reordering, etc., why not just run a script that selects the last n marked tags on DOM load and assigns the class iamlast, then use the .iamlast CSS selector?

That's good, I like your idea for using radix plus unary. It works. Radix sort has a similar idea. I understand your suggestion for iamlast however it would not work because the number of elements we may wish to select is dynamic. We might want to select 10 elements after some modifications have been made, 20 elements next time, 5 the time after, 57 the time after that. So keeping track of real order, regardless of the document order, for the whole life of the page, is necessary.


text:
Complete a Tournament Bracket
Your task is to create a program which outputs a completed tournament bracket given a list of entrants, their seeds, and their scores in each game; in the fewest characters possible.
Input
Your entrants will have the following data. You can organize your data in whatever form you like, but you cannot pre-sort your array or do any other pre-processing. The scores represent an entrant's score in each round, in other words they determine who moves on to the next round.
Example Input #1
[   {name: "James",         seed: 1,    scores: [12, 6,]}
,   {name: "Sarah",         seed: 4,    scores: [1, 16]}
,   {name: "Andre 3000",    seed: 3,    scores: [3000, 3000]}
,   {name: "Kim",           seed: 2,    scores: [20, 4]}
]

Example Input #2
[   {name: "Andy",  seed: 1,    scores: [1, 8, 4]}
,   {name: "Kate",  seed: 4,    scores: [1, 1, 8]}
,   {name: "Steve", seed: 3,    scores: [30, 1, 0]}
,   {name: "Linda", seed: 5,    scores: [4, 4, 5]}
,   {name: "Kyle",  seed: 2,    scores: [21, 0, 18]}
]

Output
Your output should resemble the examples below, and must follow these rules:

For each round in the tournament, the entrants are paired up and those pairs are output.
In the event of an odd entrant count, your program must account for and output byes. The entrant who gets the bye is the entrant who has been given the fewest bye weeks so far, and in the event of a tie, the best seed (1 is the best).
Pairing is based on the seed. Excluding byes, the best seed (1 is the best) is paired with the worst, the next best is paired with the next worst seed, etc.
The best seeds should be first in the pair, and at the top of the bracket.
The tournament champion should be output.

.
Example Output #1 (for input #1)
Round 1
James vs Sarah
Kim vs Andre 3000
Round 2
James vs Andre 3000
Champion
Andre 3000

Example Output #2 (for input #2)
Round 1
Kyle vs Linda
Steve vs Kate
Andy BYE
Round 2
Andy vs Steve
Kyle BYE
Round 3
Andy vs Kyle
Champion
Kyle

Extra props for anyone who codes a separate version of their program which prints an actual bracket.
Scoring
Assume input is correct, standard loopholes, etc and so forth. This is code golf, so fewest bytes win. In the event of a tie, most votes win. Good luck!

@Geobits Good catch! I've changed/clarified the rules around bye weeks. I also changed the seed lingo to "best" and "worst".

@FryAmTheEggman I've made the output requirements specific and added bracket output as extra. Thanks!

@Optimizer I will say no, since any additional input would probably indicate pre-processing or decision making outside of the program.

@Optimizer Are you trying to avoid declaring a variable in your code by stuffing variables into the input? I'll still say no, unless you explain the legitimacy of it.

You got me :D :D

CJam, 156 151 144 bytes
q~0f+{{1=}$_,2%{{W=}$())+aa\{1=}$\}L?\_,2//)W%a+z\+_{0f=_,1={~" BYE"+a}*" vs "*N\}%"Round "U):U+\+\{{2=0=}$W=_2=(;2\t}%_W=2=}g~0=a"Champion"\]N*

This can definitely be golfed further.
The input is in an array of array format, like:
[["James" 1 [12 6 15]] ["Sarah" 4 [3 2 5]] ["Franko" 2 [20 1 5]] ["Max" 5 [22 10 7]] ["Arthur" 3 [20 15 20]]]

where each array element is the detail about the user in [name seed score_array] format
The output for the above input is:
Round 1
Franko vs Max
Arthur vs Sarah
James BYE
Round 2
James vs Max
Arthur BYE
Round 3
Arthur vs Max
Champion
Arthur

Try it online here


text:
Short drawing programme
You just invited a liberal arts major to your house and you're telling him/her

"You know, I am a great programmer and I can do x and y and z..."

S/he quickly gets bored and asks you:

"If you really are a great programmer, can you make a programme to let me draw, I just need to draw lines on the screen by using the
  mouse, and selecting different colours in any manner".

Your code may import standard libraries. Your code may require the colours to be selected via the keyboard.
This is code-golf; shortest code wins.
Bullet points

The lines are drawn by moving the mouse around while pressing the left button.
Bresenham's Line Algorithm is not necessary any built-in algorithm will do the trick
If the user can change the line thickness in any way you get a * 0.8 bonus but it is not obligatory.
I guess it should be nicer to implement the line-drawing ourselves, but if you want you can import a library for that just say it in the code description.
The minimum is 5 different colours (red,green,blue,white,black). If you make them change randomly you get a penalty of *1.2. You may change them in any way you may want (both buttons and key presses are OK).
Drawing them pressing the mouse between to points or freehand would be best (i.e. as you do in paint) and gives you a bonus of *0.7 , but any other method is okay: (example) click two points and draw a line between those points?
The drawing canvas has to be 600x400
Changing the colour should change the colour only of the lines that will be drawn in the future.
Implementing a "Clear All " command is not obligatory but if you implement that you get *0.9 bonus.

How are lines required to be drawn? Bresenham's Line Algorithm? Do the lines need to be variable thickness? Do we need to implement the line-drawing ourselves? Please specify more. And it is normally assumed that our code may "import standard libraries". How many colors must be choosable? Is 2 okay? Or how about randomly choosing color every time a keyboard button is pressed?

Some more clarifications needed: How are the lines drawn? Do you click two points and draw a line between those points? How big does the drawing canvas have to be? How many colors must be supported? Can changing the color also change the color of every other line? Etc. This challenge is currently very underspecified.

@Quincunx  I have put a Q & A in the question tell me if it is ok now.

Please condense the Q&A. Eliminate the Questions and make the Answers stand on their own as bullet points. Note that comments can sometimes get deleted. The Bresenham's Algorithm Point does not make any sense without reading the comment. I assume what you are saying is that Bresenham's algorithm is not required and any algorithm or standard/library function will do. 2. Ultimately winning depends on in what language it is easy to get into the API and access the Right button (instead of the usual left button.)

@steveverrill I made an error "while clicking the left button"

"Drawing them pressing the mouse between 2 points is best but any other method is ok" What about freehand drawing like with the pencil tool in paint? I suggest you make it clearer, or eliminate the "any other method is ok" altogether. 2. The method of changing colour should be better specified. For example, can it be done from the keyboard, by rotating through the colours with the other mouse button, or does it have to be by clicking an on-screen pallete?

The currently accepted answer does not implement drawing in white. Does the question need to be changed to make clear that the listed colours (red,green,blue,white,black) are not required, and it is only the number of colours which counts, or does the accepted answer need to have its score adjusted for not providing all of the required colours?

@githubphagocyte if you like, you may switch purple for white, and save a byte in the process. There are shorter solutions now anyway; the accepted answer should be changed.

Doesn't *0.8 reduce original score to 80%?

HTML + jQuery + CSS - 507 x (0.7 x 0.8 x 0.9) = 255.528
Not as short as I thought it would be, but I like the result.
Features:

Click-and-drag drawing mode. (0.7)
Seven colors (black + rainbow).
Variable brush width (slider control). (0.8)
Clear all function. (0.9)

Live Demo: http://jsfiddle.net/onsLkh8y/9/

HTML - 84 bytes
<input id="r" type="range" min="1" max="9"><canvas id="c" width="600" height="400"/>

CSS - 35 bytes
#c{border:1px solid;cursor:pointer}

jQuery - 388 / 446 bytes
W3C compliant browsers (e.g. Chrome) - 388 bytes
var t=c.getContext('2d');$.each('black0red0orange0yellow0green0blue0purple0clear'.split(0),function(k,v){
$(r).before($('<button>'+v+'</button>').click(function(){k>6?t.clearRect(0,0,600,400):t.strokeStyle=v}))})
$(c).mousedown(function(e){t.lineWidth=$(r).val();t.beginPath();t.moveTo(e.offsetX,e.offsetY)})
.mousemove(function(e){if(e.which==1){t.lineTo(e.offsetX,e.offsetY);t.stroke()}})

Cross-Browser version (fixes for Firefox, Safari, IE) - 446 bytes
var t=c.getContext('2d');$.each('black0red0orange0yellow0green0blue0purple0clear'.split(0),function(k,v){
$(r).before($('<button>'+v+'</button>').click(function(){k>6?t.clearRect(0,0,600,400):t.strokeStyle=v}))})
var d,p=$(c).offset();$(c).mousedown(function(e){d=t.lineWidth=$(r).val();t.beginPath()t.moveTo(e.pageX-p.left,
e.pageY-p.top)}).mousemove(function(e){if(d){t.lineTo(e.pageX-p.left,e.pageY-p.top);t.stroke()}}).mouseup(function(){d=0})

Fixes:

FireFox - event.offset[X|Y] are undefined.
Safari - event.which and event.buttons are not meaningfully defined on mousemove.
Internet Explorer - works with both of the above fixes, although using e.buttons would have been sufficient.

$(document).ready in codegolf?

you don't need the quotes for id= and maybe others too (haven't done html in a while)

Processing - 93 · 0.9 = 83.7
With next to no overhead for drawing, but a very verbose syntax, in Processing the best score is probably reached without any nice features and only one bonus:
void setup(){
size(600,400);
}
void draw(){
if(mousePressed)line(mouseX,mouseY,pmouseX,pmouseY);
}

Score: 93 · 0.9 = 83.7 (Newlines are for readability only and are not counted in the score.)
However, it's much more fun with all the bonuses in place:
void setup(){
size(600,400);
}
int i,x,y;
void draw(){
stroke(7*i%256,5*i%256,i%256);
strokeWeight(i%9);
if(keyPressed)i++;
if(!mousePressed){x=mouseX;y=mouseY;if(x<0)background(0);}
}
void mouseReleased(){
line(x,y,mouseX,mouseY);
}

Score: 221 · 0.8 · 0.7 · 0.9 = 111.4
It's used like this:

Click and drag the mouse to draw a straight line.
While clicked, drag the mouse off the left side of the window and release the mouse button to clear the screen.
Holding down any key will cycle through the red, green and blue values of the drawing colour and through different stroke thicknesses. Since the cycling periods are different, practically all combinations can be reached (with a bit of trying).

Edit:
Since freehand drawing gives the 0.7 bonus as well, here is yet another solution:
void setup(){
size(600,400);
}
int i;
void draw(){
stroke(7*i%256,5*i%256,i%256);
strokeWeight(i%9);
if(keyPressed)i++;
if(key>9)background(0);
if(mousePressed)line(mouseX,mouseY,pmouseX,pmouseY);
}

Score: 188 · 0.8 · 0.7 · 0.9 = 94.8
It's used like this:

Click and drag to draw freehand lines.
Hold the tab key to change the colour and stroke thickness. This can also be done while drawing (see picture).
Hit any key but tab and then tab to clear the screen.

Freehand also gives you the bonus.

@Caridorc: Ah, great. I will update my answer then.

That's going to be hard to beat.

if(key>0) is shorter than if(keyPressed)

Python 2.7 - 339 197 324 * (0.7 * 0.8 * 0.9) = 163
Edit: I discovered pygame can draw lines with variable width so here is an update.
An experiment in using the PyGame modules.
A simple paint program that draws lines from the MOUSEDOWN event (value 5) to the MOUSEUP event (value 6). It uses the pygame.gfxdraw.line() function. Pressing the TAB key will cycle through 8 colours. Pressing the BACKSPACE key will clear the display to a carefully crafted paper white colour. The ENTER key will cycle the brush size through 0-7 pixels in width.
I am new at code-golf so I may have missed some methods of reducing the code size.
import pygame as A,pygame.draw as G
P=A.display
D=P.set_mode((600,400))
C=(0,255)
S=[(r,g,b) for r in C for g in C for b in C]
w=n=1
while n:
 e=A.event.wait()
 t=e.type
 if t==12:n=0
 if t==2:
  if e.key==9:n+=1
  if e.key==13:w+=1
  if e.key==8:D.fill(S[7])
 if t==5:p=e.pos
 if t==6:G.line(D,S[n%8],p,e.pos,w%8)
 P.flip()

Sample picture 1:

Sample picture 2:

I now have a file on my computer named ms-paint.py.

Enjoy the speed and clean GUI. How MS-Paint was meant to be. I hope I don't get sued by a certain large software company...

C# 519 x 0.7 x 0.8 x 0.9 = 261.6 Using the DrawLine method.
Golfed:
using System;using System.Drawing;using System.Windows.Forms;class f:Form{[STAThread]static void Main(){f F=new f{Width=600,Height=400};Point s=default(Point);sbyte[]c={0,0,0,1};F.MouseDown+=(_,e)=>{s=new Point(e.X,e.Y);};F.MouseUp+=(_,e)=>{F.CreateGraphics().DrawLine(new Pen(Color.FromArgb(255,c[0],c[1],c[2]),c[3]),s.X,s.Y,e.X,e.Y);};F.KeyPress+=(a,e)=>{unchecked{switch(e.KeyChar){case'r':c[0]++;break;case'g':c[1]++;break;case'b':c[2]++;break;case't':c[3]++;break;case'c':F.Invalidate();break;}}};F.ShowDialog();}}

Readable:
using System;
using System.Drawing;
using System.Windows.Forms;

class f : Form
{
    [STAThread]
    static void Main()
    {
        f F = new f { Width = 600, Height = 400 };
        Point s = default(Point);
        sbyte[] c = { 0, 0, 0, 1 };
        F.MouseDown += (_, e) => { s = new Point(e.X, e.Y); };
        F.MouseUp += (_, e) => { F.CreateGraphics().DrawLine(new Pen(Color.FromArgb(255, c[0], c[1], c[2]), c[3]), s.X, s.Y, e.X, e.Y); };
        F.KeyPress += (a, e) =>
        {
            unchecked
            {
                switch (e.KeyChar)
                {
                    case 'r': c[0]++; break;
                    case 'g': c[1]++; break;
                    case 'b': c[2]++; break;
                    case 't': c[3]++; break;
                    case 'c': F.Invalidate();break;
                }

            }
        };
        F.ShowDialog();
    }
}

By holding r, g or b on your keyboard it changes the color of the next line by incrementing an sbyte-array at the corresponding index. It will start at 0 again when overflowing. So this gives us plenty colors.
Same goes for thickness of the line which is increased by holding t.
Pressing c clears the form.

Mathematica - 333 x 0.7 x 0.8 x 0.9 = 168
l = {}; c = Black; s = .01;
ColorSetter@Dynamic@c
Dynamic@s~Slider~{0, .02}
Button["Clear", l = {}]
"/" Checkbox@Dynamic@b
EventHandler[
 Dynamic@Graphics@{White, Rectangle@{600, 400}, l},
 {"MouseDown" :>
   AppendTo[l, p = {}; {c, Thickness@s, Line@Dynamic@p}],
  "MouseDragged" :> (p =
     Append[p, MousePosition@"Graphics"][[If[b, {1, -1}, All]]]),
  "MouseUp" :> (l[[-1, 3]] = Line@p)
  }
 ]

Can this draw lines from point to point? It appears to allow free hand drawing only.

@githubphagocyte Yeah, free hand only at the moment.

@githubphagocyte Added a straight line option

best answer thus far.

I love the drawing though.

Tcl/Tk, 252
x 0,8 x 0,7 x 0,9
= 127,008
253 x 0,8 x 0,7 x 0,9= 127,512
254 x 0,8 x 0,7 x 0,9= 128,016
255 x 0,8 x 0,7 x 0,9= 128,52
grid [canvas .c -w 600 -he 400]
set c red
incr t
lmap k {1
B1-Motion
3
MouseWheel
2} s {{set L [.c cr l %x %y %x %y -f $c -w $t]}
{.c coo $L "[.c coo $L] %x %y"}
{set c [tk_chooseColor]}
{if $t|%D>0 {incr t [expr %D/120]}}
{.c de all}} {bind . <$k> $s}

Tcl/Tk, 267
x 0,8 x 0,7 x 0,9
= 134,568
grid [canvas .c -w 600 -he 400]
set c red
set t 0
bind .c <1> {set L [.c cr l %x %y %x %y -f $c -w $t]}
bind .c <B1-Motion> {.c coo $L "[.c coo $L] %x %y"}
bind .c <3> {set c [tk_chooseColor]}
bind .c <MouseWheel> {if $t||%D>0 {incr t [expr %D/120]}}
bind .c <2> {.c de all}

To use it:

Left mouse button behaves as question requests
The initial color is red. Right mouse shows a dialog which allows the user to choose the color which will be used the next time. Always press OK button, otherwise color will be undefined. I could fix this, but it would consume bytes
To adjust the thickness of the line that will be used next time, you can rotate the mouse wheel: Up=thicker, Down=thinner
To clear the image press the middle mouse button

A simple test:

DarkBASIC Pro - 318 x 0.7 x 0.9 = 200.34
The most interesting thing here is using some bitwise logic on the current keyboard scancode to change the color. I use two different bits from the scancode for each channel - so almost any 6-bit color is possible.

Hold down any key on your keyboard to use a color (on my American keyboard: White=F5, Black=no key, Red=2, Green=- (minus), Blue=b)
Right-click to clear

Here is a compiled EXE: Download
#constant a set current bitmap
set display mode 800,400,32
create bitmap 1,800,400
do
s=scancode()
ink rgb((s&&3)*85,((s/4)&&3)*85,((s>>4)&&3)*85),0
m=mousex()
n=mousey()
o=mouseclick()
if o*(d=0) then d=1:x=m:y=n
a 1
if (o=0)*d then d=0:line x,y,m,n
if o=2 then cls
a 0
cls
copy bitmap 1,0
if d then line x,y,m,n
loop

BBC BASIC - 141 no bonuses
My first programming language and generally never used by me anymore :)
SYS "SetWindowPos",@hwnd%,0,0,0,600,400,6:VDU 26
1 MOUSE X,Y,b
IF b=4 THEN GOTO 4
GOTO 1
4 MOUSE x,y,b
IF b=0 THEN LINE X,Y,x,y:GOTO 1
GOTO 4

Python 2.7 - 384 * .8 * .7 = 215.04
from Tkinter import*;o=1
a='0f';C=['#'+r+g+b for r in a for g in a for b in a]
def i(a):global o;o+=1
def d(a):global o;o-=1
def I(a):global u;u+=1
def D(a):global u;u-=1
m=Tk();u=0;c=Canvas(width=600,height=400);c.bind("<B1-Motion>",lambda x:c.create_rectangle((x.x,x.y,x.x+o,x.y+o),fill=C[u],outline=C[u]));m.bind("q",i);m.bind("w",d);m.bind("x",D);m.bind("z",I);c.pack();mainloop()

With all bonuses: 462 * .9 * .8 * .7 = 232.848
from Tkinter import*;o=1
a='0f';C=['#'+r+g+b for r in a for g in a for b in a]
def i(a):global o;o+=1
def d(a):global o;o-=1
def I(a):global u;u+=1
def D(a):global u;u-=1
m=Tk();u=0;c=Canvas(width=600,height=400);c.bind("<B1-Motion>",lambda x:c.create_rectangle((x.x,x.y,x.x+o,x.y+o),fill=C[u],outline=C[u]));m.bind("q",i);m.bind("w",d);m.bind("x",D);m.bind("z",I);m.bind("m",lambda _:c.create_rectangle((0,0,602,402),fill=C[7],outline=C[5]));c.pack();mainloop()

APL (dzaima/APL), 65 bytes, no bonuses
P5.size←2⌿600
P5.draw←{P5.LM.p:P5.G.ln P5.mx P5.my P5.pmx P5.pmy}

A straightforward port of the existing processing answer.
Explanation
P5.size←2⌿600                                        set canvas to 600x600 pixels
P5.draw←{                                         } do the following every frame:
P5.draw←{P5.LM.p:                                 } if the mouse is held down:
                 P5.G.ln                            draw a line from
                         P5.mx P5.my                current mouse position
                                     P5.pmx P5.pmy  to previous mouse position

I think this is currently the best score here. Well done! :D

@Dion a̶n̶d̶ ̶t̶h̶e̶ ̶m̶o̶s̶t̶ ̶l̶o̶w̶ ̶e̶f̶f̶o̶r̶t̶ ̶o̶n̶e̶

as it often is with codegolf :p