text:
A small puzzle. Why does this code work the way it does?
This was given to me by a friend of mine, it prints out 0 through 9. We have been quite puzzled over this. Does anyone know why this works?
#include <iostream>

using namespace std;

void x(int a)
{
    *(&a-1) += a;
}

int main()
{
    for(int i = 0; i < 10; ++i)
    {
        x(8);
        i = 0;
        cout << i << endl;
    }
}

CodeGolf.SE is a place to post programming contests with well defined winning conditions. This would, perhaps have been better on Stack Overflow.

@dmckee I would have thought that "Programming puzzles" in the title would reference stuff like this. Sorry :)

Imho, this clearly belongs here, not stackoverflow, the closure reflects badly on the moderator.

void(int a) is never printed.  That function is just garbage.  What is actually being printed is variable i: cout << i << endl; i is started at 0: int i = 0;, then is incremented by 1: ++i;, as long as it is less than 10.  The call x(8) does nothing and is unnecessary.

First of all, the line *(&a-1) += a; is undefined behavior, so this could do anything depending on compiler version, flags used, alignment of the stars, etc.
That said, the reason why it works in your case is probably because &a-1 happens to point to the return address of x, and incrementing it by 8 causes the i = 0; to be skipped.

oh my god... that's nasty.

in other words a buffer overflow without the buffer (or a 1 element buffer)

The reason this works is because your compiler passes the a parameter on the stack. Before the parameter, the code pushes the return address of the method onto the stack:
004A0008 | 00000008 ; a parameter
004A0004 | 00401200 ; return addr
004A0000 | ...

The &a part of the expression points to the address of the parameter on the stack, in this case I've used 004A0008. The a-1 then subtracts sizeof(int) from that address, giving you 004A0004. The * dereferences that address, so its value can be edited. This means that when you add 8 to the value at 004A0004, it alters the return address. When the method returns, it ends up 8 bytes ahead of where it should have been, skipping the i=0.


text:
I used to solve code golf puzzles like you, but then I took an arrow in the knee
Getting hit in the knee with arrows seems to be the injury of choice right now. As such, I propose the following golf challenge.
You have an adventurer that looks like this:
  O
 /|\
/ | \
  |
  |
 / \
/   \

Given a text file that contains one bow (drawn as a } symbol), a set of walls (drawn as # symbols) and one adventurer, write the smallest code that calculates the angle and initial velocity at which you should fire an arrow in order to hit him in the knee.
Assume the following:

Each character in the file is 0.5 x 0.5 meters.
The arrow is fired from the center of the }, i.e. an offset of 0.25m, 0.25m
Gravity is 10ms^-2
Arrow weighs 0.1kg
Arrow is a point, i.e. collisions only occur when the arrow's coordinate enters one of the blocks.
Maximum initial velocity is 50m/s
Angle may be between 0 (straight up) and 180 (straight down)
Hitting any part of the adventurer's leg is considered a hit to the knee.
A wall (# character) takes up one entire 0.5m x 0.5m block.
The arrow can travel over the "top" of the file, but there's nothing to stop the input from starting with a ceiling of # characters.
You can't penetrate walls with arrows.
Hitting any other part of the adventurer is not allowed!
You should display an error if hitting him in the knee is impossible.

Example input:
                                 #
}                                                     O
                        #                            /|\
                                                    / | \
            #                                         |
                            #                         |
                                                     / \
                                                    /   \

Feel free to ask questions if you need to :)

Can the arrow travel "over" the area depicted by the text file?

How many people do you know who are over 3m tall? :P

@JB - Yes, but there's nothing to stop the input starting with a big line of #############...

@PeterTaylor - Everyone knows that people in RPG games are disproportionately huge ;)

@Polynomial fair enough. Thanks for answering :)

Will the adventurer always be on the bottom row? And do arms and legs fill the entire block too? (Or at least the entire diagonal, which is equivalent for practical purposes?)

Is there an e.g. rectangular envelope around the adventurer that's free of walls?

@PeterTaylor - They aren't always on the bottom, no. For simplicity you could say that each leg takes up the whole block, but in general I would prefer it if you assumed the leg was a line between opposite sides.

@leftaroundabout - No. They could be entirely encased in walls. In that case you would hit the final assumption - "You should display an error if hitting him in the knee is impossible."

The weight of the arrow is redundant, surely ?

@PaulR - Hehe, I put it in there as a tease. Wondered how long it would be until someone noticed it was irrelevant :P

I need to make a language where this is 9 bytes-- Dovahkiin

Python, 599 chars
import os,sys
from math import*
I=os.read(0,999)
O=[]
h=v=0
for i in I:
 if'#'==i:O+=[(h,v,h+1,v+1),(h+1,v,h,v+1)]
 if'O'==i:O+=[(h,v+1,h-2,v+3)];T=(h,v+5,h-2,v+7)
 if'}'==i:e=h+.5;c=v+.5
 h+=1
 if'\n'==i:v+=1;h=0

def X(K,L):
 A,B,C=K;p=L[0];q=L[2]-p;r=L[1];s=L[3]-r;A,B,C=A*q*q,2*A*p*q+B*q-s,A*p*p+B*p+C-r;d=B*B-4*A*C
 return 0 if d<0 else any(0<x<1 for x in[(sqrt(d)-B)/2/A,(-sqrt(d)-B)/2/A])

R=range(1,999)
for v in R:
 for z in R:
  z*=pi/999;d=v*sin(z)/10;b=-v*cos(z)/10
  K=20/d/d,b/d-40*e/d/d,c+20*e*e/d/d-b*e/d
  if X(K,T)and not any(X(K,x)for x in O):print v/2,z;sys.exit(0)
print'ERROR'

The X(K,L) routine takes a parabola K=(a,b,c) representing y=ax^2+bx+c and a line segment L=(a,b,c,d) representing the segment between (a,b) and (c,d).  Both obstacles (O) and the target (T) are repesented as line segments.  All distances are scaled by a factor of 2.
The example input gives the following trajectory (by default, the minimum velocity one):
  --                             #          --
--                                            -       O
                        #                      -     /|\
                                                -   / | \
            #                                    -    |
                            #                     -   |
                                                   - / \
                                                    -   \

you can reverse R to get the maximum velocity path:
                                 #
-------------                                         O
             -----------#                            /|\
                        --------                    / | \
            #                   -------               |
                            #          -----          |
                                            -----    / \
                                                 -----  \

Good work. Only complaint is that the input size limit is 999 bytes. It could quite easily be more, considering the potential size of these ASCII drawings. 9999 would be more sensible, at the cost of only 1 character. (though at that point you might as well do 8**5 to get 64kB)

Pretty sure you could then save that one character by assigning w=v+1 and replacing the 3 instances of v+1 with w. I don't code much Python though, so I may be wrong.

source: Stack Exchange

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

sort: votes


text:
Say "Hello" to the world in ASCII art
Challenge: Produce the following output using as few chars as possible:
 _   _      _ _                             _     _ _
| | | | ___| | | ___    __      _____  _ __| | __| | |
| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |
|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|
|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)
                    |/

Rules and restrictions:

You may not use FIGLet or any similar tools.  (Otherwise, figlet Hello, world! would be a trivial and pretty much unbeatable solution.)
Your program must consist entirely of printable ASCII characters — specifically, code points 9 (TAB), 10 (LF) and 32 – 126.  (If your language / OS requires CRLF line breaks, you may use those instead of plain LFs.)  Yes, this regrettably disqualifies any language that requires non-ASCII characters (or non-textual data) as part of its syntax.
The output must look exactly like the example above.  You may, however, include extra whitespace around the output if you want.  You may assume 8-character tab spacing (or your chosen platform's native default setting, if it has a consistent one).

Ps. To set the par, I came up with a 199-char Perl solution.  I won't post it yet, though, in case someone comes up with it independently.  (Also, it's kind of cheesy.)  Of course, this shouldn't discourage you from posting your own solution, even if it's longer.

Update: Now that han has beaten it by one char, here's my cheesy 199-char Perl solution:
use Compress'Zlib;say uncompress unpack u,'M>-I]BT$*`S$,`^]YQ=R:0,&_Z<DP?8@?WVQJ]E2J"%E$$@)R(/(/MCJ*\U!OM`Z#=5`4Y>6M=L\L%DMP&DB0V.4GQL&OOGB$4:%`4TT4!R8O-Z(^BTZWNV?>F86K:9+""-35*-LNC:T^D:_$#%^`";"DD0'

It's very similar to D C's solution (and all the other zlib/gzip-based solutions in various languages), except that I used uuencoding instead of base64 for the compressed text and a few other minor golfing tricks.

Update 2: I think it's time to officially accept a winner.  The first place goes to konsolenfreddy's PHP code, since, however you count the chars, it is the shortest submitted so far.  In fact, combining it with the optimized DEFLATE stream from my 199-char Perl code yields an even shorter 176-char solution:
<?=gzinflate(base64_decode("fYtBCgMxDAPvecXcmkDBv+nJMH2IH99savZUqghZRBICciDyD7Y6ivNQbwOg3VQFOXlrXbPLBZLcBpIkNjlJ8bBr754hFGhQFNNFAcmLzeiPotOt7tn3plq2mSwgjU1SjbLo2tPpGvxAxfgA"));

However, I do think that han deserves a special honorary mention for getting so close without using any pre-written decompression tools.  Congratulations to both of you, and a happy new year to everyone!

Ok, I have to do this one in C...

Stax, 137 bytes
"9&BO]h>&)>3ieuCoKVKVnuOoT'E-^Z(1.3u[);h1[RTOGqTZkoQx?KMy&9ctG&*y~HxR9%GYn.rYMdMcOOq^wXc@%zy*P[*Q"90|E|B"0+1"{%",``_|\/()V'"@]}R.1 |t54/m

Run and debug it
It works like this.

Start with a big string literal.
Convert to integer by decoding as a base-90 number.
Convert that number to binary.
Runs of 0s followed by a 1 are translated into non-space characters.
All remaining 1s are replaced with spaces.
The resulting string is split into 54-character lines.

Congrats, looks like this is the shortest solution now! :)

Perl 5.10 - 195 198 202 203 characters
Here's an entry that does not require any libraries beyond basic regexp matching.  The encoded string is 131 characters, and the code to decode and print it takes up 64 characters (assuming no newline at the end of the source).  The idea is to represent common 3-character strings by lower case letters.
s!!xfefxxf\t\t\tf efyx
no| cnocfxefxceyxm|xmn
nm|wtnwtgt/uvy \\| 'ym|w`o|
pepyy/o| _ogrr/ _opn (ml
l lbyly|by( )fiihyjm lb,y_
\t\tf |/!;s!\w!substr'(_)\___   \_/|_| |  V \ / _',-95+ord$&,3!eg;say

The encoder is a lot longer and unfortunately not very readable right now.  The basic idea is to use dynamic programming to find the shortest encoding for each line, given a fixed set of string substitutions.  The string of substitutions on the last line was built by trial and error, and it is possible that another string of substitutions might lead to a shorter program than above.
One trick here is that some substitutions are shorter than 3 characters long: due to the way perl substr works, x is replaced by ' _' and y by '_'.  The latter is necessary because \w in the regex matches '_', which is then replaced by '(_)'.

+1, very nice. You can save 2 chars by replacing print by say

@M42: As far as I could figure out, on perl 5.10 to use say you need to either do use 5.010; or run the script as a one-liner with perl -E 'script here'.  The former makes the code longer and the latter is not appropriate for a multi-line script.  Did I miss something?

The -E doesn't count in number of char.

@M42: Maybe I'm being thick, but right now I can't see how to use -E profitably with a multi-line script that includes both single quotes and backslashes.

Per this meta thread, "the -M5.01 is free".  So feel free to use say if you want.

Ps. You can save a few more chars by using s''...' instead of $_=q!...!; just remember to escape the single quote.  With that and say instead of print (and leaving out the last newline), I get this down to 198 chars.

@IlmariKaronen: Ok, thanks! I edited the solution.

BTW, I tried using tabs instead of # for the long runs of whitespace and got your solution down to 190 chars.  I wonder if going below 184 chars is possible -- that would beat all the zlib-compressed solutions so far.

Brainfuck - 862 characters:
>++++[<++++++++>-]>-----[<---->---]<+++>>--[<+>--]<---<<.>.<...>.<....
..>.<.>.<.............................>.<.....>.<.>.>>++++++++++.<.<<.
>>.<<.>>.<<.>>.<<.>...>.<<.>>.<<.>>.<<.>...<....>..<......>.....<..>.<
.>..>.<<.>>.<<.>..>.<<.>>.<<.>>.>.<.<<.>>.<.>.<<.>>.>>>-[<->+++++]<---
-.<<<<.>.<.>---.+++<.>>.<<.>>.>>.<<<<.>.<.>---.<...>.<.>.<.>>>>.<<<.<.
>>>>.<<<<.>>>>.<<<<.>+++.<.>---.>.<<.>>>>>>---[<+>+++++++]<++.<<<<+++.
.>.<<.>>.>>.<<<<.>.+.-<.>>.<<.>>.>.<.<<..>.<..>>.<<..>..>>>.<<<<.>>.<<
.>>.<<.>>>>>+.<<<<.>>>>+.<<<<<.>>.<<...>---.<.>------.<..>.<.>>>>.<<<<
.>>>>>-.<<<<+++++++++.>>>>+.<<<<<.>>.<<.>>.<<..>>.<<.>>.<<.>>>>>-.<<<<
.>.<<.>>.<.>.>.<.<.>.<<.>>.<.>.<---.+++...>.<.>.<.>.<---.+++...>>>>.<<
<<<.>>>>>+.<<<<<...>---.+++.>>>.<<<---.+++.>>>.<<<<.>---.+++...>>>.<<.
<.>.<<..>>.<.>.<---.+++..>>>>+++.<<<<.>>>>----.<<<<.>>>>+.<<.<<<......
..............>>.>>.<.

Note that this code apparently assumes 8-bit cells; I first tried it on an interpreter with 32-bit cells, and it got stuck at [<---->---] on the first line. (Presumably it would eventually have finished, but I didn't wait long enough for that.)

How the heck did you write this in two hours?

looks like you save ` ')(,/|V_\n on the first cells and them you just go back and forth printing the needed char (BF Dev text generator?). Nice work BTW

It does depend on 8 bit wrapping cells. Stores a few common characters like you said, but not all. Also does things like switches between '' and '_' in one cell where they are close enough to do so.

@JBernardo, BF dev text generator gave code much bigger than this. It would take a much more complicated generator to beat this I think.

Python (2.x), 194 characters
print'eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc'.decode('base64').decode('zip')

This answer just made my day xD. I would have never thought I would see a codegolf that actually uses zip&base64 to decrease string size

This answer is longer than just printing the string; however, just for the fun of it, here it is:
Python, 485 characters ☺
import sys

data= ',C6UBKq.)U^\\ 8[hHl7gfLFyX6,;p\'SlYpN@K-`Kbs#fSU+4o~^_h\\dJDy{o9p?<GnLTgG{?ZM>bJE+"[kHm7EavoGcS#AQ^\\>e_'
table= " _|\\/(\n)V'`,"
key= (0,(1,((((7,5),(6,(8,(11,(9,10))))),(4,3)),2)))

number= 0
for char in data:
    number= number*95 + ord(char) - 32

mask= 1<<655
decoder= key
while mask:
    index= mask & number and 1
    try:
        decoder= decoder[index]
    except TypeError:
        sys.stdout.write(table[decoder])
        decoder= key[index]
    mask>>= 1

Since I have one of the shortest ASCII representations of the compressed original text, I must have the longest scrollbar in my code! It's a win! :)

AKA “my scrollbar is longer than yours”

This solution can be golfed down to 254 characters.  Do you mind if I edit in the shorter version?

@han: Of course the character count can be reduced; however, I didn't write this one as a serious candidate. So let this one be voted for its own merit, and write another answer using as much or as little of this answer as you like :)

Thanks, I'll pass unless someone else is really interested.  I just wanted to point out that this solution can be made significantly shorter than the original text.

Javascript, 273 265 264 characters
" _2_22_ _2222222226_26_ _10 0 3_0 | 3_2 32233_6_ 30 30 |10_0/ _ 4 0/ _ 424 4 /4 / / _ 4| '30/ _` 01|6_6|63/ 0 (_) |24 V6V / (_) 060 (_0_|1|_0_|43_|_543_( )24_/4_/ 43_/56543,_(_)12222226|/".replace(/\d/g,function(a){return'| |,\n,   ,__,\\,|_|,  '.split(',')[a]})

:(

Save the space after the return, -1 char :)

PHP, 194 189 characters
php -r'=gzinflate(base64_decode("dU/BDcQgDPszhX+lUqVs0xeSb5AMf3ZI+7qDACa2EwABeNXR4M/goxqJPUm+oLinEishKTdbKtuMQsTCC6C1EApUInHIvOlP+9zbO6PaTZ6+ynZDEZ1INFuNRu5z+ZVsMHHax1DAibCqZRdVZ/z6esYX"));'

It's basically the same as the Python and Perl answer, slightly shorter

The php -r'=...' trick doesn't seem to work for me, but you could just use <?=... for 184 chars.  Also, your output seems to have an extra space where the r and l meet.

OSX 5.3.6 works fine with the -r'=..'. does the php -r not count? It's included in my 189chars...

Generally, the name of the interpreter doesn't count.  For command line options, I've been going by this meta thread; PHP's -r switch is something of a borderline case, though, since, besides just taking code as a parameter and running it, it also modifies the parsing environment slightly compared to running the code from a file.  I'd be inclined to count it as 2 extra chars -- which incidentally puts it even with <?.

In other languages: C (original version), 209 chars; Perl, 200 chars.

J, 167 160 chars (47 + 113)
Another no-builtin-compression submission. Uses a pretty straightforward variable-length encoding, encoding each character as a series of 1 bits and separating characters by 0 bits. The compressed string is a mere 113 characters.
('a _|\/',CR,'()V`,'''){~#;.2,(6$2)#:40-~3&u:'8H1(((((H:f[4ZS4ZP2(RPMAMANf[>CZD[F;I[OVFF;TgfS5aGd[7T9JW4[eG[+Of7ddg?d[.AfT]WUASE=S>bSdgI]cS[RWBYSE?gSeG_X(()WG('

Python (2.7.x), 218 characters
import base64,zlib;
print zlib.decompress(base64.b64decode("eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc"))

Pretty straightforward... not terribly pleased with this attempt.

Bash, 199 196 193 characters
base64 -d<<<H4sIAAAAAAAAAz1PQQ6AIAw7S+IfelMTk/3GE0l9CI+3HRPYoHQtAxCAMzduGliMiL0NzElygSz+LiYhLWc1VekzDFU6FoCyIxRIYuBgyd7f5+5eGdnv5OWjbA8UUcRAVbORfBN0v5MFTlw2MhQwEVaV7KYu2tv88IgPjUlb7QoBAAA=|zcat

Close enough...
EDIT: Down to 193!

Nice. You could save three more chars by replacing gzip -d with zcat.

Using a where-string would save over echo.

bash, 196 192
base64 -d<<<H4sIAO4SqFMCA3VPQQ7AIAi7+4re5pIl/GYnk+4hPH4U0dOmILUUUBCAPEOBn8Wlao65SW6QudWJSYSUM5sqlQlZJAY2QPiAhSEJx8GSPVWm0TppOa3z1DWqboRZEY7K5pzmMw49kgU6TtXRwiDCpCrZxejTvn7u1l5z59MGKQEAAA|zcat

Perl, 230 characters
use Compress::Zlib;
use MIME::Base64;
print uncompress(decode_base64('eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc'));

This is basically the same as my Python answer. I'd like to see the 199-character version.. sounds like magic.

I won't post it quite yet, but you're on the right track.  Of course, I am/was sort of hoping that someone would beat it with a completely different approach.

Perl, 294 290 bytes.
The compressed string alone, is 151 130 bytes.
This isn't short, but it was really fun to write.
@t=split//,"_|\\/\n()V',`";$b.=substr unpack("B8",chr(-48+ord)),2,6 for split//,'Ph?`@Ooooo1l410````0066600?03l0001PP06600HHB1Q064L4D<8h8^::<DLL4@J0032>1D<90h<>00hHI@6QhYllLX3@`hHI@1Q04P@1Q04@002080R001I^80a074001Q07208P0B0X34ooo`ST';$b=~s/(1)|(0.{4})/$1?" ":$t[ord pack"B8","000$2"]/eg;print$b

@t=split//," _|x"x4 ."\\/\n()V',`";$b.=substr unpack("B8",chr(-48+ord)),2,6 for split//,'4100A0000000001017:8R5HR5@1@05E15R5R;:9Ra4`8\\A<0<30a`<C4C2=URa7PRbP@PG4R<g@P<3D=C4cM288S=RK:HV`EVK1G<d0`LL74`EaV2K1Mg=db0000002ab';$b=~s/1(1.{4})|(..)/$t[ord pack"B8","000".($2?"000$2":$1)]/eg;print$b

Perl, 346 bytes
The compressed string alone, is 111 bytes.
@t = split//, " _|\\/\n()V',`";
$k=[0,[1,[2,[[3,4],[[5,6],[7,[[8,9],[10,11]]]]]]]];

$b .= substr unpack("B8", chr(-48+ord)), 2, 6 for split//,'@P900000PBlc<b[<bX:0ZXUIUIVlcFKZLI^Y`LLMhjjW<oJcMGncNHS5MIW]l`ho3lMNgc<IW]V]i[=KUF]KUG[hL^l^^EMeSFiGmNggP001^Pl';

$d = $k;
$o.=$d=~/^\d/?$t[$s=$d,$d=$$k[$_],$s]:($d=$$d[$_],"")for split//,$b;
print $o

Trying to understand what the python with key= (0,(1,((((7,5),(6,(8,(11,(9,10))))),(4,3)),2)))
was doing, I ended up making a very similar looking perl version.

PHP 590
obviously, i'm not trying to win, just got interested on trying another compression scheme, altough it can't even beat the simpler 302 plain text PHP solution of just copy-pasting
it works as a bitmap on 10 channels
"golfed"
<? $l=['_'=>['l8kqo,ei','9uo6,2fko0','52m0w,5r1c','540lc,5maq','lifeo,19i7ai'],'|'=>[0,'1h39j4,105','1h2k8w,q9x','14l2jk,wlx','1h39j4,wlc','1s,0'],'/'=>[2=>'b9c0,n3kao','pa8,18y68','0,mihog','w,0'],'\\'=>[2=>'pc5,a0zy8','2,0','b9c1,am2kg'],'('=>[3=>'e8,b8lc','1s,4'],')'=>[3=>'3k,2t4w','g,1'],'V'=>[3=>'0,18y680'],'`'=>[2=>'0,g'],"'"=>[2=>'0,6bk'],','=>[4=>'0,g'],];$p=@str_pad;$b=@base_convert;$i=-1;while($i++<5){$h=' ';foreach($l as$c=>$r)if(@$r[$i]){$a=explode(',',$r[$i]);$d=str_split($p($b($a[0],36,2),27,0,0).$p($b($a[1],36,2),27,0,0));foreach($d as$j=>$v)$v&&$h[$j]=$c;}echo"$h\n";}

readable
<?php
$l = ['_'=>['l8kqo,ei','9uo6,2fko0','52m0w,5r1c','540lc,5maq','lifeo,19i7ai'],
      '|'=>[0,'1h39j4,105','1h2k8w,q9x','14l2jk,wlx','1h39j4,wlc','1s,0'],
      '/'=>[2=>'b9c0,n3kao','pa8,18y68','0,mihog','w,0'],
     '\\'=>[2=>'pc5,a0zy8','2,0','b9c1,am2kg'],
      '('=>[3=>'e8,b8lc','1s,4'],
      ')'=>[3=>'3k,2t4w','g,1'],
      'V'=>[3=>'0,18y680'],
      '`'=>[2=>'0,g'],
      "'"=>[2=>'0,6bk'],
      ','=>[4=>'0,g'],
      ];
$p=@str_pad;
$b=@base_convert;
$i=-1;
while($i++<5){
    $h = str_repeat(' ',54);
    foreach($l as $c=>$r)
        if(@$r[$i]){
        $a = explode(',',$r[$i]);
        $d = str_split($p($b($a[0],36,2),27,0,0).$p($b($a[1],36,2),27,0,0));
        foreach($d as$j=>$v)
            if ($v)
                $h[$j]=$c;
        }
    echo "$h\n";
}

Pylongolf2, 300 bytes
" _   _      _ _                             _     _ _
| | | | ___| | | ___    __      _____  _ __| | __| | |
| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |
|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|
|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)
                    |/"~

I couldn't find any classy encoding methods, so I'm probably not competing.

Golf-Basic 84, 325
:"                     "_Str1t` _   _      _ _ "d`Str1d`Str1t`_     _ _"t`| | | | ___| | | ___    __      _____  _ __| | __| | |"t`| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |"t`|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|"t`|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)"t`                    |/"

Assuming a calculator could print backticks, backslashes, single pipes, and underscores.

HTML + JS (223 unicode characters)
Just for fun:
<body onload=p.innerHTML=unescape(escape("").replace(/uD./g,''))><pre id=p>

NB: you have to save it in a "UTF-8 with BOM" HTML file.

Nice. Works for me even without a BOM (Firefox 26 / Chromium 31), as long as encoding is set to UTF-8 or auto-detect. Alas, it doesn't qualify under the stated rules ("program must consist entirely of printable ASCII characters"). :-(

I know, it was just for fun ;)

PowerShell, 220 byes = script:9 + archive:211
tar xOf t

Try it online!
The Powershell script to create the archive t (see TIO):
(
" _   _      _ _                             _     _ _",
"| | | | ___| | | ___    __      _____  _ __| | __| | |",
"| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |",
"|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|",
"|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)",
"                    |/"
) | Set-Content f -Force
tar zcfo t f
Get-ChildItem t # output info about archive size

Isn't the archive non-printable?

Fig, \$274\log_{256}(96)\approx\$ 225.535 bytes
Dr_tem[82]\r-reIX3vb/pBNI9@xbV1?^csytMxrA)YVtY.5yfDryr#(K{bAe,YSkOIU9\|tet&RZF_n+!\;TlNE'T3OB{GGqqvpiP 61;Y#nh0^=vOX6@vxmixkmqp<&y<%;b?=|FG&!6*XI*<glXG,bt|0Kv`/lO;OEx7[`$vT4ljhkSGVaE'</\z{uF8L2E2yXU%r\Ws9F;cF4FXZVD}TL?qdxQ;slDX~lyO# K_+lFV52P-Io9a.7JuDaWJ/sAo,lCChg=5 P9^=[B

Try it online!
Boring text compression answer. Doesn't compress very well due to the compressor being much more optimized for words and spaces before words than characters. Fun fact: when designing Fig, I was considering making the compressor use RLE in the character case, but decided to do capitalization instead :(

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

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


text:
Lose at tic-tac-toe
Write a program that a will play a game of Misère tic-tac-toe. That is, the goal is to force your opponent to take three in a row.
Accept on standard input either an 'X' or an 'O'(the letter, not zero), to determine which side the program will be playing as. Then output a single digit for your move on your turn, and read a single digit on your opponents turn until the game is over (X always goes first). Once a winner is decided, output X or O for who won, or D for a draw. For example, if O gets 3 in a row, X wins.
Assume the board is numbered like so:
0|1|2
-----
3|4|5
-----
6|7|8

Ideally a solution will be optimal and never lose. Like tic-tac-toe, perfect play should always result in a draw. If the above protocol is adhered to, I can test submissions automatically against a variety of possible strategies.
Winner is shortest code. bonus points if it picks randomly from equally good moves to make it a bit more unpredictable.

Python, 383 chars
M=[21,1344,86016,4161,16644,66576,65793,4368]
X=lambda B,k:any(m*k==B&m*3for m in M)
def S(B):
 if X(B,2):return 1,
 M=[i for i in range(0,18,2)if B>>i&3<2]
 return max((-S((B|3<<i)^87381)[0],i)for i in M)if M else(0,)
r='D'
c=ord(raw_input())&1
B=0
for i in range(9):
 if i&1==c:m=S(B^c*87381)[1];print m/2;B|=3-c<<m
 else:
  B|=2+c<<input()*2
  if X(B,2+c):r='XO'[c];break
print r

The board B is represented as an integer using two bits per square, with 00 and 01 representing empty, 10 representing O and 11 representing X.  M is a set of bitmasks with 01 in the spots of a losing triple (21 = 0b010101 = the top row etc.)  X computes if any losing triple for k is present on a board. S does minimax search for an optimal move for X, returning a pair of the score (1=win, -1=lose, 0=draw) and a square index.  ^87381 (=^0b010101010101010101) flips X and O while leaving empty squares unchanged.
The computer never loses, so I didn't need to include that check :) .
There is probably an easier/shorter rule-based algorithm out there, but this works.

Sneaky sneaky bitwise witchcraft +1


text:
Simulate any 1D cellular automaton
The Challenge
You are to write a complete program that takes seven numbers from STDIN, and prints the two dimensional history of the cellular automaton (CA) to STDOUT. This is code golf.
Input Formatting
The input will be seven integers/strings separated by commas. The first number is the number of the rule according to Wolfram code (the standard name for each rule). The second is the initial starting configuration. The third and fourth describe what pattern and how many times it should be appended to the left of the starting config. as padding. The fifth and sixth do the same for the right side. The last number is the number of generations to run the simulation.
So, an example of input is 90,11,0,4,0,4,5. This should tell your program that you are running rule 90. It should also tell the program that you want the initial configuration to be 11 with the string 0 appended 4 times to both ends, so the actual starting pattern is 0000110000. It also tells your program to run this simulation for 5 generations.
Output Your program should print the entire array of cells each generation (separated by newlines), so that the output is the space-time diagram of the CA. For each generation, the state of each cell is determined by its state and the states of the cells to the immediate left and right, in accordance to the rule provided as input. The simulation should wrap around the edges. The first thing printed should be the starting array as gen. 0.
The input 90,11,0,4,0,4,5 should result in the following output as exactly as possible.
0000110000
0001111000
0011001100
0111111110
1100000011
0110000110

Notice that the starting state is not included in the five generations. Also notice that the simulation wraps around the edges.
More Examples
input:
184,1100,01,2,01,1,4

output:
0101110001
1011101000
0111010100
0110101010
0101010101

input:
0,1011,1,0,0,1,2

output:
10110
00000
00000

More information on how 1D CA's work and how they are numbered

Well done for including rule 0 as a test case.

I'm fascinated that rule 90 is a Sierpinski Gasket. Especially since that was part of the testing I did for another Codegolf project.

@JoeFish It was your image that led me to try this one out. I wanted to make an 8086 answer -- kill 2 birds -- but it would probably need string operations, so my emulator wouldn't be able to run it (yet).

Somebody did it already: http://www.pouet.net/prod.php?which=60478

Golfscript, 77 73 70 chars
','/)~\(~:?;~~*@@~*@+\+{1&}/]({[.,{.[3<?256+]{2base}/\~=\(+}*])n@)\+}*

Thanks to @Howard, who pointed out how to save 4 chars.

You can save an obvious one 48- -> 1& and I think also three more. You may omit ) before the block (not increase the counter) and therefore also save the last two pops.

@Howard, thanks. Those pops at the end were useful in an earlier iteration but you're right that eliminating them makes sense now.

APL (153 characters)
∇ cellularautomaton
  i               ← ⍞
  s               ← (i=',') / ⍳ ⍴i
  (b a x c)       ← {i[s[⍵]↓⍳s[⍵+1]-1]} ¨ ⍳4
  (z x x l x r n) ← ⍎i
  y               ← ⍎ ¨ ⊃ ,/ (l / ⊂a) , b , r / ⊂c
  (n+1) (⊃⍴,y) ⍴ '01'[1+⊃ ,/ y,{({(z ⊤⍨ 8/2)[8 - 2⊥¨ 3 ,/ (⊃⌽⍵),⍵,⊃⍵]}⍣⍵)y} ¨ ⍳n]
∇

And in less readable, slightly shorter form:
i←⍞⋄s←(i=',')/⍳⍴i⋄b a x c←{i[s[⍵]↓⍳s[⍵+1]-1]}¨⍳4⋄z x x l x r n←⍎i⋄y←⍎¨⊃,/(l/⊂a),b,r/⊂c⋄'01'[1+⊃,/y,{({(z⊤⍨8/2)[8-2⊥¨3,/(⊃⌽⍵),⍵,⊃⍵]}⍣⍵)y}¨⍳n]⍴⍨(1+n),⊃⍴,y

Example:
      cellularautomaton
26,00110,01,4,10,6,7
0101010100110101010101010
1000000011100000000000001
0100000110010000000000011
0010001101101000000000110
0101011001000100000001101
0000010110101010000011000
0000100100000001000110100
0001011010000010101100010

I'm certain there is room for improvement (I even found a few changes while writing this post!), but some of it could involve fundamental changes, and I can't stand staring at APL any longer. The variant of APL used here is Dyalog APL.

Ruby, 165 159 characters
a=gets.split ?,
b=a.map &:to_i
c=(x=a[2]*b[3]+a[1]+a[4]*b[5]).chars.map &:hex
(0..b[6]).map{puts c*''
c=(1..w=x.size).map{|i|b[0]>>c[i-1]*2+c[i%w]+c[i-2]*4&1}}

Edit: I found some places for small enhancements.
Example run:
> 30,1,0,20,0,20,20
00000000000000000000100000000000000000000
00000000000000000001110000000000000000000
00000000000000000011001000000000000000000
00000000000000000110111100000000000000000
00000000000000001100100010000000000000000
00000000000000011011110111000000000000000
00000000000000110010000100100000000000000
00000000000001101111001111110000000000000
00000000000011001000111000001000000000000
00000000000110111101100100011100000000000
00000000001100100001011110110010000000000
00000000011011110011010000101111000000000
00000000110010001110011001101000100000000
00000001101111011001110111001101110000000
00000011001000010111000100111001001000000
00000110111100110100101111100111111100000
00001100100011100111101000011100000010000
00011011110110011100001100110010000111000
00110010000101110010011011101111001100100
01101111001101001111110010001000111011110
11001000111001111000001111011101100010001

C, 303 305 301 294 292
305 Edit: oops. Forgot that calloc() takes two args. It was blowing up on larger input.
301 Edit: Ah HA! Used my calloc() boo-boo to save 2 more bytes by upping the block size of the requested memory.
294 Edit: Broke 300! Eliminated one of the strcat()s and tweaked a few loops. Got to use maximal munch, which is as much fun to say as use.
292 Edit: Didn't need the +2 in memory allocation.
I used luser droog's answer as the base idea, but changed up the wrapping algorithm, as well as a lot of tweaking and factoring out of constants.
r,A,C,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);for(s=calloc(A+++C,9);A--;)strcat(s,A?a:b);for(;C--;)strcat(s,c);p=strdup(s);for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)for(j=C;j--;)p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;}

r,A,C,n,j;
main(){
    char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    for(s=calloc(A+++C,9);A--;)
        strcat(s,A?a:b);
    for(;C--;)
        strcat(s,c);
    p=strdup(s);
    for(C=strlen(s);A++<n;puts(s),t=p,p=s,s=t)
        for(j=C;j--;)
            p[j]=(1<<(s[j?j-1:C-1]*4+s[j]*2+s[(j+1)%C])-336)&r?49:48;
}

You forgot to make it start C,A,! :)

for loads of memory, what about brk()? then p=s+C+1; somewhere.

+1 again for using +++!

Haha! Change all the %[01] to %s ! -9 (... many years later)

@luserdroog this doesn't work because the %s is greedy and eats the commas and other digits, too.

C (487 484 418 with spaces removed)
*Dropped 66 with help from JoeFish*
C,A,r,n,j;main(){char*s,*p,*t,a[9],b[9],c[9];
    scanf("%d,%[01],%[01],%d,%[01],%d,%d",&r,b,a,&A,c,&C,&n);
    s=malloc(strlen(a)*A+strlen(b)+strlen(c)*C+3);*s=0;
    strcat(s,"0");
    for(;A--;)strcat(s,a);
    strcat(s,b);
    for(;C--;)strcat(s,c);
    strcat(s,"0");
    p=malloc((C=strlen(s)-1)+2);
    for(;n--;){
    *s=s[C-1];
    s[C]=0;
    puts(s+1);
    s[C]=s[1];
    for(j=1;s[j+1];j++)
        p[j]=(1<<(s[j-1]-48)*4+(s[j]-48)*2+s[j+1]-48)&r?49:48;
    t=p;p=s;s=t;
    }
    s[C]=0;
    puts(s+1);
}

typescript

josh@Z1 ~
$ !m
make ca
cc     ca.c   -o ca
ca.c:1:1: warning: data definition has no type or storage class
ca.c: In function ‘main’:
ca.c:2:5: warning: incompatible implicit declaration of built-in function ‘scanf’
ca.c:3:7: warning: incompatible implicit declaration of built-in function ‘malloc’
ca.c:3:14: warning: incompatible implicit declaration of built-in function ‘strlen’
ca.c:4:5: warning: incompatible implicit declaration of built-in function ‘strcat’

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ca
-bash: ca: command not found

josh@Z1 ~
$ echo 90,11,0,4,0,4,5 | ./ca
0000110000
0001111000
0011001100
0111111110
1100000011
0110000110

Nice. You can shave quite a few bytes by making your int variables global and removing the #include:  r,A,B,C,n,i,j; main(){char *s...

Save a bunch in your for loops: for(;A--;)strcat(s,a);

And re-use A and C later so you don't have to declare i or B at all. p=malloc((C=strlen(s))+1);     --C;     strcpy(p,s);     for(A=0;A<n;A++){ Sorry, I'll stop now :)

Ok, I lied, one more. Get rid of 2 byes by eliminating --C;: p=malloc((C=strlen(s)-1)+2);. I think golfing code is more fun than coming up with it in the first place!

I wasn't sure about removing the #include since scanf is variadic. But it's probably ok since it's only called once. ... My old machine died yesterday, and I'm still installing Cygwin. I'll incorporate those changes as soon as I can test it. Thanks!

+1 for leaving in command not found :)

It's the very first thing I compiled on my new Cygwin install. :)

Vyxal 67 59
□÷bṅṅṘ‟:L∇∇~≤[$_⋏ð\0øV|$_Ẏ]$($₀Sf$~Ŀ,$_‟:₌ht∇++3lvB~İṅ$_^„)

There is extra feature: replacement "10" symbols to any Unicode characters.
Many thanks to @lyxal
Try it online!
Input:

List of replacement symbols
Width
Height (number of iterations)
Initial string
Wolfram CA-code

Explanations


text:
Hello World Rainbow
Dealing with colors in non-markup languages often complicates things.
I would like to see some variations of how color is used in different languages.
The object of this competition is to output 'Hello World' in the seven colors of the rainbow.
According to Wikipedia, these are the 7 colors.
Red      #FF0000 (RGB: 255, 0, 0)
Orange   #FF7F00 (RGB: 255, 127, 0)
Yellow   #FFFF00 (RGB: 255, 255, 0)
Green    #00FF00 (RGB: 0, 255, 0)
Blue     #0000FF (RGB: 0, 0, 255)
Indigo   #6600FF (RGB: 111, 0, 255)
Violet   #8B00FF (RGB: 143, 0, 255)

The rules

The program must output 'Hello World'. (Doesn't necessarily need to be text, but it must be distiguishable as 'Hello World')
Each letter must be a different color.
The colors can be in any order.
You must use each of the seven colors at least once. (You may use more than the given colors)
No use of markup languages in any case.

The winner is whoever has the lowest amount of characters AND follows the rules
Bonus -1 character if it is written in DART
I will pick the winner on Jan 11 (if I remember ;D).
Good luck
WINNER(s)
I made a mistake D:, updated winners.
1st.
stranac - Python, 60 chars
2nd.
Ilmari - Karonen Perl + GD, 146 chars
Shortest length with all rules adhered to.
Brownie points to JiminP for the DART answer.

Python, 60 chars
Now using 7 colors, and the "correct" ones.
Uses ansi escape sequences. The underscore is there just so it's not an invisible space.
This version prints some extra spaces, because of the way python's print works, but those spaces save quite a few chars, so I'm fine with them being there.
for p in zip(range(7)*2,'Hello_World'):print'\033[3%im%s'%p,

And a screenshot, as required by MrZander:

Have I made an error?
Please post a screenshot proving that you used all colors properly.
"8 Colors from black to white" doesn't sound like it used the 7 required colors.

@MrZander: I have updated my answer, and hope it now pleases you. Btw, are you sure the 6th color you provided is correct? It is pretty much the same as the 7th.

Took it straight off Wikipedia... I'm no color expert haha.

This relies on a custom palette to work. For example, the H is printed using the escape code for black, so it's not visible on most terminals.

Mathematica
ImageMultiply[ColorNegate[Graphics[Text[Style["Hello World",30]],ImageSize->190]],ColorData["Rainbow","Image"]]

I know, I know, it doesn't comply with the rules.. but I had to try playing with Mathematica's image processing functions.
Screenshot:

Haskell, 88 characters
f(c,n)=putStr$"\27["++show n++"m"++[c]
main=mapM_ f$zip"Hello World\n"$35:cycle[31..36]

Note that this uses ANSI terminal colors, of which there are only 6 and they might not match the exact ones given (it depends on terminal settings), so I'm bending the rules a little here.
Slightly longer version with almost correct colors, 107 characters
This version uses xterm colors instead of ANSI ones. This does not rely on any custom palettes, and uses the closest colors I could find in the 256-color xterm palette.
f(c,n)=putStr$"\27[38;5;"++show n++"m"++[c]
main=mapM_ f$zip"Hello World\n"$cycle[196,208,226,46,21,57,93]

Perl -> ANSI terminal, 53 chars
s//Hello World/;s/./\e[3${[5,(1..6)x2]}[pos]m$&/g;say

This produces the exact same output as Hammar's Haskell solution.  It uses say, so needs perl 5.10+ and the -M5.010 (or -E) switch.  For older perls, replace say with print.  A trivial one-character reduction could be achieved by replacing \e with a literal ESC character, but that would make the code much harder to read and edit.
Edit: Added two chars to match Hammar's output exactly, and to actually show all six possible terminal colors.  (In the earlier version, the only character printed in color 6 = cyan was the space.)
Screenshot:

Edit 2: If using a custom terminal palette (and an underscore for the space) is allowed, then I can easily reproduce the exact colors given in the spec with just 50 chars:
$_=Hello_World;s/./\e[3${[(0..6)x2]}[pos]m$&/g;say

Screenshot:

Try it online! (Includes a 1-byte saving for literal Esc!

Python, 261 chars
C=((255,0,0),(255,127,0),(255,255,0),(0,255,0),(0,0,255),(111,0,255),(143,0,255))
print'P3 67 5 255'
for i in range(335):print'%d %d %d'%(C+C[2:])[i%67/6]if 0x4f7c938a00e7df7d12208a8aa0220820a34413d154044105f7e8828a28808820828cf04f39100e0417d1>>i&1 else'0 0 0'

Implements the spec exactly, generating a ppm image.  Here is the result, converted to gif and scaled up by a factor of 4:

Hehe, nice. Took me an embarrassingly long moment to understand.

n=255;C=((n,0,0),(n,127,0),(n,n,0),(0,n,0),(0,0,n),(111,0,n),(143,0,n))

Perl -> HTML, 99 chars
@c=(("00")x5,77,(ff)x5,77)x2;print"$_"for split//,"Hello World"

Screenshot:

The HTML probably won't pass any validators, but should be understood by just about all browsers.
This code doesn't produce the exact RGB colors you listed, but it does get very close.  Specifically, the colors of the letters are:
H  Red           #FF0000
e  Orange        #FF7700
l  Yellow        #FFFF00
l  Chartreuse    #77FF00
o  Green         #00FF00
  (Spring green  #00FF77)
W  Cyan          #00FFFF
o  Sky blue      #0077FF
r  Blue          #0000FF
l  Indigo        #7700FF
d  Violet        #FF00FF

The output looks a lot nicer on a black background, but explicitly printing a  would've cost me 28 extra characters.  You may adjust your browser settings to achieve the same effect instead. :-)

I may not have been specific enough with rule 5.
I didn't want to see markup used in conjunction with another language either.
But in any case, very creative code.

Perl + GD, 146 chars
Per the comments to my other answer, here's a solution that directly produces an image file using the GD library:
use GD'Simple;move{$m=new GD'Simple 70,12}2,12;s//Hello World/;s/./fgcolor$m(((0)x5,127,(255)x5,127)x2)[$i+8,$i+4,$i++];string$m$&/eg;print$m->png

And here's the output:

Again, using a black background would look better, but would cost me 29 characters ($m->bgcolor(0,0,0);$m->clear;).
Edit: Figured out how to shave off 20 chars by (ab)using indirect object notation and a few other tweaks.  The new code emits a warning, but still runs fine.

That's more like it ;)

So far, this is the lowest character count that follows all the rules to the dot.

Some cheating but solve the problem
Bash + Ruby (needs lolcat gem)
echo Hello World | lolcat -p 0.25

Postscript 155 143
This relies on Ghostscript's ability to "figure-out" that Palatino is short for Palatino-Roman.
/h{c 1 1 sethsbcolor}def/c 0 def
200 400 moveto/Palatino 36 selectfont
h{32 ne{/c c .14 add dup 1 gt{1 sub}if def}if pop
h}(Hello World!)kshow

I suppose "Times" is shorter, but ... ugh.

Stole some of your ideas...

Some different approaches to doing this with
PostScript
First: Shortest one (89):
9 9 moveto/Courier 9 selectfont
0{pop pop
dup 1 1 sethsbcolor
.07 add}( Hello World)kshow

Un-golfed:
9 9 moveto
/Courier 9 selectfont
0                       % hue
{                       % hue c1 c2
  pop pop               % hue
  dup 1 1 sethsbcolor   % hue
  .07 add               % newHue
}( Hello World)kshow

This is continuously changing colour in x direction using the hsb color space. (Idea to use hsb colors and kshow are credited to luser droog - see his entry!) It does  not use the exact seven colors given by MrZander.
When restricting myself to MrZander's colors, I get there using 141 chars:
9 9 moveto/Courier 9 selectfont(H e*l4l4oI  WIosrsl{d~)dup
0 2 20{2 copy
1 add get 32 sub 166 div 1 1 sethsbcolor
1 getinterval show
dup}for

This encodes the hue value of MrZander's colors as one byte in the printable ASCII range. This byte is translated to a hue value in the range between 0 and 1 by subtracting 32 and dividing by 166. Each character of the "Hello World" string is followed by its encoded hue value.
Un-golfed:
9 9 moveto
/Courier 9 selectfont
(H e*l4l4oI  WIosrsl{d~)dup     % string string
0 2 20{                         % string string index
  2 copy                        % string string index string index
  1 add get                     % string string index hueChar
  32 sub 166 div                % string string index hueValue
  1 1 sethsbcolor               % string string index
  1 getinterval                 % string substring
  show                          % string
  dup                           % string string
}for

TODO: Something isn't quite right with the colors.

Bash, 81 bytes
s="Hello World";for((i=0;i<11;i++));do printf "\e[$((RANDOM%9+31))m${s:i:1}";done

Try it online!

Welcome to Code Golf! What language is this?

Hi @RydwolfPrograms This is bash. Sorry I should've mentioned it

Thanks for the feedback @TheThonnu.  I just updated the answer.

@ValentinBajrami sorry, I didn't actually read the challenge before posting that comment. Since TIO doesn't support colours, the link is sort of useless, so you don't actually need it. Still a good first answer anyway.

It doesn't look like this uses the colours specified in the challenge.

Dart to HTML, 135 134-1 = 133
main(){for(var s="Hello World",i=0;i<11;print("${s[i++]}"));}
Is there any way to color texts without using markup language? I can't test canvases...

Oooo... +1 even with the HTML

I know it says "no markup in any case", but I'd like to submit this CSS one in 468 characters:
<s></s>

None of the styling is done with the markup.

Japt, 64 bytes
Ol`HÁM Wld`Ëici%Ã$,...$BÇg`ff7fo8Þ»èç36nãr`qÍ ro0 i`¬l:#

Test it (open your browser's console)
Or, for the benefit of those on devices without browser consoles:

Mfw you can’t open the console on an iPad

Added a screenshot, @Jacob

Ruby
242 more procedural way:
require 'paint'

s = "HelloWorld"
out = ""
[
  '#FF0000',
  '#FF7F00',
  '#FFFF00',
  '#00FF00',
  "#00FFFF",
  "#5555FF",
  '#0000FF',
  '#000077',
  '#6600FF',
  '#8B00FF'
].each_with_index { |c, i| out << "#{Paint[s[i], c.dup]}" }
puts out

If i manage to think of a better way to generate the colours i will. A  few of the middle ones i just did some trial and error for getting the colours close.


text:
determine longest group of consecutive numbers
INPUT:

10 random numbers
each number is greater than 0 and less than 100
list of numbers is presorted, lowest to highest
the list will not contain any duplicate numbers

CHALLENGE:
Write a function that would take in the numbers, and return the count of the longest group of consecutive numbers.
EXAMPLE OUTPUT:
1 2 33 44 55 66 77 88 90 98 => return of the function would be 2
1 3 23 24 30 48 49 70 75 80 => return of the function would be 2
6 9 50 51 52 72 81 83 90 92 => return of the function would be 3

APL, 26 21 characters
1+⌈/+/^\9 9⍴0,1=-2-/⎕

Here's the 26-character solution:
i←⎕⋄⌈/{1++/^\⍵↓1=-2-/i}¨⍳9

I used Dyalog APL as my interpreter, and ⎕IO should be set to 0 for the 26-character version.
Example:
      1+⌈/+/^\9 9⍴0,1=-2-/⎕
⎕:
      6 7 51 51 53 51 54 55 56 55
3

This answer explains most of what I in the 26-character solution, but I might have to write a new one up for the 21-character version.

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

Haskell, 54
import List
f=maximum.map length.group.zipWith(-)[1..]

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

@user unknown: what challenge is it, then?

Ask Bromide. I didn't came up with it.

@user unknown: he was already asked; he declined to answer.  In the meantime, this is an algorithm question with no scoring criterion; there's no reason why I shouldn't restrict myself to short answers in my answer.  I'd upvote yours as well if you gave an explicit reason to.

Well - I don't want to discuss this with 10 different persons in the comments, so I started this thread on meta. Would it mind you, to repeat your argument there? I'm not interested in your particular answer here, but in the general case. See how others count their code size too. I guess a lot just repeat what they see, and believe it is a CG.

GolfScript, 23 characters
~]1\{.@-(!@*).@}*;]$)p;

Test cases:
"1 2 33 44 55 66 77 88 98"  --> 2
"1 3 23 24 30 48 49 70 80"  --> 2
"6 9 50 51 52 72 81 83 92"  --> 3

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

@user unknown: When arguing that against a GolfScript submission, you ought to make it clear that you're complaining about the explicit character count, not the language.

@JB: I thought it is clear from the meta thread.

Jelly, 5 bytes
_JŒɠṀ

Try it online!
_J          Subtract [1,2,3…] from the input.
            This will turn a run like [48,49,50] into something like [45,45,45].
  Œɠ        Get group lengths. (“aaaabbc” → [4,2,1])
    Ṁ       Maximum.

Python
new:
def s(q):
    i = r = 1
    l = -1
    for n in q:
        if n == l + 1:
            i += 1
        elif i > r:
            r,i = i,1
        else:
            i=1
        l=n
 return i if i > r else r

old (buggy):
def s(q):
 i=r=1;l=-1
 for n in q:
  if n==l+1:i+=1
  elif i>r:r,i=i,1
  l=n
 return r

test case:
x = [1,2,3,50,56,58,60,61,90,100]
print x
print s(x)
>>> 3

edit: forgot the input numbers had to be in order. fixed
edit2: fixed a problem when all the numbers are a sequence, eg 1,2,3,4,5,6,7,8,9,10, and it returned just '1'
edit3: oops, didn't realize it wasn't code golf.

Try using x = [1,2,3,4,5,6,7,8,9,10] the result will be 1. Basically if the very last digit is part of a consecutive group it will return the wrong count.

@bromide thanks, fixed now

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

J, 23
>:>./(+*[)/\.(}.=>:&}:)

Sample use:
   >:>./(+*[)/\.(}.=>:&}:) 1 2 33 44 55 66 77 88 98
2
   >:>./(+*[)/\.(}.=>:&}:) 1 3 23 24 30 48 49 70 80
2
   >:>./(+*[)/\.(}.=>:&}:) 6 9 50 51 52 72 81 83 92
3

Python, 79 characters
f=lambda l:max(map(len,''.join(' x'[a-b==1]for a,b in zip(l[1:],l)).split()))+1

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

@userunknown: Indeed it's not.  However, it is such a trivial boring question that is much more fun to treat as code golf, and so I did so.

Mathematica, 50 31 bytes
Max[Length/@Split[#,#2-#==1&]]&

This is an anonymous function. You can either give it a name, by assigning it to something, or you can just append @{6, 9, 50, 51, 52, 72, 81, 83, 90, 92} to use it straight away.
Here is how it works:
#2-#==1& is a nested anonymous function, which takes two arguments and returns True if the arguments are consecutive integers (and False for other integer pairs).
Split then partitions the resulting array into runs of elements, for which the above function returns True.
Now we map Length onto the result to figure out how many numbers each run contains, and select the maximum.
Thanks to David Carraher for eliminating large parts by using a test function in Split!

You can save 19 chars by eliminating RotateLeft and Cases: Max[Length/@Split[#,#2-#==1&]]&

@DavidCarraher Sweet! Thanks... I always forget that Split takes a test function.

Scheme/Racket
Here's a trivial answer in Scheme...
(define f
  (λ (l)
    (letrec ((g (λ (l M c p)
                  (cond ((null? l)
                         (max M c))
                        ((= (car l) (+ p 1))
                         (g (cdr l) M (+ c 1) (car l)))
                      (else (g (cdr l) (max M c) 1 (car l)))))))
      (g l 1 1 -2))))

(f '(1 2 33 44 55 66 77 88 98)) ;=> 2
(f '(1 3 23 24 30 48 49 70 80)) ;=> 2
(f '(6 9 50 51 52 72 81 83 92)) ;=> 3

where

l is the list
M is the Maximum consecutive number count found so far
c is the current consecutive number count
p is the previous number in the list

Ruby
I'm generally not that great at knowing more efficient methods. Might be some ruby standard lib things I'm missing.
def consec_count(arr)
  tg = 1
  cg = 1
  l = arr[0]
  arr.each do |v|
    if l + 1 == v
      cg += 1
      tg = cg if tg < cg
    else
      cg = 1
    end
    l = v
  end
  tg
end

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

JavaScript (80 93 107)
for(n=prompt(c=m=1).split(' '),i=9;i;m=++c>m?c:m)c*=!(--n[i]-n[--i])|0;alert(m);

Demo: http://jsfiddle.net/QqfY4/3/
Edit 1: Replaced a with n[i] and b with n[i-1]. Converted Math.max to ternary if.  Moved initialization statement into for(.
Edit 2: Reversed iteration direction to eliminate need for i++ by changing to --i in second n[--i].  Replaced i++ with part of if body.  Changed condition to i to take advantage of ending at 0 = false.  Hard-code starting value of 9 due to spec 10 random numbers.

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

I am seeing this more, I don't think Its a problem. We are learning how to program.

Python, 87 characters
Recursive solution:
def s(l):
 n=1
 while n<len(l)and l[n]-l[0]==n:n+=1
 return max(n,s(l[n:])if l else 0)

Testing:
>>> s([1, 2, 33, 44, 55, 66, 77, 88, 98])
2
>>> s([1, 3, 23, 24, 30, 48, 49, 70, 80])
2
>>> s([6, 9, 50, 51, 52, 72, 81, 83, 92])
3

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

Since I can't edit code, I'll redefine the Scheme answer (Racket or not, portable and easier to read). Variables have descriptive names and there is only one recursion of the list while being error free (i think). Who cares about characters when you got efficiency?
(define (count-consecutive lst)
  (call-with-current-continuation
    (lambda (return)
      (define (test n)
        (unless (integer? n)
          (return (error "Not integer: " n))))
      (define (g best) (f best n (cdr lst)))
      (let ([prev (car lst)] [count 0]) (test prev)
        (let f ([best 0] [prev prev]
                [lst (cdr lst)])
          (if (null? lst) best
              (let ([n (car lst)]) (test n)
                (if (= (- n prev) 1)
                    (let ([count (+ count 1)])
                      (if (> count best) (g count)
                          (g best)))
                    (let ([count 0])
                      (g best))))))))))

Scala
def maxconsec(ln:List[Int]):Int=
{
    var (max,current,last)=(1,1,-1)
    for(n<-ln)
    {
        if(n==last+1)
        {
            current+=1;
            if(current>max)max=current
        }
        else
        {
            current=1
        }
        last=n
    }
    return max
}

I think this is O(n); is it possible to be more efficient? Can the OP elaborate on how efficiency is being measured here?
Usage: (you can test it on simplyscala.com)
maxconsec(List(6,9,50,51,52,72,81,83,90,92))

Python
def s(n):
l=0
t=1
for i in range(0,9):
    if n[i]+1==n[i+1]:
        t+=1
    else:
        if l<t:
            l=t
        t=1
return l

It's not a golf challenge. Please visit this meta thread: http://meta.codegolf.stackexchange.com/q/456/373

R, 34 bytes
u=rle(1:99%in%scan());max(u$l*u$v)

Try it online!
This is a copy-paste of Micky T's answer to this challenge. Upvote him!

05AB1E, 7 6 bytes
∞-γ€gZ

Try it online!
Thanks to @Kevin Cruijssen for -1 byte
Code:
∞       push endless list [1, 2, 3, 4, 5, ...]
-       subtract that from input
γ       group by equal elements
€g      push lengths of each group
Z       push max length
        implicitly print top of stack

6 bytes (∞ instead of TL). PS: M is the max number on the entire stack, whereas à and Z are the max number in the list (where à pops the list itself; and Z does not pop the list).

Python 3, 73 bytes
def f(l):s=[n-i for i,n in enumerate(l)];return max(s.count(i)for i in s)

Try it online!
This works by subtracting the index from each number in the list and finding the greatest frequency in the list.

-6 bytes by using max(map(s.count,s). TIO. Could save another by using Python 2 and print instead of return

Husk, 7 bytes
▲mLgz-N

Try it online!
Explanation
▲mLgz-N
    z N  zip input and infinite list [1..]
      -  with '-'
   g     group adjacent equal values
 mL      map length
▲        maximum

Java
public static int getConsecutiveCount(int[] A) {
    int r = 1, t = 1;
    boolean c = false;
    for (int i = 0; i < A.length; i++) {
        if (i + 1 < A.length) {
            if (A[i + 1] - A[i] == 1) {
                    t++;
                    c = true;
            } else {
                c = false;
            }
        } else {
            c = false;
        }
        if (t > r && !c) {
            r = t;
            t = 1;
        }
    }
    return r;
}

Just for fun, CJam, 24 bytes
l~]M\{:H(=+H}*;0a/:,$W=)

I know this is not valid as the language did not exist at the time of asking the question, but I thought I will give it a try.
How it works:
l~]M\                     "Read the input, convert to array, put an empty array M before it";
     {      }*            "For each pair of the array, run the code block";
      :H(                 "Assign the second number from the pair to H and decrement it";
         =+               "Check if it is equal to previous number and put result in M";
           H              "Put back the second number so as to be used in next iteration":
              ;0a         "Drop the trailing last number and put [0] on stack";
                 /        "Split M on [0]";
                  :,      "For each split element, replace it with its length";
                    $W=   "Sort the final array and take its last element";
                       )  "Increment this highest element from the array";

Try it online here

Perl
my @o = (1,4,4,6,7,45,46,47,48,98);

sub r{
    $c=1;
    $l=pop@_;
    $m=1;
    while($n=pop@_){
        if($l-$n==1){++$c;$m=$c if $c>$m}
        else{$c=1}
        $l=$n
    }
    $m
}

print "MAX: " . r(@o);

Output:
MAX: 4

Julia 0.6, 55 bytes
a->((d=diff(a))[d.!=1]=x=0;maximum(x=(x+y)y for y=d)+1)

Try it online!
Going for \$ O(n) \$,
82 bytes
a->(l=m=0;i=1;while i<length(a);a[i]==a[i+1]-1 ? l+=1 : l=1;l>m&&(m=l);i+=1;end;m)

Try it online!
which ungolfed is:
function f(a)
    l = m = 0
    i = 1
    while i < length(a)
        a[i] == a[i+1]-1 ? l+=1 : l=1
        if l > m
          m = l
        end
        i += 1
    end
    return m
end

Japt, 9 bytes
äa è_¥1ÃÄ

Try it online!

è¥1  saves a byte. However, this approach will fail if the input contains more than 1 run of consecutive numbers.

Japt -h, 9 bytes
í- ò¦ mÊn

Try it

Factor, 45 bytes
[ [ - -1 = ] monotonic-split longest length ]

Try it online!

R, 30 bytes
x=scan();max(rle(x-seq(!x))$l)

Try it online!
Approach boringly copied from other answers, but different from (and slightly shorter than) JayCe's earlier R answer.

authors: Justin ᚅᚔᚈᚄᚒᚔ


text:
Generate the Stack Overflow logo
The challenge is to generate an image similar to the StackOverflow logo:

The output must contain:

Image size 64*64 or greater
A gray |__| shaped base
A curved segmented stack coming up from the base. The segments will fade from gray to orange, and make a ~90 degree right turn. The number of segments should be between 5 and 7, with 6 being preferred.

Note: For ascii displays that lack color, use a '0' character to represent gray, and '9' for orange. '1' to '8' would represent the shades in-between.
Restrictions:

You must generate the image. Loading images or storing them in the code/binary is not allowed.

Additional rules/information:

The image is not required to be identical to the logo, however it must be recognizable as it.
The method of display is up to you. Saving it to an image file or displaying on the screen are both acceptable.

Judging/winning criteria:

Accuracy of the image is the primary condition
Elegance of generation is the secondary condition

The official 16x16 px version of the logo actually has only 4 bars in the stack.

I'm not sure what it was like in 2012, but by today's standards this is not an objective winning criterion. I guess the best fix (which also wouldn't affect the winner), would be to turn this into a [tag:popularity-contest] and move the judging criteria to voting guidelines.

@IlmariKaronen I count SIX. Also, that's 32x32px.

@mbomb007: It looked different back in 2012.

Mathematica
Graphics[{
   Gray, Rectangle[{0, 0}, {78, 50}],
   White, Rectangle[{9, 9}, {69, 50}]}
  ~Join~
  Table[{
    Blend[{Gray, Orange}, x/5],
    Rotate[
     Translate[
      Rectangle[{16, 16}, {61, 25}],
      {0.25x^3 + 0.6x^2 - 0.4x, -0.53x^3 + 3.26x^2 + 12x}],
     -0.05x^2 - 0.04x]},
   {x, 0, 5}]]

I decided to prettify my answer after realizing this isn't code golf. Whoops!
Screenshot:

In related news, I also created what I think the Stack Overflow logo might look like in... THE FUTURE:

Here's the code if anyone wants to play around with it (sorry for the mess):
Graphics3D[{EdgeForm[],
   Opacity[1],
   RGBColor[0.2, 0.2, 0.2], Cuboid[{0, 0, 0}, {78, 4, 50}],
   Cuboid[{0, 4, 0}, {4, 45, 50}],
    Cuboid[{74, 4, 0}, {78, 45, 50}],
   Opacity[1]}
  ~Join~
  Fold[Join, {},
   Table[{Hue[0.15 - i/5/12, i/3, 1],
     Translate[
      Rotate[
       Scale[Cuboid[{16, 16, 16}, {61, 25, 25}], {1, .3, .3}],
       (-.05 ((i*2 - 1.5)*1.25)^2 - .04 ((i*2)*1.2)), {0.3,
        0.8, -1}, {(16 + 61)/2, (16 + 25)/2, (16 + 25)/2}],
      {-((i*2)^2 - (i*2)*4)/2, (i*2)^2*3/2, 0}]},
    {i, 0, 4.5, 0.05}]], Lighting -> "Neutral", Axes -> False,
 Background -> White, Boxed -> False]

Awesome, but the proportion sheet - box would look better, imho, with a smaller box with less thick border.

Very nice! This community could use your skills ;-) http://mathematica.stackexchange.com/

Hehe Out[404]

Javascript (650)
I wrote a quine that reads the characters in the function, and replaces non-space characters with a number from 0-9.
(function a(){
l=[
                   1,
                    1,
            11,      1,
             11,     1,
               11,    1,
       11,      11,   1,
         11,      11,
           11,
   11,       1111,
     1111,
0,       11111111, 0,
0, 11,             0,
0,   111111111111, 0,
0,                 0,
0, 11111111111111, 0,
0,                 0,
000000000000000000000]

b=a.toString().split("[")[1].split("]")[0].split(""),i=-1
document.getElementById("output").innerHTML=
b.map(function(c){
++i
if(c==" "||c=="\n")return c
if(c!=0)c=9-Math.floor((i/b.length)*10)
if(b[i-1]=="0")c=0
return""+c+""
}).join("")
})()

This outputs this ASCII art:
                   99
                    88
            888      88
             777     77
               766    66
       666      666   66
         555      555
           555
   444       44444
     44444
00       333333333 00
00 333             00
00   2222222222222 00
00                 00
00 111111111111111 00
00                 00
000000000000000000000

which can be colored with a css stylesheet if you like
  span{
    font-weight: bold;
  }
  .c0, .c1{
    color: #222;
  }
  .c2{
    color: #765;
  }
  .c3{
    color: #976;
  }
  .c4{
    color: #A64;
  }
  .c6, .c5{
    color: #D51;
  }
  .c8, .c9, .c7{
    color: #F60;
  }

You can see it in action on jsBin.
Here is a screenshot, in case the link dies:

SVG (347 characters)
Based on Sir_Lagsalot's version, with strokes instead of fills.  Besides shaving off a few chars, the code is simpler and the output looks better scaled up.
<svg width="66" height="85" xmlns="http://www.w3.org/2000/svg">
<g stroke-width="7" fill="none">
<path stroke="gray" d="m4,50v31h49V50M12,69h33"/>
<path stroke="#a86" d="m12,57 33,3"/>
<path stroke="#b95" d="m14,42 32,9"/>
<path stroke="#c82" d="m22,24 27,19"/>
<path stroke="#e80" d="m37,9 18,27"/>
<path stroke="#f71" d="m58,1 4,32"/>
</g></svg>

Link to SVG image.
Rendered to PNG (at natural size and scaled up x2 and x3):

Edit: Finally got around to fixing the off-by-one error that caused the sides of the box not to line up.  Also tweaked the line thickness and end point placement a bit, and added explicit width and height to avoid the bottom and right edges being cropped too tight.  It now looks a lot closer to the official logo.

Haskell w/Gloss
import Graphics.Gloss

picture = translate 0 (-50) $ pictures [stack, base 150 60 20]

stack = translate 0 30 $ pictures [item n | n <- [0..5]]

item n = bend 200 (-10*n) $ color (fade grey orange (n/5)) box
  where box = rectangleSolid 110 20

base width height thickness = color grey $ pictures [left, right, bottom]
  where bottom = rectangleSolid width thickness
        left = translate (width / 2) (height / 2) side
        right = translate (-width / 2) (height / 2) side

        side = rectangleSolid thickness (height + thickness)

bend radius angle = translate radius 0 . rotate angle . translate (-radius) 0

fade from to alpha = mixColors (1-alpha) alpha from to

grey = greyN 0.5

Paste the code here to see it in action, or add the following line to compile it (requires Gloss).
main = display (InWindow "Stack Overflow" (512, 512) (10, 10)) white picture

SVG (333 characters)
I've created a SVG image that generates a 67x68 version of the logo in 333 characters:
<svg xmlns="http://www.w3.org/2000/svg">
<path fill="grey" d="m0,53v34h53V53h-5v29H5V53M9,69h33v6H11v-6"/>
<path fill="#a86" d="m12,56 31,3-1,6-31-3"/>
<path fill="#b95" d="m15,41 31,9-2,6-31-8"/>
<path fill="#c82" d="m22,25 28,17-3,5-28-17"/>
<path fill="#e80" d="m38,8 19,27-5,4-19-27"/>
<path fill="#f71" d="m62,0 5,32-6,1-5-32"/>
</svg>

Link for small SVG image
Link for large SVG image

I wonder if using stroked paths wouldn't be even shorter.

LaTeX
Using the TikZ and PGF packages.
\documentclass{minimal}
\usepackage{tikz}
\pagestyle{empty}
\begin{document}
\xdefinecolor{col1}{RGB}{167, 149, 116}
\xdefinecolor{col2}{RGB}{189, 153, 87}
\xdefinecolor{col3}{RGB}{211, 157, 57}
\xdefinecolor{col4}{RGB}{233, 161, 28}
\xdefinecolor{col5}{RGB}{255, 165, 0}
\begin{tikzpicture}
\draw[gray, fill=gray] (-1,0.5) -- (-1,0) -- (0,0) -- (0,0.5) -- (-0.1,0.5) -- (-0.1,0.1) -- (-0.9,0.1) -- (-0.9,0.5) -- (-1,0.5);
\draw[gray, fill=gray] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col1, fill=col1, xshift=0.3pt, yshift=3pt,  rotate around={-15:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col2, fill=col2, xshift=0.5pt, yshift=6pt,  rotate around={-30:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col3, fill=col3, xshift=0.8pt, yshift=9pt,  rotate around={-45:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col4, fill=col4, xshift=1.3pt, yshift=12pt, rotate around={-60:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\draw[col5, fill=col5, xshift=2.1pt, yshift=14pt, rotate around={-75:(0.2,0.2)}] (-0.8,0.3) rectangle(-0.2,0.2);
\end{tikzpicture}
\end{document}

CSS+JavaScript (HTML div based)
* { padding: 0; margin: 0; }

div { position: absolute; width: 100px; height: 20px; background-color: red; }
.s { background-color: gray; }
#d0,#d2 { width: 20px; height: 70px; }
#d0 { left: 20px; top: 160px; }
#d1 { left: 20px; top: 230px; width: 160px; }
#d2 { left: 160px; top: 160px; }

.e { -moz-transform-origin: 200% center; -ms-transform-origin: 200% center; -o-transform-origin: 200% center; -webkit-transform-origin: 200% center; transform-origin: 200% center; }

$(document).ready(function() {
    for (var i = 0; i < 9; i++)
        $('body').append($('
').attr('id', 'd' + i).attr('class', i < 3 ? 's' : 'e'))

    $('.e').each(function(i) {
        $(this).css({
            left: (50 - i * 3) + 'px',
            top: '200px',
            backgroundColor: '#' + (i + 10).toString(16) + 'a' + (10 - i * 2).toString(16),
            '-moz-transform': 'rotate(' + (i * 15) + 'deg)',
            '-ms-transform': 'rotate(' + (i * 15) + 'deg)',
            '-o-transform': 'rotate(' + (i * 15) + 'deg)',
            '-webkit-transform': 'rotate(' + (i * 15) + 'deg)',
            transform: 'rotate(' + (i * 15) + 'deg)'
        });
    });
});

Sample run: http://jsfiddle.net/ryzBx/
Sample rendering (Firefox 14):

Javascript (a lot of 814 characters)
window.onload = function() {
                var canvas = document.getElementById("cgCanvas");
                var context = canvas.getContext("2d");
                context.moveTo(60,140);
                context.lineTo(60,190);
                context.moveTo(57.5,190);
                context.lineTo(137.5,190);
                context.moveTo(135,140);
                context.lineTo(135,190);
                context.lineWidth = 5;
                context.strokeStyle = "rgb(94,94,94)";
                context.stroke();
                for(i=0;i<6;i++) {
                    context.beginPath();
                    var b=1;
                    var a=1;
                    if(i==5) {
                        a=3;
                        b=1.3;
                    }
                    else if(i==4)
                        a==2;
                    x=94+i*9;
                    y=94-i*5;
                    z=95-i*19;
                    context.moveTo(122.5+i*i,180-i*15);
                    context.lineTo(72.5+i*i+i*i*b,180-i*15-i*i*i+i*i*a);
                    context.lineWidth = 8;
                    context.strokeStyle = 'rgb('+ x +','+ y +','+ z +')';
                    context.stroke();
                }
            };

It ain't pretty but looks a bit like the SO logo.
Test fiddle here - http://jsfiddle.net/elssar/jcYtg/2/

That can be golfed down quite a bit if you change the name of context to something more simple.

Hey there, I golfed it down a little bit for you, it now is on 749 chars: http://jsfiddle.net/jcYtg/5/ -- I liked this approach! Very nice.

706 now: http://jsfiddle.net/jcYtg/12/ -- wanted to change the repetition of i's or the rgb but only messed it up, so didn't change that part.

(Sorry for the spam, this is the last one, I promise). Minimized: http://jsfiddle.net/jcYtg/13/ 501 chars.

Thanks @Alpha It's going to take some time getting used to golfing the code, most times looking at golfed code makes me want to kill the person who wrote it(sorry). About the approach was basically trial & error as I was too lazy to do the math. Would've been better to use concentric circles or even better concentric ellipses to get the positions of the stacks.

C#/GDI+
I was surprised when I noticed there's no C# answer here. So here's one. This is not an ingenious way of drawing the logo, and is not a short solution either. But gets the required output.

You can check my blog post out to download the full working solution →
http://guganeshan.com/blog/stackoverflow-logo-using-csharp-and-gdi.html
public class SOLogo
{
    private float _rotateValue;
    private float _xValueForTransformation;
    private float _yValueForTransformation;

    int _containerWidth;
    int _containerHeight;
    float _lineThickness;
    int _paddingWithinContainer;
    int _elementStartY;

    public SOLogo(float rotateValue, float xValueForTransformation, float yValueForTransformation)
    {
        // Values used to position and rotate the overflowing elements.
        _rotateValue = rotateValue;
        _xValueForTransformation  = xValueForTransformation;
        _yValueForTransformation = yValueForTransformation;
    }

    public void DrawLogo(Graphics g, int startX, int startY)
    {
        // Backup the current smoothing mode to apply later.
        var SmoothingMoodBackup = g.SmoothingMode;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        // Values for the container box.
        _containerWidth = 94;
        _containerHeight = 61;
        _lineThickness = 11f;
        _paddingWithinContainer = 15;

        // Y value of the position where the 1st overflowing element starts.
        _elementStartY = 0;

        // Starting point of the 'container' - Top point of the line on the left-> |_|
        Point pointContainerLineStart = new Point(startX, startY);

        Point pointContainer1stLineEnd = new Point(pointContainerLineStart.X, pointContainerLineStart.Y); // Start with the previous
        pointContainer1stLineEnd.Offset(0, _containerHeight); // Offset "Y"

        Point pointContainer2ndLineEnd = new Point(pointContainer1stLineEnd.X, pointContainer1stLineEnd.Y); // Start with the previous
        pointContainer2ndLineEnd.Offset(_containerWidth, 0); // Offset "X"

        Point pointContainer3rdLineEnd = new Point(pointContainer2ndLineEnd.X, pointContainer2ndLineEnd.Y); // Start with the previous
        pointContainer3rdLineEnd.Offset(0, 0 - _containerHeight); // Offset "Y" (negative)

        GraphicsPath pathOfBox = new GraphicsPath();
        pathOfBox.AddLine(pointContainerLineStart, pointContainer1stLineEnd); // Left line. Top to bottom
        pathOfBox.AddLine(pointContainer1stLineEnd, pointContainer2ndLineEnd); // Bottom line. Left to right
        pathOfBox.AddLine(pointContainer2ndLineEnd, pointContainer3rdLineEnd); // Right line. Bottom to top

        Pen thickPen = new Pen(Brushes.Gray, _lineThickness);
        Color elementColor = Color.FromKnownColor(KnownColor.Gray);

        // Draw the 'container'
        g.DrawPath(thickPen, pathOfBox);

        // Increase the size of the pen to draw the elements inside the container
        thickPen.Width = _lineThickness += 3;
        // "Y" - position of the 1st element
        _elementStartY = startY + 38;

        // The following section draws the overflowing elements

        Point pointElement1Left = new Point(startX + _paddingWithinContainer, _elementStartY);
        Point pointElement1Right = new Point((startX + _containerWidth) - _paddingWithinContainer, _elementStartY);

        // Six colors of the overflowing elements
        var colors = new Color[] {
            Color.Gray,                 Color.FromArgb(-6911615),   Color.FromArgb(-4417693),
            Color.FromArgb(-2848227),   Color.FromArgb(-554957),    Color.FromArgb(-688847)
        };

        for (int x = 0; x < 6; x++)
        {
            thickPen.Color = colors[x];
            pointElement1Left = new Point(startX + _paddingWithinContainer, _elementStartY);
            pointElement1Right = new Point((startX + _containerWidth) - _paddingWithinContainer, _elementStartY);
            g.DrawLine(thickPen, pointElement1Left, pointElement1Right);
            g.RotateTransform(_rotateValue);
            g.TranslateTransform(_xValueForTransformation, _yValueForTransformation);
        }

        pathOfBox.Dispose();
        thickPen.Dispose();

        // Restore the smoothing mood that was backed up before we started this method.
        g.SmoothingMode = SmoothingMoodBackup;
    }
}

I know I'm super late to the game here, but I was surprised no one did a CSS version of this. This is definitely not a competitive answer when it comes to character count (1,195) but the final product is pretty accurate.
Written in Safari (9.0) and tested in Chrome (45.0.2454.93) and Firefox (40.0.3).

body {
    padding: 100px 40px;
}
.base {
    width: 60px;
    height: 40px;
    border: 8px solid #818286;
    border-top: none;
}
.container {
    bottom: 28px;
    left: 6px;
    position: relative;
}
.line {
    width: 48px;
    height: 10px;
    position: relative;
}
.line:nth-child(1n) {
    background: #ff7a15;
    bottom: 23px;
    left: 45px;
    transform: rotate(80deg)
}
.line:nth-child(2n) {
    background: #ff8907;
    bottom: 25px;
    left: 25px;
    transform: rotate(55deg)
}
.line:nth-child(3n) {
    background: #d48c28;
    bottom: 19px;
    left: 10px;
    transform: rotate(30deg)
}
.line:nth-child(4n) {
    background: #c19653;
    bottom: 12px;
    left: 3px;
    transform: rotate(16deg)
}
.line:nth-child(5n) {
    background: #a78b6e;
    bottom: 5px;
    left: 0;
    transform: rotate(5deg);
}
.line:nth-child(6n) {
    background: #818286;
    bottom: 0;
    left: 0;
    transform: rotate(0deg);
}

JavaScript + jQuery & SVG - 250
$('body').html('<svg><g stroke-width="6" fill="none"$grey" d="m3,51v31h47V53M10,70h33"/$#a86" d="m10,57 33,3"/$#b95" d="m13,42 31,9"/$#c82" d="m20,25 28,17"/$#e80" d="m34,9 19,27"/$#f71" d="m56,1 4,32"/></g></svg>'.replace(/\$/g, '><path stroke="'))

I took Ilmari Karonen's SVG and used JavaScript to replace $s with ><path stroke=" effectively shortening it even with the overhead of JavaScript.

R
Not the prettiest solution but it returns the requested output.
library(grid)
my.palette <- colorRampPalette(c("grey57","orange"))(6)
png("StackOverflow_Logo.png", width=300, height=300)
pushViewport(viewport(x=0.5, y=0.5, w=unit(100, "points"), h=unit(100, "points")))
grid.polygon(x=unit(c(10, 0, 0, 100, 100, 90, 90, 10),"points"),
             y=unit(c(50, 50, 0, 0, 50, 50, 10, 10),"points"),
             default.units="points", gp=gpar(col = "grey57", fill="grey57"))
grid.rect(vp=viewport(x=0.5, y=0.3, w=unit(70, "points"), h=unit(10, "points")),
          gp=gpar(col = "grey57", fill="grey57"))

grid.rect(vp=viewport(x=0.52, y=0.52, w=unit(70, "points"), h=unit(10, "points"), angle=-10),
          gp=gpar(col = my.palette[2], fill=my.palette[2]))

grid.rect(vp=viewport(x=0.58, y=0.78, w=unit(70, "points"), h=unit(10, "points"), angle=-20),
          gp=gpar(col = my.palette[3], fill=my.palette[3]))

grid.rect(vp=viewport(x=0.70, y=1.05, w=unit(70, "points"), h=unit(10, "points"), angle=-35),
          gp=gpar(col = my.palette[4], fill=my.palette[4]))

grid.rect(vp=viewport(x=0.90, y=1.25, w=unit(70, "points"), h=unit(10, "points"), angle=-55),
          gp=gpar(col = my.palette[5], fill=my.palette[5]))

grid.rect(vp=viewport(x=1.15, y=1.38, w=unit(70, "points"), h=unit(10, "points"), angle=-70),
          gp=gpar(col = my.palette[6], fill=my.palette[6]))
dev.off()

PHP w/ GD
<?php
$img = imagecreatetruecolor(67,68);
$white = imagecolorallocate($img,0xff,0xff,0xff);
$grey = imagecolorallocate($img,0x80,0x81,0x85);
$orng1 = imagecolorallocate($img,0xa6,0x8a,0x6e);
$orng2 = imagecolorallocate($img,0xc0,0x95,0x53);
$orng3 = imagecolorallocate($img,0xd3,0x8b,0x28);
$orng4 = imagecolorallocate($img,0xfd,0x88,0x08);
$orng5 = imagecolorallocate($img,0xfe,0x7a,0x15);
imagefilledrectangle($img,0,0,67,68,$white);

//container
imagefilledrectangle($img,7,41,10,65,$grey);
imagefilledrectangle($img,10,61,44,65,$grey);
imagefilledrectangle($img,41,61,44,41,$grey);

// stack levels
imagefilledrectangle($img,14,52,37,56,$grey); //1st level
imagefilledpolygon($img,array(14,42,14,47,37,49,37,44),4,$orng1);
imagefilledpolygon($img,array(16,32,15,36,37,42,38,38),4,$orng2);
imagefilledpolygon($img,array(22,21,20,24,39,35,41,32),4,$orng3);
imagefilledpolygon($img,array(33,10,31,12,43,30,45,28),4,$orng4);
imagefilledpolygon($img,array(45,5,48,5,51,27,48,27),4,$orng5);
header("Content-type: image/png");
imagepng($img);
?>

Example:

Use variable functions: $a = 'imagecolorallocate';$r =  'imagefilledrectangle'; $p = 'imagefilledpolygon'; which allows you to reduce the code substantially: $p(...);$p(...);....

Here is a 700 character gist down from the 1000+ characters here.

Scala

object LogoCanvas extends javax.swing.JPanel {

  import java.awt._

    def viereck (g: Graphics, points: scala.List[(Int, Int)]) = {
      val polygon = new Polygon ()
      points.foreach (p => polygon.addPoint (10 * p._1, 400 - 10 * p._2))
      g.fillPolygon (polygon)
    }

  override def paint (g: Graphics) = {
    g.setColor (Color.GRAY);
    // ablage
    viereck (g, scala.List ((2, 1), (2, 11), (3, 11), (3, 1)))
    viereck (g, scala.List ((2, 1), (2, 2), (23, 2), (23, 1)))
    viereck (g, scala.List ((23, 1), (23, 11), (24, 11), (24, 1)))
    // blaetter flach
    viereck (g, scala.List ((5, 5), (5, 6), (21, 6), (21, 5)))
    viereck (g, scala.List ((5, 9), (5, 10), (21, 10), (21, 9)))
    // blaetter schraeg
    g.setColor (Color.LIGHT_GRAY);
    viereck (g, scala.List ((7, 22), (8, 23), (21, 13), (21, 12)))
    viereck (g, scala.List ((12, 28), (13, 29), (22, 15), (21, 14)))
    // blaetter steil
    g.setColor (Color.ORANGE);
    viereck (g, scala.List ((18, 34), (19, 34), (23, 17), (22, 16)))
    viereck (g, scala.List ((24, 36), (25, 36), (25, 17), (24, 17)))
  }

  import javax.swing._

  def main (args: Array [String]) : Unit = {
    val jf = new JFrame ("Stackoverflow!")
    jf.setSize (350, 520)
    jf.setLocationRelativeTo (null)
    jf.setBackground (Color.BLACK)
    jf.add (LogoCanvas)
    jf.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE)
    jf.setVisible (true)
  }
}

JavaScript

var c=document.getElementById('c'),x=c.getContext('2d'),i=0
c.width=c.height=140
x.scale(5,5)
x.fillStyle="#999"
x.fillRect(3,26,14,2)
x.fillRect(1,18,2,10)
x.fillRect(17,18,2,10)
for(;i<6;){x.fillStyle="#"+"999a96b95c94d93f90".substr(i*3,3)
x.save()
x.translate(i*i/2,22-i*6)
x.rotate(i++/5)
x.fillRect(5,0,10,2)
x.restore()}
<canvas id="c"></canvas>


text:
Show Ulam's spiral
Similar to this but in this one you need to write spiral starting from the center where:

space means composite number
.(dot) means prime number.

Size of the spiral can be given as parameter or on stdin. By size I mean side of square NxN and also N will be always odd.

Doesn't Ulam's spiral usually start with 1 in the middle and spiral outward, instead of spiraling inward?

Yeah, it's late so my brain is out of order.

By size of the spiral do you mean the number to go up to, or the number of spirals?

Also, are there limits on the number that may be input or is it 1 to infinity?

Square NxN and limit to 100000

Also similar to this: http://stackoverflow.com/questions/1805796/code-golf-ulam-spiral

Wow, the J paper linked to in the original post of that question is amazing. 72 characters! ' .'{~1 p:>:|.(,~$/:@(+/\)@(_1&|.@((}:@(2:#>:@i.))#(<:@+:$1:,],_1:,-))))

Python, 219 chars
N=input()
A={0:' '}
d=1j
x=1
for p in range(2,N*N+1):
 A[x]=' .'[all(p%i for i in range(2,p))]
 if abs(x.imag)==abs(x.real):x+=(1-1j)*(d==1);d*=1j
 x+=d
R=range(N)
for y in R:print''.join(A[x-N/2+(N/2-y)*1j]for x in R)

Works for any odd N.  For example:
$ echo 9 | ./ulam.py
    . .
 .     .
. .   .
   . . .
  .  .. .
 . .
.   .
 .   .
.     .

JavaScript (240 202 195 151 characters)
Update: Another much smaller version without function (a lot of credits to @mellamokb):
for(x=3,e=d=f=a>>1,c=2;(x&1?x&2?++e<a-d:--e>d:x&2?++f<a-d-1:--f>d)||++x&3||d--;c
++)for(g=0;g<2*a*a;z[g+=c]=1)z[c]||z.getContext("2d").fillRect(e,f,1,1)

Works with this HTML:
<script>a = 50</script>
<canvas id=z width=50 height=50></canvas>

25x25 example (zoomed in) - 800x800 example
This new version now performs well and outputs the right size (NxN) for any odd a.
Found some small improvements (195 now). Thanks @mellamokb.

Old version:
c=1;i=e=0;b={};for(d=[];c<a*a;){d.push("");for(i+=e+=2;i--;)d[Math.min(e-2,i)]+=
j();d.unshift("");for(i-=e;++i<e;)d[g=Math.max(0,i)]=j()+d[g]}x.innerHTML=d.join
("\n");function j(){if(f=!b[++c])for(h=c*c;h<2*a*a;h+=c)b[h]=1;return f?".":" "}

Currently takes variable a as input and outputs to an element with the id x:
<script>a = 50</script>
<pre id=x>

I used the Sieve of Eratosthenes for prime generation, which works really well. Output is quite slow so far though. Don't expect this to run for huge n yet.

I've used Math.max(0,i) trick in the past before thinking it was clever, but it's actually shorter to use a ternary: d[g=i>0?i:0].  Same with Math.min(e-2,i) which should be rewritten as d[i<e-2?i:e-2].

@mellamokb: My never version doesn't use min or max anymore. But thanks for the tip; it's good to remember these minor optimizations.

This is code-golf, so sacrifice a little performance to gain 3 chars: for(g=0;g<2*a*a;b[g+=c]=1); Likewise, move the whole for outside of the if and you can nix the {} for the if, saving another 2 characters :)

@mellamokb: wow, you're good at this. The second suggestion was even better because it can now be written as b[c]||z.getContext, saving 2 more characters.

Working through some ideas.  I have a few improvements to make, but I figured out this eval(["--f>d","--e>d","++f<a-d-1","++e<a-d"][x%4])||++x%4||d--;.  Basically this replaces all the for(h().. and also changes the condition on the main loop to just d. Then you must define x=0 and subtract 1 from d to begin with since it's no longer in the condition.  Finally, inline h() since it's now only called once, and should be able to save about 10 characters (hopefully) :).  Will update with another idea that might save much more in a bit...

I figured out that if I started x at 3, then ++e runs first so you no longer need e=(..)+1.  Also, then if I move the eval(..) to the front of the calls to h(), d-- gets applied first, so everything is correct again.  However, then with a condition of d it stops one row early... so simply move the entire eval() and make it the condition of the main for loop!  Then we can also move the ++c into the third part of the main for loop if we start c at 2 instead, saving another character.  Here's the final working 163-character solution:

for(x=3,e=d=f=a>>1,c=2,b=[];eval(["--f>d","--e>d","++f<a-d-1","++e<a-d"][x%4])||++x%4||d--;c++)for(g=0;g<2*a*a;b[g+=c]=1)b[c]||z.getContext("2d").fillRect(e,f,1,1)  (http://jsfiddle.net/SZp5v/2/)

@mellamokb: Nice one. This can be shortened even more by replacing the eval by ternary. And I think we can merge the 2 remaining loops, making this the least readable JavaScript code ever. I am working on it ...

that's what code golf is all about :P  love to see the outcome.. i do all JS answers on this site, u can look at some of my other ones.  i'm not satisfied until every last possible optimization is made ^_^

@mellamokb: Cut your version down to 151 chars. I also have this version with only one loop, but it's bigger. But this is great now.

Shaved off 3 more characters by optimizing the inner loop to use multiples of c instead of adding c over and over: for(i=0;a-i++;z[c*i]=1).  Basic idea using index i and multiply by c.  Also now only need to check i<=a instead of g<2*a*a.  To optimize further, I use a-i instead and increment in the condition so that a-i==0 loop iteration is still performed.  I'm also looking into optimizing the movement further by using x/y direction vectors and combining the four movement operations and conditions into a single one...stay tuned! :)

Golfscript - 92 Characters
Based on my answer here:
~.(:S+,:R{S\-:|;R{S-:$|>' .'1/[|$.|]2/@:d|~)$<!^=~:$;:y.*4*$-y-)2d*$y-*+:$,{)$\%!},,2==}%n}%

APL (85)
K[R↑+\(1+M-⍨N×M←⌈N÷2),(2/⍳N)/(2×N)⍴1(-N)¯1N]←K←⍳R←N×N←⎕⋄'. '[1+N N⍴K∊P/⍨P∊P∘.×P←1↓⍳R]

Explanation:

Generating the spiral:

K←⍳R←N×N←⎕: Read N from the user. The array size N×N is stored in R. K is [1..R].
(1+M-⍨N×M←⌈N÷2): The coordinate of the middle field.
(2×N)1(-N)¯1N: the delta coordinates for the next field (i.e. 1 right, up a line (so N fields to the left in a 1-dimensional array), then 1 left, then down a line.
(2/⍳N)/: duplicate the deltas to form an expanding spiral. 2/⍳N is 1 1 2 2 3 3 ... N N, duplicating the deltas by these values gives right up left left down down right right right...
R↑+\: sum these values (giving absolute coordinates) and take the first R.
K[...]←K: assign K to K in the order given above. We now have K in spiral order.

Generating the pattern:

P/⍨P∊P∘.×P←1↓⍳R: more or less the standard APL idiom for generating primes. P is [2..R], P∘.×P is a multiplication table for P. P∘.P therefore contains all composite numbers in the range [1..R]. P/⍨ then selects from P all values present in P∘.×P, giving a list of composite numbers.
1+N N⍴K∊: this selects from K all the composite numbers, giving a binary list in spiral order where there's an 1 if the number is composite. Then add 1 so that composite numbers are 2 and noncomposite (prime) numbers are 1. This is formatted as a N by N table.
'. '[...]: prime numbers (1) become '.' and composites (2) become ' '.

MATL, 13 bytes
UGlYLZp42*cwx

Try it online!
A clockwise outward spiral which starts from the right.
Explanation
    U       % convert char matrix to numeric or to general array / square
    G       % paste from user-input clipboard G
    l       % array of ones
    YL      % Create spiral matrix
    Zp      % is prime / totient function
    42      % number literal
    *       % array product (element-wise, singleton expansion)
    c       % convert to character array
    w       % swap elements in stack
    x       % delete elements
            % (implicit) convert to string and display

Python - 203 Characters
Similar to my answer here:
x=input();y=x-1;w=x+y
A=[];R=range;k,j,s,t=R(4)
for i in R(2,w*w):
 A+=[(x,y)]*all(i%d for d in R(2,i))
 if i==s:j,k=k,-j;s,t=s+t/2,t+1
 x+=j;y+=k
for y in R(w):print"".join(" ."[(x,y)in A]for x in R(w))


text:
compute number of 1 bits in a binary representation of a number
The goal is to write a program that returns number of 1 bits in a given number.
Examples
5      ->  2
1254   ->  6
56465  ->  8

Winner
The winning submission is the code which runs in the minimum time. You can assume that normal int value in your language can handle any number (no matter how large) and computes all the valid operators defined for integer in O(1).
If two pieces of code run in the same time the winner is the one implemented in fewer bytes.
Please provide some explanation how your code is computing the result.

Duplicate: Print the amount of ones in a binary number without using bitwise operators

@gareth: that's not a duplicate, in that question binary operators were not allowed, while in mine you can use them. beside in that question he assumed numbers are small while in mine I assume int is large enough!

Runtime is not a meaningful selection criteria as this is highly dependent on the language used. Are you expecting answers in assembler?

I usually write my own codes in c++, it doesn't really matter which language you are using as while as I can implement the same algorithm in c++.

@Gajet then shouldn't you mention that in the question & add a c++ tag?

@elssar as I said it's not important that your code is written in c++. I can almost convert any code to c++, since CPU can run any code in any language! as I said I just need explanation how some algorithms work.

C/C++
int popcnt(int n)
{
    return __builtin_popcount(n);
}

For some CPUs __builtin_popcount compiles to a single instruction (e.g. POPCNT on x86).
Note: requires gcc or gcc-compatible compiler (e.g. ICC).

Using an 8-bit lookup table in the python shell
>>> tab=[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8]
>>> N=123456789
>>> tab[N>>24]+tab[N>>16&255]+tab[N>>8&255]+tab[N&255]
16

I guess in c++ I can use pointers instead of shifting which makes my code run a bit faster.

Haskell, 9 (+16)
There was a popCount routine added to the Data.Bits module for GHC v7.2.1/v7.4.1 this summer (see tickets concerning the primop and binding).
import Data.Bits
popCount

There is a good arbitrary precision popcount function in the GNU Multiple Precision Arithmetic Library (GMP), which GHC uses by default, but most other serious languages offer bindings to :
Python, 16 (+12)
import gmpy;
gmpy.popcount(...);

Perl, 11 (+22)
use GMP::Mpz qw(:all);
popcount(...);

fastest for 32 bit numbers:
int bitcount(int i){
    i=i&0x55555555 + (i>>1)&0x55555555;
    i=i&0x33333333 + (i>>2)&0x33333333;
    i=i&0x0f0f0f0f + (i>>4)&0x0f0f0f0f;
    i=i&0x00ff00ff + (i>>8)&0x00ff00ff;
    return i&0x0000ffff + (i>>16)&0x0000ffff;
}

for 64 bits:
int bitcount(long i){
    i=i&0x5555555555555555 + (i>>1)&0x5555555555555555;
    i=i&0x3333333333333333 + (i>>2)&0x3333333333333333;
    i=i&0x0f0f0f0f0f0f0f0f + (i>>4)&0x0f0f0f0f0f0f0f0f;
    i=i&0x00ff00ff00ff00ff + (i>>8)&0x00ff00ff00ff00ff;
    i=i&0x0000ffff0000ffff + (i>>16)&0x0000ffff0000ffff;
    return i&0x00000000ffffffff + (i>>32)&0x00000000ffffffff;
}

these are all for C-based languages that define the binary operators (C, C++, C#, D, java, ...) (barring the int long type, translate as needed)
for arbitrary bit sizes:
int bitcount(BigInt i){
    int c=0;
    BigInt _2_pow_64 = BigInt(2).pow(64);
    while(i>0){
       long rem = i.mod(_2_pow_64);//or AND with 0xffffffffffffffff
       c+=bitcount(rem);//as defined above
       i=i.div(_2_pow_64);//or rshift with 64
    }
    return c;
}

BigInt being the class for integers of arbitrary size, and the .div, .pow, .mod being the 'divide by', 'to the power of' and 'remainder of' functions reps.

though I'm not big int part (caused by all div and mod parts), it sure works fast enough for int and long .

@Gajet you can use shift and mask (its dividing and mod by a power of 2) I edited to clarify

I think a lookup table will be faster. For an 8 bit lookup table, you only need 4 lookups and 3 additions to do 32 bit. 16 bit lookup table will be slightly faster but much bigger.

@gnibbler then you get caching issues

Is a 256 byte table really too large for the cache?

@gnibbler cache lines can be as small as 4 words

scala:
@tailrec
def bits (i: Long, sofar: Int): Int = if (i==0) sofar else bits (i >> 1, (1 & i).toInt + sofar)

computes on a 2Ghz single core for about 1.500.000 64bit Long values the number of bits set.
A straight forward recursive method, comparing the last bit, and shifting the number towards zero. The @tailrec is just a hint to the compiler to warn me, if it can't optimize the tail recursive call - it is not necessary, for the optimization to take place.
It's about 10times faster than the simplest method, using the library function:
def f(n:Long)=n.toBinaryString.count(_=='1')

Translating them to c++ might not lead to similar results.

the other answers are much more faster, for example ratchet only computes 18 operations for 64bit integer, while you code need at least 128 operations for same size int.

Yes, I see - 10 M longs/s with bitcount as Javacode on the same machine. Btw.: I count 24 operations for ratchet, not 18.

my bad! by the way java use the same algorithm as gnibbler suggested

Here is rachet freak's submission (the 32-bit version) converted to Scala (thanks RF!):
def num1Bits(x: Int) = {
  var i = x
  i = (i & 0x55555555) + ((i>> 1) & 0x55555555)
  i = (i & 0x33333333) + ((i>> 2) & 0x33333333)
  i = (i & 0x0f0f0f0f) + ((i>> 4) & 0x0f0f0f0f)
  i = (i & 0x00ff00ff) + ((i>> 8) & 0x00ff00ff)
      (i & 0x0000ffff) + ((i>>16) & 0x0000ffff)
}

Three years too late, but welcome to the site!

Erlang
p(N)->p(N,0).
p(0,S)->S;p(N,S)->p(N div 2, S+N rem 2).

The p function divides the number with 2, adds the remainder to S, and calls itself with N/2 (tail) recursively.
While it takes log2(N) steps (division and function call) to calculate the result, it works with arbitrary large numbers.

C, 33 bytes
I just saw the challenge today, but thought of a recursive solution.
B(n){return (n&1)+(n?B(n/2):0);};

Edited to note that I assumed it was a smallest size challenge. The speed is linear to the number of bits required to contain the number. O(N) = k * Log2(N).

30 bytes

Python (72 bytes)
x=bin(int(input()));n=0
for i in x:
    if i=='1':
        n+=1
print(n)

Converts str, to int, to bin, then iterates over the string to count.

Rust
Rust has its built-in popcount function:
(num as u128).count_ones();
It's also worth noting that \$\color{blue}{\text{this function operates in constant time}}\$. That is, regardless of the input value, it always takes the same amount of time to execute. This is because the number of bits in an integer is fixed, so no matter the value, the same number of bits need to be examined.
u128
Try it online!
use std::time::Instant;

fn main() {
    let numbers = vec![5, 1254, 56465];
    let answers = vec![2, 6, 8];

    for (i, &num) in numbers.iter().enumerate() {
        let start = Instant::now();
        let result = (num as u128).count_ones();
        let duration = start.elapsed();

        assert_eq!(result, answers[i], "Failed test for {}", num);
        println!("Number: {}, Ones: {}, Time taken: {:?}", num, result, duration);
    }
}

u256
/src/main.rs
use uint::construct_uint;
use std::time::Instant;

construct_uint! {
    pub struct U256(4);
}

fn count_ones(n: U256) -> u32 {
    n.as_ref().iter().map(|&b| b.count_ones()).sum()
}

fn main() {
    let numbers = vec![
        U256::from(5u64),
        U256::from(1254u64),
        U256::from(56465u64),
        U256::from(18446744073709551615u64),
        U256::from_dec_str("115792089237316195423570985008687907853269984665640564039457584007913129639935").unwrap(),  // 2^256 - 1
    ];

    let answers = vec![2, 6, 8, 64, 256];

    for (i, num) in numbers.iter().enumerate() {
        let start = Instant::now();
        let result = count_ones(num.clone());
        let duration = start.elapsed();

        assert_eq!(result, answers[i], "Failed test for {}", num);
        println!("Number: {}, Ones: {}, Time taken: {:?}", num, result, duration);
    }
}

Cargo.toml
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
uint = "0.9"
# bitvec = "1.0.1"

Build and running
# win10 environment

$ cargo build
$ target\debug\rust_hello.exe

Number: 5, Ones: 2, Time taken: 600ns
Number: 1254, Ones: 6, Time taken: 700ns
Number: 56465, Ones: 8, Time taken: 400ns
Number: 18446744073709551615, Ones: 64, Time taken: 700ns
Number: 115792089237316195423570985008687907853269984665640564039457584007913129639935, Ones: 256, Time taken: 800ns

Mathematica
Mathematica has its built-in function DigitCount.
Try it online!
popCount[n_Integer] := DigitCount[n, 2, 1];
(ans=popCount[115792089237316195423570985008687907853269984665640564039457584007913129639935])//AbsoluteTiming//Print