text:
Design and Solve a Maze [on hold while sandboxing]
Your task is to play the roles of both characters in this scene from Inception. In it, Cobb gives Ariadne a challenge:

You have two minutes to design a maze that takes one minute to solve.

Some liberties will be taken on that description. Most importantly, this challenge is not time-based, rather scores are based on the effectiveness of your mazes and maze-solvers.
I apologize for the many edits to this challenge as we iterate towards an easy and fair format..
Part I: Maze format
All mazes are square. A cell in the maze is represented as a zero-indexed tuple row column.
Walls are represented by two binary strings: one for horizontal walls (which block movement between rows) and vertical walls (vice versa). On an NxN maze, there are Nx(N-1) possible walls of each type. Let's take a 3x3 example where the cells are labelled:
A   B | C
   ---
D | E   F
   ---
G   H | I

all possible vertical walls are: AB BC DE EF GH HI. Translated into a string, the walls shown are 011001 for vertical walls and 010010 for horizontal walls. Also, by "binary string" I mean "the characters '0' and '1'".
The full maze format is a string which contains, in this order:

width
start cell tuple
end cell tuple
horizontal walls
vertical walls

For example, this maze:
   0 1 2 3 4
   _________
0 | |  E|  _|
1 |  _|_|_  |
2 |_ _ _  | |
3 |  _ _  | |
4 |____S|___|
start:(4,2)
end:(0,2)

is formatted to this:
5
4 2
0 2
00001011101110001100
10100110000100010010

Part II: The Architect
The Architect program creates the maze. It must play by the rules and provide a valid maze (one where a solution exists, and the end is not on top of the start).
Input: Two positive integers:
size [random seed]

Where size will be in [15, 50]. You are encouraged to make use of the random seed so that matches can be replayed, although it is not required.
Output: A valid size x size (square) maze using the format described in Part I. "valid" means that a solution exists, and the start cell is not equal to the end cell.
The score of an Architect on a given maze is
   # steps taken to solve
–––––––––––––––––––––––––––––
max(dist(start,end),(# walls))

So architects are rewarded for complex mazes, but penalized for each wall built (this is a substitute for Ariadne's time restriction). The dist() function ensures that a maze with no walls does not get an infinite score. The outside borders of the maze do not contribute to the wall count.
Part III: The Solver
The Solver attempts to solve mazes generated by others' architects. There is a sort of fog-of-war: only walls adjacent to visited cells are included (all others are replaced with '?')
input: the same maze format, but with '?' where walls are unknown, an extra line for the current location, and a comma-separated list of valid choices from this location. (This is a big edit that is meant to make it simpler to write a maze-parsing function)
example (same as the above 5x5 maze after taking one step left)
5
4 2
0 2
???????????????011??
????????????????001?
4 1
4 0,4 2

Which corresponds something like this, where ? is fog:
   0 1 2 3 4
   _________
0 |????E????|
1 |?????????|
2 |?????????|
3 | ?_?_????|
4 |__C_S|_?_|

output: One of the tuples from the list of valid choices
Each Solver's score is the inverse of the Architect's score.
Part IV: King of the Hill
Architects and Solvers are given separate scores, so there could potentially be two winners.
Each pair of architects and solvers will have many chances to outwit each other. Scores will be averaged over all tests and opponents. Contrary to code golf conventions, highest average score wins!
I intend for this to be ongoing, but I can't guarantee continued testing forever! Let's say for now that a winner will be declared in one week.
Part V: Submitting

I maintain veto power over all submissions - cleverness is encouraged, but not if it breaks the competition or my computer! (If I can't tell what your code does, I will probably veto it)
Come up with a name for your Architect/Solver pair. Post your code along with instructions on how to run it.

Coming soon: an updated python test kit for the new format. Big changes happened to allow any language submissions.

Rather than restricting it to python, couldn't you define a maze format to be created/read by contestants? That would probably get more people interested.

I had two reasons to be restrictive: first is to easily and safely automate running matches. Second is to avoid requiring a reading and writing library for each language. I guess if nobody wants to use python I'll have to give up one or both...

I'm currently writing a wrapper that runs a sub program and communicates over stdin/stdout. This way you can use any language you want. Would you allow that?

Absolutely! I was in the middle of rewriting the entire question format. Should I wait?

Feel free to change the question. This would be my first time writing python. I got something small working but it's far from finished.

The solver really needs to know not only the cells already visited, but what the walls were in those cells.

Good point. I'll change the format now.

size range updated to [15-50]

Could you clarify where the start and end are on the example maze please? Above it says (row, column), which means there's a giant dead end beyond the end of the maze. If instead it's (column, row) then the maze looks a lot more "maze-like"! Thanks

@tttppp it was a confusing example because the algorithm used to generate it did nothing to ensure that start and end were actually dead-ends.. Hopefully the new example explains it more clearly!

In the 5x5 example you have the same line for both vertical and horizontal walls, mind to correct?

@TeunPronk That was not smart. Thanks!

@rangu confused me and started to doubt myself :P

why don't you copy it over to the sandbox while you continue iterating over it?

I didn't know that was a thing. I guess I'll put it on hold for now..

I've written a solver in Java. Can I post that?

@CrazyMod I've almost got my architect ready, I could post that for you! I think this question should be opened up again.

@stokastic I'm not the asker, but I'd love to see it anyway :)

@CrazyMod, stokastic: sorry for the delay. My life is hectic at the mmoment. I really do want to run this challenge sometime, and your comments may have inspired the necessary second wind. However, I'm still not happy with the restrictions on the architect. I want to encourage a wider range of effective designs (ie no way to cheat the scoring system). Suggestions are welcome!

I just want to comment that the original quote is wrong: it should be "Can you, in only two minutes, create a maze that is so complicated that it takes another person more than one minute to solve it?"  That is, it will always take less time to solve a maze than to build it.

BuildFun and SolveFun
Well, this took quite a while and I'm not entirely sure if the solver is cheating or not. While it has access to the entire maze all of the time, it only looks at the cell it's in, the walls surrounding it and, if there isn't a wall between them, the cells adjacent to it. If this is against the rules please let me know and I'll try to change it.
Anyway, here's the code:
#Architect function
def BuildFun(size,seed):
   #Initialise grid and ensure inputs are valid
   if size<15:size=15
   if size>50:size=50
   if seed<4:seed=4
   if seed>size:seed=size
   grid=[]
   for x in range(size):
      gridbuilder=[]
      for y in range(size):gridbuilder.append([0,1,1])
      grid.append(gridbuilder)
   coords=[0,0]
   grid[0][0][0]=1
   #Generate maze
   while 1:
      #Choose a preffered direction based on location in grid and seed
      pref=((((coords[0]+coords[1]+2)*int(size/2))%seed)+(seed%(abs(coords[0]-coords[1])+1)))%4
      #Find legal moves
      opt=[]
      if coords[0]>0:opt+=[0] if grid[coords[0]-1][coords[1]][0]==0 else []
      if coords[1]<size-1:opt+=[1] if grid[coords[0]][coords[1]+1][0]==0 else []
      if coords[0]<size-1:opt+=[2] if grid[coords[0]+1][coords[1]][0]==0 else []
      if coords[1]>0:opt+=[3] if grid[coords[0]][coords[1]-1][0]==0 else []
      #There are legal moves
      if len(opt)>0:
         moved=False
         while not moved:
            #Try to move in preffered direction
            if pref in opt:
               if pref==0:
                  coords[0]-=1
                  grid[coords[0]][coords[1]][0]=1
                  grid[coords[0]][coords[1]][2]=0
               elif pref==1:
                  grid[coords[0]][coords[1]][1]=0
                  coords[1]+=1
                  grid[coords[0]][coords[1]][0]=1
               elif pref==2:
                  grid[coords[0]][coords[1]][2]=0
                  coords[0]+=1
                  grid[coords[0]][coords[1]][0]=1
               else:
                  coords[1]-=1
                  grid[coords[0]][coords[1]][0]=1
                  grid[coords[0]][coords[1]][1]=0
               moved=True
            #Change preferred direction if unable to move
            else:
               pref+=1
               if pref==4:pref=0
      #There aren't legal moves
      else:
         moved=False
         #Return to a previously visited location
         if not moved:
            try:
               if grid[coords[0]-1][coords[1]][0]==1 and grid[coords[0]-1][coords[1]][2]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[0]-=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]][coords[1]+1][0]==1 and grid[coords[0]][coords[1]][1]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[1]+=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]+1][coords[1]][0]==1 and grid[coords[0]][coords[1]][2]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[0]+=1
                  moved=True
            except:pass
         if not moved:
            try:
               if grid[coords[0]][coords[1]-1][0]==1 and grid[coords[0]][coords[1]-1][1]==0:
                  grid[coords[0]][coords[1]][0]=2
                  coords[1]-=1
                  moved=True
            except:pass
      #Check if finished
      fin=True
      for x in grid:
         for y in x:
            if y[0]==0:
               fin=False
               break
         if not fin:break
      if fin:break
   for x in grid:
      for y in x:
         y[0]=0
   #Find positions for start and finish such that the route between them is as long as possible
   lsf=[[0,0],[0,0],0]
   for y in range(size):
      for x in range(size):
         #Check all start positions
         lengths=[]
         coords=[[y,x,4,0]]
         while len(coords)>0:
            #Spread tracers out from start to the rest of the maze
            for coord in coords:
               opt=[]
               if coord[0]>0:opt+=[0] if grid[coord[0]-1][coord[1]][2]==0 else []
               opt+=[1] if grid[coord[0]][coord[1]][1]==0 else []
               opt+=[2] if grid[coord[0]][coord[1]][2]==0 else []
               if coord[1]>0:opt+=[3] if grid[coord[0]][coord[1]-1][1]==0 else []
               try:opt.remove(coord[2])
               except:pass
               #Dead end, tracer dies and possible end point is recorded along with length
               if len(opt)==0:
                  lengths.append([coord[0],coord[1],coord[3]])
                  coords.remove(coord)
               else:
                  #Create more tracers at branch points
                  while len(opt)>1:
                     if opt[0]==0:coords.append([coord[0]-1,coord[1],2,coord[3]+1])
                     elif opt[0]==1:coords.append([coord[0],coord[1]+1,3,coord[3]+1])
                     elif opt[0]==2:coords.append([coord[0]+1,coord[1],0,coord[3]+1])
                     else:coords.append([coord[0],coord[1]-1,1,coord[3]+1])
                     del opt[0]
                  if opt[0]==0:
                     coord[0]-=1
                     coord[2]=2
                     coord[3]+=1
                  elif opt[0]==1:
                     coord[1]+=1
                     coord[2]=3
                     coord[3]+=1
                  elif opt[0]==2:
                     coord[0]+=1
                     coord[2]=0
                     coord[3]+=1
                  else:
                     coord[1]-=1
                     coord[2]=1
                     coord[3]+=1
         #Find furthest distance and, if it's longer than the previous one, the start/end positions get updated
         lengths=sorted(lengths,key=lambda x:x[2],reverse=True)
         if lengths[0][2]>lsf[2]:lsf=[[y,x],[lengths[0][0],lengths[0][1]],lengths[0][2]]
   #Find number of walls and output maze
   w=draw(grid,size,lsf[0],lsf[1])
   #Output maze information
   print('Start = '+str(lsf[0]))
   print('End = '+str(lsf[1]))
   print('Distance = '+str(lsf[2]))
   print('Walls = '+str(w))
   print('Score = '+str(float(lsf[2])/float(w))[:5])
   #Convert array grid to binary strings horizontal and vertical
   horizontal=vertical=''
   for y in range(size):
      for x in range(size-1):vertical+=str(grid[y][x][1])
   for y in range(size-1):
      for x in range(size):horizontal+=str(grid[y][x][2])
   #Save maze information to text file for use with SolveFun
   save=open('Maze.txt','w')
   save.write(str(size)+'\n'+str(lsf[0][0])+' '+str(lsf[0][1])+'\n'+str(lsf[1][0])+' '+str(lsf[1][1])+'\n'+horizontal+'\n'+vertical)
   save.close()
#Solver function
def SolveFun():
   try:
      #Get maze information from text file
      save=open('Maze.txt','r')
      data=save.readlines()
      save.close()
      size=int(data[0])
      s=data[1].rsplit(' ')
      start=[int(s[0]),int(s[1])]
      e=data[2].rsplit(' ')
      end=[int(e[0]),int(e[1])]
      horizontal=data[3].rstrip('\n')
      vertical=data[4]
      #Build maze from information
      grid=[]
      for y in range(size):
         grid.append([])
         for x in range(size):
            grid[y].append([0,1,1])
      for y in range(size):
         for x in range(size-1):
            grid[y][x][1]=int(vertical[y*(size-1)+x])
      for y in range(size-1):
          for x in range(size):
            grid[y][x][2]=int(horizontal[y*size+x])
      path=''
      cpath=''
      bs=0
      pos=start[:]
      grid[pos[0]][pos[1]][0]=1
      while pos!=end:
         #Want to move in direction of finish
         if end[0]<pos[0] and pos[0]-end[0]>=abs(pos[1]-end[1]):pref=0
         elif end[1]>pos[1] and end[1]-pos[1]>=abs(pos[0]-end[0]):pref=1
         elif end[0]>pos[0] and end[0]-pos[0]>=abs(pos[1]-end[1]):pref=2
         else:pref=3
         #Find legal moves
         opt=[]
         if pos[0]>0:
            if grid[pos[0]-1][pos[1]][2]==0:opt+=[0]if grid[pos[0]-1][pos[1]][0]==0 else[]
         if pos[1]>0:
            if grid[pos[0]][pos[1]-1][1]==0:opt+=[3]if grid[pos[0]][pos[1]-1][0]==0 else[]
         if grid[pos[0]][pos[1]][2]==0:opt+=[2]if grid[pos[0]+1][pos[1]][0]==0 else[]
         if grid[pos[0]][pos[1]][1]==0:opt+=[1]if grid[pos[0]][pos[1]+1][0]==0 else[]
         if len(opt)>0:
            moved=False
            while not moved:
               #Try to move in preferred direction
               if pref in opt:
                  if pref==0:
                     pos[0]-=1
                     path+='0'
                     cpath+='0'
                  elif pref==1:
                     pos[1]+=1
                     path+='1'
                     cpath+='1'
                  elif pref==2:
                     pos[0]+=1
                     path+='2'
                     cpath+='2'
                  else:
                     pos[1]-=1
                     path+='3'
                     cpath+='3'
                  grid[pos[0]][pos[1]][0]=1
                  moved=True
               #Change preferred direction by 1
               else:
                  pref=(pref+1)%4
         #No legal moves, backtrack
         else:
            bs+=1
            grid[pos[0]][pos[1]][0]=2
            if int(cpath[len(cpath)-1])==0:
               pos[0]+=1
               path+='2'
            elif int(cpath[len(cpath)-1])==1:
               pos[1]-=1
               path+='3'
            elif int(cpath[len(cpath)-1])==2:
               pos[0]-=1
               path+='0'
            else:
               pos[1]+=1
               path+='1'
            cpath=cpath[:len(cpath)-1]
      #Output maze with solution as well as total steps and wasted steps
      draw(grid,size,start,end)
      print('\nPath taken:')
      print(str(len(path))+' steps')
      print(str(bs)+' backsteps')
      print(str(bs*2)+' wasted steps')
   except:print('Could not find maze')
def draw(grid,size,start,end):
   #Build output in string d
   d='   '
   for x in range(size):d+=' '+str(x)[0]
   d+='\n   '
   for x in range(size):d+='  ' if len(str(x))==1 else ' '+str(x)[1]
   d+='\n    '+'_'*(size*2-1)
   w=0
   for y in range(size):
      d+='\n'+str(y)+'  |' if len(str(y))==1 else '\n'+str(y)+' |'
      for x in range(size):
         if grid[y][x][2]:
            if start==[y,x]:d+=UL.S+'S'+UL.E
            elif end==[y,x]:d+=UL.S+'F'+UL.E
            elif grid[y][x][0]==1:d+=UL.S+'*'+UL.E
            else:d+='_'
            w+=1
         else:
            if start==[y,x]:d+='S'
            elif end==[y,x]:d+='F'
            elif grid[y][x][0]==1:d+='*'
            else:d+=' '
         if grid[y][x][1]:
            d+='|'
            w+=1
         else:d+=' '
   #Output maze and return number of walls
   print(d)
   w-=size*2
   return w
#Underlines text
class UL:
   S = '\033[4m'
   E = '\033[0m'

I realise that this is ridiculously long and not particularly easy to read, but I'm lazy so this is how it's staying.
BuildFun
The architect, BuildFun, is a fairly simple maze generating program that will always create a 'perfect' maze (one with no loops and where any two points will always have exactly one path between them). It bases its logic off of the seed input meaning that the mazes generated are pseudo-random with what often appear to be repeating patterns and, with the same seed and size, the same maze will be created.
Once the maze is generated, the program will attempt to maximise the maze's score by searching for the start point and end point that result in the longest path between them. To do this, it runs through every start point, spreads out tracers to find the end point furthest from it, and picks the combination with the longest path.
After this, it draws the maze, counts the walls and outputs the maze's information. This is the start point, end point, distance between them, number of walls and score. It also formats this information into the style described above for size, start and end, horizontal walls and vertical walls and saves this into a text file called Maze.txt for use later.
SolveFun
The solver, SolveFun, uses the text file Maze.txt as the input and works in a very similar way to the architect. For every move, it will choose a direction that it wants to go based on its relative position to the end and then it will look at the walls surrounding it. If a wall is not there, it will check to see if it has been in the cell adjacent to it and, if not, it will be added as  possible option. It will then move in the direction closest to its preferred direction provided it has options. If it doesn't have options, it will backtrack until it does. This continues until it reaches the end.
As it moves, it records the path it is taking in the variable path which is used at the end to output the total number of steps. It also records the amount of times it had to backtrack used to calculate wasted steps at the end. When it reaches the end, it will output the maze with the shortest path from start to end marked on with *s.
How to Run
Due to the method of outputting the maze (which includes underlining certain characters), this has to be run from a command line in the form
python -c 'import filename;filename.BuildFun(Size, Seed)'
and
python -c 'import filename;filename.SolveFun()'
where Size is an integer between 15 and 50 (inclusive) and Seed is an integer between 4 and Size (inclusive).


text:
Solve the Rotation puzzle
On some old Nokia phones, there was a variation of the fifteen puzzle called Rotation. In this variation, instead of sliding one tile at a time, you rotated four tiles at a time in one direction.
In this game, you'd start out with a board like this:
4 9 2
3 5 7
8 1 6

And by rotating the lower-left block twice clockwise and the upper-left block once clockwise, you'd get this:
4 9 2
8 3 7
1 5 6

4 9 2
1 8 7
3 5 6

1 4 2
8 9 7
3 5 6

and the 1 tile would be in the top-left corner where it's supposed to be. Eventually, after a few more moves, you'd end up with:
1 2 3
4 5 6
7 8 9

which is the "original" configuration.
Your task is to build a program that will take as input a 3x3 grid of numbers from 1 to 9 (in any format you choose) and return as output a sequence of moves representing the moves you must take to return the board back to its original configuration (again, in any format you choose). The legal moves are defined as moving the [top/bottom]-[left/right] block of 4 tiles [clockwise/counterclockwise].
Your program must be able to solve all possible 3x3 grids (all permutations are solvable).
The shortest code to do this wins.

...and return as output a sequence of moves representing the moves you must take to return the board back to its original Does this mean "back to 1 2 3\n4 5 6\n7 8 9"? I'm not sure how to read that.

Yes, I mean back to 1 2 3 4 5 6 7 8 9.

I think the second and third board in your example should have the 3 and 5 swapped.

@JoeZ. I'd suggest modifying it to declare that the solution must have a bounded worst case performance.

GolfScript, 39/83 bytes
# Optimized for size:

{.4rand.p.2/+>`{?1420344440`=}+$..$>}do

# Optimized for speed:

6,(7++:t;~{.(1=.@7=9=+4\-rand+..2/+@.@>:s^[3s=0s=2s=4s=1s=]+s|.)9<\t>|}do.$>30764`*

Speed vs size
The size-optimized version randomly chooses clockwise rotations until the desired permutation is achieved. This is sufficient, since a counterclockwise rotation is equivalent to three consecutive clockwise rotations of the same square.
The speed-optimized version does the same, except for the following:

If the number 1 is in the upper left corner, it doesn't rotate the upper left square anymore.
If the number 9 is in the lower right corner, it doesn't rotate the lower right square anymore.
The steps for swapping positions 7 and 8 are hardcoded, so there are two positions that allow the loop to break.

Aside from changing the algorithm, the speed-optimized version achieves the rotation in a straightforward manner, while the size-optimed version uses GolfScript's built-in sort by mapping. It also hardcodes the final state (for comparison) instead of sorting the state in every iteration.
The speed-optimized version requires fewer iterations and every iteration is much faster by itself.
Benchmarks
I have used the following code to randomize the positions of the numbers and perform test runs, uncommenting the line corresponding to the version to be tested:
[{[
    0:c;10,1>{;2 32?rand}$
    #{c):c;.4rand.2/+>`{?1420344440`=}+$..$>}do
    #6,(7++:t;{.(1=.@7=9=+4\-rand+..2/+@.@>:s^[3s=0s=2s=4s=1s=]+s|.)9<\t>|}do.$>30764`*
],c+}\~*]

$.0='Min: '\+puts .-1='Max: '\+puts ..{+}*\,/'Avg: '\+puts .,2/='Med: '\+

The output shows the minimum and maximum number of steps it took to order the numbers, the the average and the median of all runs, as well as the elapsed time in seconds:
$ TIME='\n%e s' time golfscript rotation-test-size.gs <<< 100
Min: 4652
Max: 2187030
Avg: 346668
Med: 216888

21500.10 s
$
$ TIME='\n%e s' time golfscript rotation-test-speed.gs <<< 1000
Min: 26
Max: 23963
Avg: 3036
Med: 2150

202.62 s

On my machine (Intel Core i7-3770), the mean execution time of the size-optimized version was 3.58 minutes. The mean execution time of the speed-optimized version was 0.20 seconds. Thus, the speed-optimized version is approximately 1075 times faster.
The speed-optimized version yields 114 times less rotations. Performing each rotation is 9.4 times slower, which is mainly due to how the state is updated.
I/O
The output consists of 3-bit numbers. The MSB is set for counterclockwise rotations, the middle bit is set for lower squares and the LSB is set for right squares. Thus, 0 (4) is the upper left square, 1 (5) the upper right one, 2 (6) the lower left and 3 (7) the lower right one.
The speed-optimized version prints all rotations on a single line. The size-optimized version prints one rotation per line, followed by the final position of the numbers.
For the speed-optimized version, the input has to yield an array containing the numbers from 1 to 9 when evaluated. For the size-optimized version, the input has to be a string without final newline; it does not get evaluated.
Example runs:
$ echo -n '253169748' | golfscript rotation-size.gs
3
0
123456789
$ golfscript rotation-speed.gs <<< '[5 4 7 1 2 9 3 8 6]'
2210300121312212222212211121122211122221211111122211211222112230764

Size-optimized code
{               #
  .             # Duplicate the state.
  4rand         # Push a randomly chosen integers between 0 and 3.
  .p            # Print that integer.
  .2/+          # Add 1 to it if it is grater than one. Possible results: 0, 1, 3, 4
  >`            # Slice the state at the above index.
  {             # Push a code block doing the following:
    ?           # Get the index of the element of the iteration in the sliced state.
    1420344440` # Push the string "14020344440".
    =           # Retrieve the element at the position of the computed index.
  }+            # Concatenate the code block with the sliced state.
  $             # Sort the state according to the above code block. See below.
  ..$>          # Push two copies of the state, sort the second and compare the arrays.
}do             # If the state is not sorted, repeat the loop.

Updating the state is achieved in the following fashion:
Rotation 2 yields the integer 3 after adding 1. If the state is “123456789”, slicing the state yields “456789”.
Right before executing “$”, the topmost elements of the stack are:
[ 1 2 3 4 5 6 7 8 9 ] { [ 4 5 6 7 8 9 ] ? "1420344440" = }

“$” executes the block once for every element of the array to be sorted, after pushing the element itself.
The index of 1 in “[ 4 5 6 7 8 9 ]” is -1 (not present), so the last element of "1420344440" is pushed. This yields 48, the ASCII code corresponding to the character 0. For 2 and 3, 48 gets pushed as well.
The integers pushed for 4, 5, 6, 7, 8 and 9 are 49, 52, 50, 48, 51 and 52.
After sorting, the first element of the state will be one of the elements yielding 48; the last will be one of those yielding 52. The built-in sort is unstable in general, but I've verified empirically that it is stable in this particular case.
The result is “[ 1 2 3 7 4 6 8 5 9 ]”, which corresponds to a clockwise rotation of the lower left square.
Speed-optimized code
6,(7++:t;       # Save [ 1 2 3 4 5 7 ] in variable “t” and discard it.
~               # Interpret the input string.
{               #
  :s            # Duplicate the current state.
  (1=           # Unshift the first element and push 1 if it is equal to 1 and 0 otherwise.
  .@            # Duplicate the boolean and rotate the unshifted array on top of it.
  7=9=          # Push 1 if the eighth element of “s” is equal to 9 and 0 otherwise.
  +4\-          # Add the booleans and subtract their sum from 4.
  rand          # Push a randomly chosen integers between 0 and the result from above.
  +.            # Add this integer to the first boolean and duplicate it for the output.
  .2/+          # Add 1 to the result if it is grater than one. Possible results: 0, 1, 3, 4
  @.            # Rotate the state on top of the stack and duplicate it.
  @>:s          # Slice the state at the integer from above and save the result in “s”.
  ^             # Compute the symmetric difference of state and sliced state.
  [             # Apply a clockwise rotation to the sliced array:
    3s=         # The fourth element becomes the first.
    0s=         # The first element becomes the second.
    2s=         # The third element remains the same.
    4s=         # The fifth element becomes the fourth.
    1s=         # The second element becomes the fifth.
  ]             # Collect the results into an array.
  +             # Concatenate with array of elements preceding the slice.
  s|            # Perform set union to add the remaining elements of “s”.
  .             # Duplicate the updated state.
  )9<           # Pop the last element; push 0 if it is equal to 9 and 1 otherwise.
  \t            # Swap the popped state on top and push [ 1 2 3 4 5 7 ].
  >             # Push 0 if the state begins with [ 1 2 3 4 5 6 ] and 1 otherwise.
  |             # Take the logical OR of the booleans.
}do             # If the resulting boolean is 1, repeat the loop.
.$              # Duplicate the state and sort it.
>30764`*        # If the state was not sorted, 7 and 8 are swapped, so push "30764".

Observe that the rotations 3, 0, 7, 6 and 4 swap the elements in positions 7 and 8, without altering the positions of the remaining seven elements.

Optimized for speed? It's Golfscript...

@Synthetica: Nevertheless, it's the fastest solution that has been posted so far.

Python with Numpy – 158
from numpy import*
A=input()
while any(A.flat>range(1,10)):i,j,k=random.randint(0,2,3);A[i:i+2,j:j+2]=rot90(A[i:i+2,j:j+2],1+2*k);print"tb"[i]+"lr"[j]+"wc"[k]

Input has to be of the following format:
array([[1,2,5],[4,3,6],[7,8,9]])

Each output line is a move encoded in strings like trw or blc and to be read as follows:

t: top
b: bottom
l: left
r: right
c: clockwise
w: counter-clockwise (widdershins)

This program performs random moves until the target configuration is reached. Under the approximative assumption that every move has an independent probability of 1/9! to hit the target configuration¹, the number of rotations before a solution is exponentially distributed with a mean (i.e., the average number of moves) of 9! ≈ 3.6·10⁵. This is in accordance with a short experiment (20 runs).
¹ 9! being the total number of configurations.

So essentially it tries random moves until it achieves a solution?

Works for me. Although I'd be interested in the expected number of rotations before a solution could be reached.

@JoeZ.: See the edit to my post.

That's awesome.

C++ fewest moves solution -- breadth first (1847 chars.)
After a bit more thought, I think I have this done much more efficiently and more sensibly.  This solution, while it is certainly not winning this golf, is so far the only one that will attempt to find the shortest number of rotations that will solve the board.  So far, it solves every random board I've thrown at it in nine or fewer moves.  It also performs significantly better than my last one and, hopefully, addresses Dennis's comments below.
From the previous solution, the largest change was to move the key history from the board state (BS) into a new class that stores the history at a given depth (DKH).  Any time the application makes a move, it checks the history at that depth and all depths prior to see if it's ever been evaluated, if so, it won't be added to the queue again.  This seems to significantly reduce the storage on the queue (by removing all this history from the board state itself) and therefore reduces pretty much all the stupid pruning I had to do to keep the code from running out of memory.  Plus it runs a lot faster since there is much less to copy onto the queue.
Now, it's a simple breadth first search on the various board states.  Plus, as it turns out, my want to change the key set (currently stored as set of numbers in base-9, each of which are computed by BS::key as the base-9 representation of the board) over to a bitset having 9! bits seems to be needless; though I did find out how to compute a key in the "factorial number system" which could have been used to compute the bit in the bitset to test/toggle.
So, the newest solution is:
#include <iostream>
#include <list>
#include <set>
#include <vector>
using namespace std;
struct BS{
#define LPB(i) for(int*i=b;i-b<9;i++)
struct ROP{int t, d;};
typedef vector<ROP> SV;
typedef unsigned int KEY;
typedef set<KEY> KH;
BS(const int*d){const int*x=d;int*y=b;for(;x-d<9;x++,y++)*y=*x;}
BS(){LPB(i)*i=i-b+1;}
bool solved(){LPB(i)if(i-b+1!=*i)return 0;return 1;}
void rot(int t, int d){return rot((ROP){t,d});}
void rot(ROP r){rotb(r);s.push_back(r);}
bool undo(){if (s.empty())return false;ROP &u=s.back();u.d*=-1;rotb(u);s.pop_back();return true;}
SV &sol(){return s;}
KEY key(){KEY rv=0;LPB(i){rv*=9;rv+=*i-1;}return rv;}
int b[9];
SV s;
void rotb(ROP r){int c=r.t<2?r.t:r.t+1;int bi=(r.d>0?3:4)+c;const int*ri=r.d>0?(const int[]){0,1,4}:(const int[]){1,0,3};for(int i=0;i<3;i++)swap(b[bi],b[c+ri[i]]);}
};
ostream &operator<<(ostream &o, BS::ROP r){static const char *s[]={"tl","tr","bl","br"};o<<s[r.t]<<(r.d<0?"w":"c");return o;}
struct DKH{
~DKH(){for(HV::iterator i=h.begin();i<h.end();++i)if(*i!=NULL)delete *i;}
void add(int d,BS b){h.resize(d+1);if(h[d]==NULL)h[d]=new BS::KH();h[d]->insert(b.key());}
bool exists(BS &b){BS::KEY k=b.key();size_t d=min(b.sol().size(),h.size()-1);do if (h[d]->find(k)!=h[d]->end())return true;while(d--!=0);return false;}
typedef vector<BS::KH *> HV;HV h;
};
static bool solve(BS &b)
{
const BS::ROP v[8]={{0,-1},{0,1},{1,-1},{1,1},{2,-1},{2,1},{3,-1},{3,1}};
DKH h;h.add(0,b);
list<BS> q;q.push_back(b);
while (!q.empty())
{
BS qb=q.front();q.pop_front();
if (qb.solved()){b=qb;return true;}
int d=qb.sol().size()+1;
for (int m=0;m<8;++m){qb.rot(v[m]);if (!h.exists(qb)){h.add(d,qb);q.push_back(qb);}qb.undo();}
}
return false;
}
int main()
{
BS b((const int[]){4,9,2,3,5,7,8,1,6});
if (solve(b)){BS::SV s=b.sol();for(BS::SV::iterator i=s.begin();i!=s.end();++i)cout<<*i<<" ";cout<<endl;}
}

Your code looks like C++ instead of C.

@ace, indeed it is, corrected.

In case anybody else has issues compiling this with g++, I had to change all instances of int[] to const int[] and set the flag -fpermissive.

@Dennis, Sorry about that, I've compiled it with two distinct g++ compilers and neither seemed to mind.  But, I can see how a newer, stricter, version would whine.  Thanks.

Compiles well now and it's a lot faster. Addressing the comment you deleted from the question: There are some permutations that seems to require 11 steps. 978654321 is one of them.

@Dennis, thanks for checking.  I wonder if there's a mathematically provable worst case board.  Or, I could just generate all 9! of them and let it run for a while, assuming my code is correct anyway.

I found a C program on this page that solves all permutations. As yours, it requires 11 steps for 978654321. There are no permutations that require 12 or more steps.

@Dennis, looks like they go about it the other direction -- generate all possible permutations of the board keeping track of the moves that got them to that permutation.  Then it's a simple dictionary lookup to find the board.  Humph, lol, it's probably smarter than mine, haha; nice find.

@Dennis, was nice to see the author had similar thoughts on storing the board as a scalar rather than 2D array and rotating it with similar offsets for the corner.

CJam - 39
l{4mr_o_1>+_@m<_[Z0Y4X]\f=\5>+m>__$>}g;

Another random solver :)
It takes a string such as 492357816 and outputs a (long) series of digits from 0 to 3, each representing a clockwise rotation of a block: 0=top-left, 1=top-right, 2=bottom-left, 3=bottom-right.
Brief explanation:
4mr generates a random number from 0 to 3
_1>+ increments the number if it's greater than 1 (so we end up with 0, 1, 3 or 4 - the starting indexes of the 4 blocks)
m< rotates the string to the left (such as 492357816 -> 923578164, not the block rotation) in order to bring the block to rotate in the first position
[Z0Y4X]\f= does the block rotation which affects the first 5 characters, such as 12345 -> 41352;
X=1, Y=2, Z=3 so [Z0Y4X] is actually [3 0 2 4 1] and those are the 0-based indexes of the rotated tiles
5> copies the rest of the string
m> rotates the (modified) string back to the right
__$> checks if the string is sorted (it's the stopping condition)

Mathematica, 104 chars
We can interpret the task in the language of permutation groups. The four rotations are just four permutations that generate the symmetric group S9, and the task is just to write a permutation as a product of the generators. Mathematica has a built-in function to do this.
i={1,2,5,4};GroupElementToWord[PermutationGroup[Cycles/@({i}+#&/@i-1)],Input[]~FindPermutation~Range@9]

Example:
Input:
{4, 9, 2, 8, 3, 7, 1, 5, 6}

Output:
{-2, -3, -4, 2, 4, 1, 4, -1, -2, 3, 2, -4, 3, 4, -3, -3, -4, -4, -2, -2, -3, -2, 3, -1}

1: top-left clockwise
2: top-right clockwise
3: bottom-right clockwise
4: bottom-left clockwise
-1: top-left counterclockwise
-2: top-right counterclockwise
-3: bottom-right counterclockwise
-4: bottom-left counterclockwise

source: Stack Exchange

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

sort: votes


text:
Immutable dictionaries in Haskell
You need to implement immutable dictionaries using only functions without any other data types (custom or built-in).
The dictionary must be indexed by any data type of class Eq and contain values of arbitrary type, but all the values in a dictionary should be of the same type.
Here are some examples of usage:
dict `access` True -- returns value of key True
dict `access` "y"  -- returns value of key "y"
(update "x" 10 dict) `access` "x" -- returns 10 for any dict

This is a site for programming contests, and contests need criteria to select the winners. What makes one correct implementation better than another?

The amount of code is the criteria (less is better).

update key1 value obj = \key2 -> if key2 == key1 then value else obj key2
access = id

Given the above definitions, your examples should work. Also, you can define an empty dictionary as const x where x is the default value for keys not in the dictionary.

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


text:
Count how many characters are in the program's source
Write a program that counts and prints the number of characters in it's own source code to standard output.
The number must be generated from counting the characters.
This Ruby solution would not be allowed:
puts 6

because it is not calculated. Spaces, tabs, new lines, etc should be counted.
The program must be smallest possible in any programming language.

If you post another challenge, I strongly suggest using this template.

My guess, make a program that will count how many characters are used in the programs code, so basicly count the characters in your source and make it as short as possible. Is this really being downvoted for poor english?

I made a winner!  PHP, 1 character:  1

Something like echo 'wc -c $0' > x ; sh x... I think this is a nice question, maybe the rules should be a little more precise...

So is this [tag:code-golf] then?

Whatever tags it should have, it's a rubbish question. It's like making a cheating "quine" without even having the interest of being a quine.

Must it actually read the source code, or is a stat on the source code file good enough ?

The program must be smallest possible in any programming language. The halting problem makes this challenge impossible.

Bash, 10
Pretty boring, but:

Prints the code size in bytes, and nothing else.
Filename may contain spaces.

Make sure that the file doesn't have a new line at the end! If it does, it will output 11.
wc -c<"$0"

If the file doesn't have spaces in its name, you can get 8 characters:
wc -c<$0

since others are specifying the filename, you should be able to count this as 8

Actually, on that note, you could specify it as being named a and just have wc -c<a.

CJam / GolfScript - 11
CJam:
{`"_~"+,}_~

GolfScript:
{`".~"+,}.~

This actually generates its own source code (like a quine) and then calculates the string length.

PYG (9, and actually calculated)
Calculates the length of the source code (Q) with the builtin string length checker len, and prints (P) the result:
P(len(Q))

Nice golfing of Python.

Ruby, 30 22 20 18
p IO.read($0)=~/$/

You could make it a touch shorter by using a regex match to calculate the length: p File.read($0)=~/$/

@Chron thanks, fixed

you could reduce to 18 : p IO.read($0)=~/$/

Even better, 15: p open($0).size

perl, 9 bytes
No trailing newline.
print-s$0

Running it looks like this:
$ echo -n 'print-s$0' >/tmp/foo.pl
$ perl /tmp/foo.pl ; echo
9

-M5.01 is free, so you can reduce this by two bytes by using say instead of print. (Tested on Strawberry 5.20.2.)

BASH (builtins only) - 18
$ cat bash ; echo # no final newline in file
a=`<$0`
echo ${#a}
$ ls -l bash
-rwxr-xr-x 1 yeti yeti 18 18. Mai 07:11 bash
$ ./bash
18

Python 31
Save the file as 'l'
print len(file.read(file('l')))

Outputs 34

Might as well name it l... Saves 3 chars

Fortran 78
character*78::a;open(unit=9,file='c.f90');read(9,'(a78)')a;print*,len(a);end

File IO isn't the best in Fortran, so we have to waste space opening the file & then reading from it. Had I not specified the a78 (78 characters), then it would stop at the comma next to file (silly list-directed IO).

HTML + Javascript (jQuery): 48
Save this script as script.html and open it with a browser.
<script>alert($('body').html().length)</script>

You also need to include any library with a $ function. Otherwise this won't work.

Rebol, 40
print length? read system/options/script

VIM - 43
Add this in your .vimrc file :
:echo strlen(join(readfile(".vimrc")),"\n")

But it will only work if you are in your home when executing vim.
More generic solution vim ~/.vimrc (46 chars) :
:echo strlen(join(readfile(bufname("%")),"\n"))

Your first solution seems to have one too many rightparens.

@Aurel300 yup thx. fixed

PHP - 22
<?=filesize(__FILE__);

Python 3, 28 27 bytes
I got 2̶8̶ 27 characters, plus file name and extension (4 in this case for 'f.py') The minimum value for this is 3̶2̶ 31, if there was a 1 letter file name and the .py exension:
print(len(open("f.py").read()))

EDIT:
The bite count is actually 27 rather than 28, thanks @mbomb007 for pointing that out

The byte count is wrong.

Why not just f?

@NoOneIsHere The program I use to execute the program doesn't run unless the file is a .py file, so it was out of habit that I put that. But, as you say, using f instead of f.py would lower the byte count from 31 to 28 (including the filename)

JavaScript 78
<script id="s">
function f(){document.write(document.getElementById("s").innerHTML.length);}
</script>

You may save 2 chars removing quotes from id="s"

also, the stdout of javascript is alert so you may save lot of chars replacing the document.write

This isn't pure javascript.

J - 16 char
J can read($0) itself too, you know! Not all that well, but...
echo#1!:1]1{ARGV

A more natural solution in the interpreter REPL, in which we do the normal quine thing and then take the length, costs 24 chars:
#(,2#{:),~'#(,2#{:),~'''

,~ appends the string to itself, (,2#{:) appends two copies of the trailing single quote, and # takes the length.

Extended BrainFuck: 12
,(>+<,)>55+.

Usage:
beef ebf.bf < cnt.ebf > cnt.bf
beef cnt.bf < ent.ebf

Output:
C

Which is 12 in hex. If you add a linefeed in the file it will output a D for 13 so it's definitely counting the characters in the source.

I wonder how fun it would be to program in something that adds GolfScript functionality to Extended BF...Makes me tempted to spec out a more fully featured BF derivative that combines a lot of things invented by other BF derivatives (limited networking support, early termination, timing from NetFuck, significant comment syntax and function/macro support from cbrain, multithreading support from Brainfork, etc.) with some things from GolfScript (like variables) and a few additions of mine for utility reasons (modules, anyone?).

@impinball EBF has variables and macros and it would have been difficult to make LISP in it without it. A major design goal of EBF was that it should produce pure BF object code that runs under any BF implementation. Making just an interpeter/compiler that has added primitives like pbrain is IMO cheating. A cleaner approach to get feature like file I/O would be to implement message passing through stdin/stdout so that you could make a program X that implements the protocol that run standard brainfuck interpreter/compiler Y and intercept the I/O.

Just leisurely wondering. I wouldn't add half a million primitives. I was pondering the idea of modular BF that includes some useful other stuff like what EBF and NetFuck has. Make a more useful(ish) BF. I wouldn't use pbrain's comment syntax, because it would be easier to use the more common empty register comment. I still would want to include native file I/O, but not by flooding with primitives.

@impinball EBF is a more useful BF since it provides more primitives front end without demanding it from it's back end. BTW: I have made a joke compiler called BrainBack that is a Forth type language like GolfScript. I wrote the compiler in EBF and it compiles to EBF :)

Ok... Could you reread my comment... I sent it earlier than I intended.

Or maybe I could implement modules, implementing a few in native code, but it only adding two more primitived to EBF: the module import and module export. Modules with optional native ones (both plugin and standard library) could almost make it real world useful. That would probably be best. The one issue will be circular dependencies (my pet project of a JS compiler will teach me how to manage that).

@impinball I've though about these things but I'm leaving it outside of EBF for my Scheme to BF project by specifying a message passing API. eg. my BF program outputs "This needs BF APIv1" and my API implementation intercepts I/O so it answers this. After that you need to opcode your output after the spec. 1 might be "fork" and the first byte read in would then indicate if you are parent or child. 2 + ascii0 file path might be open file and you'll get a file handle on the next byte read. Such a thing can extend BF to support any OS feature without extending the actual language.

@impinball modules import could easily be implemented by the front end and compile it to pure BF or message passing calls. How should it react for unavailable modules? You can send me a link when you got your project up and running as I'd love to see it :)

I haven't really put too much serious thought into it.

Hy (38 characters):
(defmain [n] (print (.read (open n))))

dc - 8
Not sure if this is allowed, but calculates the length of the macro(the part in the square brackets and adds 4(which is the length of the part outside the macro)).
[Z4+p]dx

Lua: 42
print(string.len(io.open('l',"r"):read()))

Pretty straight-forward, you must save the file as l and call it as lua l.

In lua read only is the default, so you can remove the "r". You can use # instead of string.len to make it even shorter.

K,13
1@$#,/0:.z.f;

/
$ q a.k -q
13

Python 3: 33 or 37
print(len(open(__file__).read()))
print(len(open(__file__,'b').read()))

First if you only count the characters, second if you want to count the number of bytes.

JavaScript (Node.js) - 60
console.log(require('fs').readFileSync(__filename).length);

Java, 157 characters
Since nobody has done Java yet...
public class A{public static void main(String[]a) throws Exception{System.out.print(new java.util.Scanner(new java.io.File("A.java")).nextLine().length());}}

Welcome to Programming Puzzles & Code Golf! Answers to code golf challenges here are typically prefixed with a header mentioning the language the code is written in and its amount of characters. I've edited it in for you this time, but it would be great if you could include one in your future code golf solutions. Thanks!

Cause ya know, java.

PHP - 44
Save this as c
<?$f=fopen("c","r");echo strlen(fgets($f));

Why do you store $f? echo strlen(fgets(fopen("c","r")));

<?=strlen(fgets(fopen(c,r)));, 29 bytes: Neither c nor r need quotes; and echo-tag is shorter than echo.

JavaScript
42 - ES5
(function a(){alert((a+"()()").length)})()

37 - ES6
(a=x=>{alert((a+"(a=)()").length)})()

And also, a self invoking function is longer, than actually calling it

Javascript (pure - no HTML nor JQuery) 41 bytes
function f() {alert((f+"f()").length)}f()

Dyalog APL, 8 bytes
The niladic function f:
≢∊⎕NR'f'

Notice that this prints 10 because APL counts (and stores) the function header (name + newline). However, PPCG practice is not to count this header. The entire program can be displayed with
      ↑⎕NR'f'

Giving:
f
≢∊⎕NR'f'

⎕NR'f' the Nested (i.e. a list of character lists) Representation of f
∊ ϵnlist (flatten)
≢ tally

RProgN, 3 bytes.
Q L

Simply, Q is the function that pushes the source code to the stack, and L is the function that gets the length of the string on top of the stack. The stack is then implicitly printed.
Try it online!

awk, 13 bytes
$0=length($0)

Write it to a program file program.awk and
$ awk -f program.awk program.awk
13

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


text:
Output a solid PNG from scratch
Input: An RGBA hex color c (ex. FFFF00FF) and an integer > 0 and < 1000 n (ex. 200).
Output: Raw bytes of a PNG file such that when the output is saved to a file and opened in an image viewer, an n by n image filled with the color c is displayed.
Specification: Your program should output exactly:

a PNG header (89504E470D0A1A0A in hex)
an IHDR chunk containing these specifications:

width: the previous input n
height: the previous input n
bit depth: 8 (RGBA)
color type: 6 (truecolor with alpha)
compression method: 0
filter method: 0
interlace method: 0

one or more IDAT chunks containing the image data (a solid image of color previously input c); may be compressed or uncompressed
an IEND image end chunk

Further details available on Wikipedia, on the W3 site, or via a Google search.
Restrictions:

You may not use any image libraries or functions designed to work with images of any kind.
Your program must run in under 3 minutes and output a file under 10 MB for all inputs (sanity check).
This is code-golf, so the shortest code in bytes will win!

You say that the file may be entirely uncompressed, but then that it must be under 30kB for all inputs. A 999x999 file has more than 30720 pixels, so that seems self-contradictory.

@PeterTaylor Hm, for some reason I thought that 30 KB was more than enough. Don't know what I was thinking... edited. (And I only said that you may or may not use compression; whichever you want.)

Width:              4 bytes
Height:             4 bytes
Bit depth:          1 byte
Color type:         1 byte
Compression method: 1 byte
Filter method:      1 byte
Interlace method:   1 byte

@technosaurus ... um, what?

Almost like cheating: http://mainisusuallyafunction.blogspot.se/2012/04/minimal-encoder-for-uncompressed-pngs.html

Your example isn't correct: bit depth: 8 (RRGGBBAA).  Bit depth 8 is (RGBA) not (RRGGBBAA).

@GlennRanders-Pehrson Ah, thanks. Edited.

Perl, 181
/ /;use String::CRC32;use Compress::Zlib;sub k{$_=pop;pack'Na*N',y///c-4,$_,crc32$_}$_="\x89PNG\r\n\cZ\n".k(IHDR.pack NNCV,$',$',8,6).k(IDAT.compress pack('CH*',0,$`x$')x$').k IEND

Size is 180 bytes and option -p is needed (+1). Score is then 181.
The arguments are given via STDIN in a line, separated by a space,
the color as hex value (16 chars) and the number of pixels for width/height, e.g.:
 echo "FFFF00FF 200" | perl -p solidpng.pl >yellow200.png

The file size is 832 bytes. The maximal sized image (n=999) with the same color has 6834 bytes (way below 10 MB).
The solution uses two libraries:

use Digest::CRC crc32; for the CRC32 values at the chunk ends.
use IO::Compress::Deflate deflate; to compress the image data.

Both libraries are not related to images.
Ungolfed:
# Perl option "-p" adds the following around the program:
#     LINE:
#     while (<>) {
#         ... # the program goes here
#     } continue {
#         print or die "-p destination: $!\n";

/ /;    # match the separator of the arguments in the input line
        # first argument, color in hex:  $`
        # second argument, width/height: $'                              #'

# load the libraries for the CRC32 fields and the data compression
use String::CRC32;
use Compress::Zlib;

# function that generates a PNG chunk:
#   N (4 bytes, big-endian: data length
#   N:                      chunk type
#   a* (binary data):       data
#   N:                      CRC32 of chunk type and data
sub k {
    $_ = pop; # chunk data including chunk type and
              # excluding length and CRC32 fields
    pack 'Na*N',
        y///c - 4,   # chunk length                                      #/
                     # netto length without length, type, and CRC32 fields
        $_,          # chunk type and data
        crc32($_)    # checksum field
}

$_ =                      # $_ is printed by option "-p".
    "\x89PNG\r\n\cZ\n"    # PNG header
        # IHDR chunk: image header with
        #   width, height,
        #   bit depth (8), color type (6),
        #   compresson method (0), filter method (0), interlace method (0)
    . k('IHDR' . pack NNCV, $', $', 8, 6)
        # IDAT chunk: image data
    . k('IDAT' .
          compress        # compress/deflate data
          pack('CH*',     # scan line with filter byte
              0,          # filter byte: None
              ($` x $')   # pixel data for one scan line                 #'`
          ) x $'          # n lines                                      #'
      )
        # IHDR chunk: image end
    . k('IEND');

Edits

use IO::Compress::Deflate':all'; is replaced by use Compress::Zlib;. The latter does export the deflate function compress by default. The function
does not need references as arguments and also returns the
result directly. That allows to get rid of variable $o.

Thanks for Michael's answer:

Function k: A call of pack could be removed by using template Na*N for the first pack in the function.
pack template NNCV with four values optimizes NNC3n with six values.

Thanks for VadimR's comment with lots of tips:

use String::CRC32; is shorter than use Digest::CRC crc32;.
y///c-4 is shorter than -4+y///c.
The scan line is now constructed by the template CH* with the repetition in the value.
Removal of $i by using a value reference.
Bare words instead of strings for the chunk types.
Options now read by matching a STDIN input line (option -p) with matching
the space separator / /. Then the first option is in $` and the second argument goes in $'.
Option -p also automatically prints $_.
"\cZ" is shorter than "\x1a".

Better compression
At the cost of code size the image data can be further compressed, if filtering is applied.

Unfiltered file size for FFFF0FF 200: 832 bytes
Filter Sub (horizontal pixel differences): 560 bytes
$i = (                            # scan line:
         "\1"                     # filter "Sub"
         . pack('H*',$c)          # first pixel in scan line
         . ("\0" x (4 * $n - 4))  # fill rest of line with zeros
      ) x $n;                     # $n scan lines

Filter Sub for the first line and Up for the remaining lines: 590 bytes
$i = # first scan line
     "\1"                     # filter "Sub"
     . pack('H*',$c)          # first pixel in scan line
     . ("\0" x (4 * $n - 4))  # fill rest of line with zeros
     # remaining scan lines
     . (
           "\2"               # filter "Up"
           . "\0" x (4 * $n)  # fill rest of line with zeros
       ) x ($n - 1);

First unfiltered line, then filter Up: 586 bytes
$i = # first scan line
     pack('H*', ("00" . ($c x $n)))  # scan line with filter byte: none
     # remaining scan lines
     . (
           "\2"               # filter "Up"
           . "\0" x (4 * $n)  # fill rest of line with zeros
       ) x ($n - 1);

Also Compress::Zlib can be tuned; the highest compression level can be set by additional option for the compression level in function compress at the cost of two bytes:
compress ..., 9;

File size of example yellow200.png without filtering decreases from 832 bytes to 472 bytes.
Applied to the example with Sub filter, the file size shrinks from 560 bytes to 445 bytes (pngcrush -brute can't compress further).

Great answer (as always), but golfing can go further - I get 202, + 1 for -p. In addition to insights in Michael's answer (NA*N and NNCV templates), - String::CRC32 exports by default, y///c-4 is OK, CH* template, $i be gone, \cZ, barewords are OK, -p and / /; places arguments into prematch and postmatch. I wonder if I missed something and score can get below 200 :)

@VadimR: Many thanks for the useful tips. I could even golf it further by using use Compress::Zlib; and got ≈ 10 % below 200.

PHP 214
I'm not an expert on PHP, there is place for golfing. Tips are welcomed.
<?function c($d){echo pack("Na*N",strlen($d)-4,$d,crc32($d));}echo"\x89PNG\r\n\x1a\n";c("IHDR".pack("NNCV",$n=$argv[1],$n,8,6));c("IDATx^".gzdeflate(str_repeat("\0".str_repeat(hex2bin($argv[2]),$n),$n)));c("IEND");

Generate a PNG file:
php png.php 20 FFFF00FF > output.png

Generate base64 stream (paste the result in your browser address bar)
echo "data:image/png;base64,`php png.php 200 0000FFFF | base64`"

Ungolfed version :
<?php

//function used to create a PNG chunck
function chunck($data) {
  return pack("Na*N", //write a big-endian integer, a string and another integer
    strlen($data)-4,     //size of data minus the 4 char of the type
    $data,               //data
    crc32($data));       //compute CRC of data
}

//png header
echo "\x89PNG\r\n\x1a\n";

//IHDR chunck
echo chunck("IHDR".pack("NNCV", //2 big-endian integer, a single byte and a little-endian integer
                   $n=$argv[1], $n,
                   8, 6)); //6 also write 3 zeros (little endian integer)

//IDAT chunck
//create a binary string of the raw image, each line begin with 0 (none filter)
$d = str_repeat("\0".str_repeat(hex2bin($argv[2]),$n),$n);
echo chunck("IDATx^".
       gzdeflate($d)); //compress raw data

//IEND chunck
echo chunck("IEND");

It's 214 now, isn't it? And, I can get no correct image from both golfed and un-golfed versions, but I have no PHP experience, so if it works for everyone else, it's me doing it wrong.

@VadimR, yes 214, you're right. I've checked, the image generated is valid for me.

For me (I test with PHP 5.4.27.0), image is 4 bytes short - shouldn't adler-32 be appended to deflated data? IE and Chrome are happy to display image as is, FF is not. Different apps behave differently, too, with this image.

Python, 252 bytes
import struct,sys,zlib as Z
P=struct.pack
A=sys.argv
I=lambda i:P(">I",i)
K=lambda d:I(len(d)-4)+d+I(Z.crc32(d)&(2<<31)-1)
j=int(A[2])
print "\x89PNG\r\n\x1A\n"+K("IHDR"+P(">IIBI",j,j,8,6<<24))+K("IDAT"+Z.compress(("\0"+I(int(A[1],16))*j)*j))+K("IEND")

This script takes input from argv. Run this script from command line, like python 27086.py deadbeef 999


text:
Throw a null-pointer exception
Your task is to generate a null-pointer exception. That is, your program must accept a value which it expects to be non-null, and throw an exception/error or crash because the value is null.
Furthermore, it can't be obvious from reading the code that the value is null. Your goal is to make it seem clear to the reader that the value is not null, even though it actually is.

Instead of null, you can use nil, none, nothing, or whatever the equivalent is in your language. You can also use undefined, uninitialized, and so on.
The problem with your code must be that the variable is (surprisingly) null where the program expects a non-null variable.
Your program can respond to the null by throwing an exception, throwing an error, crashing, or whatever it normally does when an unexpected null is encountered.

This is a popularity contest, so be clever!

@Ourous Can you give an example to show what you mean?

After looking over it, It's more of a cast error than what you're looking for.

Am I allowed to use a compiler bug?

@Mark It is a popularity contest; let the community decide. I'd definitely vote for a compiler bug.

I'm closing this question because underhanded contests are off topic per community consensus.

Java
Let's calculate the absolute value of a number. Java has Math.abs for this purpose, however the number we're using could be null sometimes. So we need a helper method to deal with that case:
public class NPE {
    public static Integer abs(final Integer x) {
        return x == null ? x : Math.abs(x);
    }

    public static void main(final String... args) {
        System.out.println(abs(null));
    }
}

If x is null, return null, else use Math.abs().
The code is very simple and clear, and should work fine... right?
By the way, using this line instead:
return x == null ? null : Math.abs(x);

works correctly. I thought about making this a spoiler, but.. I think it's just as puzzling :)
Ok, an explanation:

 First, Math.abs does not take an Integer, but an int (there are also overloaded methods for other numeric types) and also returns an int. In java, int is a primitive type (and can not be null) and Integer is its corresponding class (and can be null). Since java version 5, a conversion between int and Integer is performed automatically when needed. So Math.abs can take x, automatically converted to int, and return an int.

 Now the weird part: when the ternary operator (?:) has to deal with 2 expressions where one has a primitive type and the other one has its corresponding class (such as int and Integer), one would expect that java would convert the primitive to the class (aka "boxing"), especially when the type it needs (here for returning from the method) is the reference (class) type, and the first expression is also of the reference type. But java does exactly the opposite: it converts the reference type to the primitive type (aka "unboxing"). So in our case, it would try to convert x to int, but int can not be null, thus it throws a NPE.

 If you compile this code using Eclipse, you will actually get a warning: "Null pointer access: This expression of type Integer is null but requires auto-unboxing"

 Also see:
https://stackoverflow.com/questions/7811608/java-npe-in-ternary-operator-with-autoboxing
https://stackoverflow.com/questions/12763983/nullpointerexception-through-auto-boxing-behavior-of-java-ternary-operator

Hint: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

SPOILERS What happens when x != null? (I figured it out already.)

@11684 when x is not null, it works fine

Then I think I do not know how this works. If it works when x is not null and I'm right about why this throws, the colon has to be parsed in two senses (which I would not put in a Language Specification).

@11684 not sure what you mean about "two senses", but anyway I added an explanation now

Yes, there's two different cases in which you will need a colon. One is the one displayed here. It's used to separate the bodies of a ternary operator. The second one is in foreach loops.

@IchBinKeinBaum I know that; I'm sorry it's so vague what I meant. My initial idea was that the colon was used as a division operator (auto-unboxing could allow this), but that would corrupt the ternary expression (there would be no expression for the false case). To handle the case x != null (and work like I thought it did) the colon should have been parsed as a division operator (sense one) and as delimiter (separating the last two expressions).

This (and related issues) is one of the main reasons considering ' ? : ' to be just a fancy  'if-else' is a bad idea

@11684 I'm not aware of any programming language that uses ":" for division. Java definitely doesn't.

@aditsu Ha, how stupid. I'm even in the top 30% for the Stackoverflow tag. I'll go home now :'(.

This is absolutely dastardly.  +1.

C
Every C programmer made this error, at least once.
#include <stdio.h>

int main(void) {
    int n=0;
    printf("Type a number : ");
    scanf("%d",n);
    printf("Next number is : %d",n+1);
    return 0;
}

Reason :

 scanf takes a pointer (int *) in argument, here 0 is passed (NULL-pointer)

Fix:

 scanf("%d",&n);

http://ideone.com/MbQhMM

It's not exactly like that. scanf is a variadic function, and argument of incorrect type (int) was given, when it expected int *. Because C (I know, compilers can detect this in case of scanf) cannot check the types in variadic function, this happily compiles. 0 is indeed null pointer literal, but this only applies to the directly used literal itself, without storing it in a variable. n never contained a null pointer.

You also need to check the return value of scanf to fix this function.

@David It's not correct without checking the return value, but it won't crash or invoke UB - n will remain at 0. (To see this happen, try redirecting an empty file as stdin.)

PHP
This one has bitten me a few times.
<?php

class Foo {
  private $bar;

  function init() {
    $this->bar = new Bar();
  }

  function foo() {
    $this->bar->display_greeting(); // Line 11
  }
}

class Bar {
  function display_greeting() {
    echo "Hello, World!";
  }
}

$foo_instance = new Foo();
$foo_instance->init();
$foo_instance->foo();

Expected result:
Hello, World!

Actual result:
Fatal error: Call to a member function display_greeting() on a non-object on line 11

a.k.a. NullPointerException
Reason:

 By default, constructor syntax is backwards compatible with PHP 4.x, and as such, the function foo is a valid constructor for the class Foo, and thus overrides the default empty constructor. This sort of error can be avoided by adding a namespace to your project.

CoffeeScript (on Node.js)
In CoffeeScript, ? is existential operator. If the variable exists, it's used, otherwise right hand side is being used. We all know that it's hard to write portable programs. Case in point, printing in JavaScript is under specified. Browsers use alert (or document.write), SpiderMonkey shell uses print, and Node.js uses console.log. This is crazy, but the CoffeeScript helps with this issue.
# Portable printer of "Hello, world!" for CoffeeScript

printingFunction = alert ? print ? console.log
printingFunction "Hello, world!"

Let's run this under Node.js. After all, we want to make sure our script works.
ReferenceError: print is not defined
  at Object.<anonymous> (printer.coffee:3:1)
  at Object.<anonymous> (printer.coffee:3:1)
  at Module._compile (module.js:456:26)

Uhm, why would you complain about that, when alert is also not defined?

 For some reason, in CoffeeScript, ? is left associative, which means it ignores undefined variables only for the left side. It's unfixed, because apparently some developers may depend on ? being left associative.

Ruby
Find awk in the PATH of a Unix clone.
p = ENV['PATH'].split ':'

# Find an executable in PATH.
def find_exec(name)
  p.find {|d| File.executable? File.join(d, name)}
end

printf "%s is %s\n", 'awk', find_exec('awk')

Oops!
$ ruby21 find-awk.rb
find-awk.rb:5:in `find_exec': undefined method `find' for nil:NilClass (NoMethodError)
        from find-awk.rb:8:in `<main>'

From the error, we know that p.find called nil.find, so p must be nil. How did this happen?
In Ruby, def has its own scope for local variables, and never takes local variables from the outer scope. Thus the assignment p = ENV['PATH'].split ':' is not in scope.
An undefined variable usually causes NameError, but p is a special case. Ruby has a global method named p. So p.find { ... } becomes a method call, like p().find { ... }. When p has no arguments, it returns nil. (Code golfers use p as a shortcut for nil.) Then nil.find { ... } raises NoMethodError.
I fix it by rewriting the program in Python.
import os
import os.path

p = os.environ['PATH'].split(':')

def find_exec(name):
    """Find an executable in PATH."""
    for d in p:
        if os.access(os.path.join(d, name), os.X_OK,
                     effective_ids=True):
            return d
    return None

print("%s is %s" % ('awk', find_exec('awk')))

It works!
$ python3.3 find-awk.py
awk is /usr/bin

I probably want it to print awk is /usr/bin/awk, but that is a different bug.

C#
With() is an extension method to the string object, which is essentially just an alias for string.Format().
using System;

namespace CodeGolf
{
    internal static class Program
    {
        private static void Main()
        {
            Console.WriteLine( "Hello, {0}!".With( "World" ) );
        }

        private static string With( this string format, params object[] args )
        {
            Type str = Type.GetType( "System.string" );
            MethodInfo fmt = str.GetMethod( "Format", new[] { typeof( string ), typeof( object[] ) } );

            return fmt.Invoke( null, new object[] { format, args } ) as string;
        }
    }
}

Looks good, right? Wrong.

 Type.GetType() requires a fully-qualified, case-sensitive type name. The problem is that System.string doesn't exist; string is just an alias for the actual type: System.String. It looks like it should work, but str.GetMethod() will throw the exception because str == null.

Most people who know a bit about the internal specifics of the language will probably be able to spot the problem fairly quickly, but it's still something that's easily missed at a glance.

That is a great one :D

This is a little too obvious. The reader get an immediate clue because there are two ways to do the same thing .GetType() and typeof() and thus leading to a fault when the result is not the same. I think the poster wanted bullet proof looking code which isn't.

Why would reflection be used in this extension method? The obvious code is return string.Format(format, args);. If reflection was needed (in another use case), one would use typeof(string) (catches casing mistakes at compile-time, no magic string), not the static GetType method. So the example seems "unrealistic".

Unity3D
public GameObject asset;

Then you forget to drag&drop the asset there and BOOM, Unity explodes. Happens all the time.

wait, development in unity3d requires a mouse?

@Einacio if you want things easier you can just dragNdrop an asset to a variable. Very handy. But you can code without that if you want to.

Ruby
Just some simple code to take the product of an array.
number_array = [2,3,9,17,8,11,14]
product = 1
for i in 0..number_array.length do
  product *= number_array[i]
end
puts product

 Two things here. One is that the .. range operator is inclusive. So 0..x has x+1 elements and includes x. This means that the we exceed the bounds of the array. The other thing is that when you do this in Ruby, it just gives you a nil back. This is a lot of fun when, say, your program throws an except ten lines after the bug.

This is kindof too obvious. It's like doing for (int i = 0; i <= arr.length; i++) in Java.

Android
I see this happen too often. A person passes a message to the next activity (maybe a status code, map data, whatever), and ends up pulling a null from the Intent.
At first glance it seems pretty reasonable. Just:

make sure the message isn't null
pack it into the intent
start new activity
get intent in new activity
extract message by tag

In MenuActivity.java:
private void startNextActivity(String message){
    // don't pass a null!
    if(message == null)
        message = "not null";

    // put message in bundle with tag "message"
    Bundle msgBundle = new Bundle();
    msgBundle.putString("message", message);

    // pack it into a new intent
    Intent intent = new Intent(this, NextActivity.class);
    intent.putExtras(msgBundle);
    startActivity(intent);
}

In NextActivity.java:
private void handleMessage(){
    // get Intent
    Intent received = getIntent();
    if(received == null){
        Log.d("myAppTag","no intent? how does this even happen?");
        finish();
    }
    // get String with tag "message" we added in other activity
    String message = received.getStringExtra("message");
    if(message.length() > 10){
        Log.d("myAppTag", "my message is too long! abort!");
        finish();
    }
    // handle message here, etc
    // ...
    // too bad we never GET here!
}

FWIW, the JavaDoc does say that Intent.getStringExtra(String) may return null, but only if the tag wasn't found. Clearly I'm using the same tag, so it must be something else...

The problem with this answer is that people not familiar with Android development (such as me) won't be able to appreciate it.

@JanDvorak Agreed, but no big deal. There are other answers on the site that I don't fully appreciate also. :)

C
Just a quick read from the buffer, where the programmer has even been kind enough to document the potential danger!
char* buffer;
int main( void )
{
    ///!!WARNING: User name MUST NOT exceed 1024 characters!!\\\
    buffer = (char*) malloc( 1024 );
    printf("Please Input Your Name:");
    scanf("%s", buffer);
}

 Very simple and obvious trick if you're expecting malicious code. The comment ending '\' escapes the newline, so the buffer is never allocated memory. It will then fail the scanf, as buffer will be NULL (as file scope variables are zero initialised in C).

C++:
#include <iostream>
#include <cstring>
#include <vector>
#include <conio.h>
#include <string>

using namespace std;

class A
{
public:
    string string1;
    A()
    {
        string1 = "Hello World!";
    }
};
A *a_ptr;

void init()
{
    A a1;
    a_ptr = &a1;
}

int main()
{
    init();
    cout<<a_ptr->string1;
    _getch();
    return 0;
}

What you would expect is "Hello World!" to be printed. But you will see only garbage on the screen.
Here the a1 is destroyed when the scope init() is finished. So a_ptr, as it points to a1, will produce garbage.

C
#define ONE 0 + 1

int main(void) {
    printf("1 / 1 = %d\n", 1 / ONE);
    return 0;
}

Explanation

 The preprocessor doesn't actually calculate 0 + 1, so ONE is literally defined as 0 + 1, resulting in 1 / 0 + 1, which is a division by zero, and results in a floating point exception.

Nimrod
type TProc = proc (a, b: int): int

proc func1(a, b: int): int=a+b
proc func2(a, b: int): int=a-b

proc make_func(arg: int, target: var TProc)=
  if arg == 1:
    target = func1
  elif arg == 2:
    target = func2
  else:
    raise newException(EIO, "abc")

var f, f2: TProc

try:
  make_func(2, f)
  make_func(3, f2)
except EIO:
  discard

echo f(1, 2)
echo f2(3, 4)

 What's happening here is a little complicated. In Nimrod, procedures are default initialized to nil. In the first make_func call, it succeeds. The second, however, throws an exception and leaves f2 uninitialized. It is then called, causing an error.

C#
This is classical. The very useful method FindStringRepresentationOf will create a new instance of the specified type parameter, then find the string representation of that instance.
Surely it will be wasteful to check for null immediately after having created a new instance, so I haven't done that...
static void Main()
{
  FindStringRepresentationOf<DateTime>();  // OK, "01/01/0001 00:00:00" or similar
  FindStringRepresentationOf<DateTime?>(); // Bang!
}

static string FindStringRepresentationOf<TNewable>() where TNewable : new()
{
  object goodInstance = new TNewable();
  return goodInstance.ToString();
}

 Changing object in the local variable declaration into TNewable
 or into var (C# 3 and later) makes the problem go away. Hint:
 Boxing of Nullable<T> (a.k.a. T?) is anomalous in the .NET Framework.

After having fixed the issue as described in the invisible text above, aslo try goodInstance.GetType() (the difference being that GetType(), unlike ToString(), is non-virtual, so they could not override it in the type Nullable<>).


text:
Steampunk: Clacker animation
In the highly underrated Steampunk novel The Difference Engine, the equivalent of cinema houses delivered a pixelated moving image displayed by tiles which could be flipped mechanically. The control engine for orchestrating the movement of the these tiles was a large noisy machine controlled by a deck of punched cards.
Your task is to emulate such an engine and display a pixelated animation as specified by an input file. The input consists of lines in a fixed-width format, but you may assume whatever is convenient for a line-ending indication. The format is:
SSSSYYxxXXOA
SSSS: 4 digit sequence no. may be padded by blanks or all blank
    YY: the y coordinate affected by this line (descending, top is 0, bottom is m-1)
      xx: the starting x coordinate
        XX: the ending x coordinate
          O: hexadecimal opcode
           A: argument (0 or 1)

The input is explicitly sequenced (if you ever drop your deck of cards on the floor, you'll thank me for this part). That means the program must perform a stable sort of the input lines using the sequence field as a sort key. Lines with the same sequence number must maintain their original relative ordering. (It should work with an unstable sort, if you append the actual line number to the key.) A blank sequence field should be interpreted as lower than any number (ascii collation sequence).
A single statement line can only affect a single y coordinate, but may specify a contiguous range of x values. The ending x value may be left blank or may be identical to the initial value in order to affect a single pixel.
The opcode is a hexadecimal digit which specifies the Universal Binary Function Code which is used as a rasterop. The argument is 0 or 1. The raster operation performed is
pixel = pixel OP argument          infix expression
         --or--
        OP(pixel, argument)        function call expression

So the original value of the pixel enters as X in the UBF table, and the argument value from the statement enters as Y. The result of this function is the new value of the pixel. And this operation is performed upon each x,y pair from xx,YY to XX,YY specified in the statement. The range specified by xx and XX includes both end-points. So
0000 0 010F1

should set pixels 0,1,2,3,4,5,6,7,8,9,10 on row 0.
Output dimensions (m x n) should be 20 x 20 at a minimum, but may be larger if desired. But the grain should show, you know? It's supposed to be pixelated. Both graphical and ASCII-art output are acceptable.
If for example, we wanted to make an image of a pixelated figure:
  #   #
   ###
   ##
   ####
    #
#### ####
   # #

   ###
   # #
   # #

If we draw him with a bit-flipping op, like XOR, it can be drawn and erased regardless of whether the screen is black or white.
    00020261
     0 6 661
     1 3 561
     2 3 461
     3 3 661
     4 4 461
     5 0 361
     5 5 861
     6 3 361
     6 5 561
     8 3 561
     9 3 361
     9 5 561
    10 3 361
    10 5 561

Duplicating this sequence will make the figure appear and disappear.

A larger animation can be composed out-of-order, by specifying different "shots" in the sequence field.
   100 016F0
   101 016F0
   102 016F0
   103 016F0
   104 016F0
   105 016F0
   106 016F0
   107 016F0
   108 016F0
   109 016F0
   110 016F0
   111 016F0
   112 016F0
   113 016F0
   114 016F0
   115 016F0
   200020261
   2 0 6 661
   2 1 3 561
   2 2 3 461
   2 3 3 661
   2 4 4 461
   2 5 0 361
   2 5 5 861
   2 6 3 361
   2 6 5 561
   2 8 3 561
   2 9 3 361
   2 9 5 561
   210 3 361
   210 5 561
    00020261
     0 6 661
     1 3 561
     2 3 461
     3 3 661
     4 4 461
     5 0 361
     5 5 861
     6 3 361
     6 5 561
     8 3 561
     9 3 361
     9 5 561
    10 3 361
    10 5 561
   300020261
   3 0 6 661
   3 1 3 561
   3 2 3 461
   3 3 3 661
   3 4 4 461
   3 5 0 361
   3 5 5 861
   3 6 3 361
   3 6 5 561
   3 8 3 561
   3 9 3 361
   3 9 5 561
   310 3 361
   310 5 561
    00020261
     0 6 661
     1 3 561
     2 3 461
     3 3 661
     4 4 461
     5 0 361
     5 5 861
     6 3 361
     6 5 561
     8 3 561
     9 3 361
     9 5 561
    10 3 361
    10 5 561

Producing:

This is code-golf so shortest program (by byte-count) wins.
Bonus (-50) if the engine makes clickity-clack noises.

Normally one requests clarification by posting to the sandbox. Are you trying to shut the sandbox down?

For me personally, the sandboxes are a dead-end. I'm too good at procrastinating to finish them up. Here, live, I cannot ignore the fire under my butt.

How does the Boolean connector work? Does it only join lines with the same sequence number? If they're mixed, is there some form of operator precedence? Do you have any test cases which rely on Boolean connectors? Why does the test case you posted not have any sequence numbers? Is the ending x coord always inclusive?

Good questions! I've tried to address them all in the update. The Boolean connectors were inspired by the MARKIV mainframe database query language.

Here are some clickety clack noises.  Do I get a bonus? ;-)

Are    0,   00,  000 and 0000 the same sequence ID or are they different?

@Oberon They are different.

For sound, are you thinking something like train station flipboards? E.g. solari board at gare du nord train station in paris or Split-flap Display - DIY driver circuit. Or are you thinking more mechanical relay sounds?

I hadn't imagined the sound very precisely. I really like the train station flipboard sound, but the simpler flipping sound would also be acceptable, as would other mechanical sounds so long as they're appropriately evocative. The motors in the novel would be steam-driven as well, so shrieks and whistles and puffs would also work.

I mentioned this in the chatroom, but I'll repeat it here. The sequence field does seem kinda stupid, from our textfile point-of-view, but think of the cards! Think of piping this input from some kind of shellscript, positional sorting is very natural to shells... perhaps the interactive command-line is the closest modern analogue to an editable card.

@Oberon was that clear? They should be sorted as strings rather than integers, and valid input will only contain spaces or digits 0-9 and if spaces are present, they will be only on the left of any digits present. I suppose you could interpret them as numbers if you treat space as the 'digit' -1 in a base-10 encoding, but leaving them as strings should be simpler I think.

s.b. ^0 in a base-11 encoding^.

Mathematica, 306 281 bytes
This expects the input string to be stored in variable i
ListAnimate[ArrayPlot/@FoldList[({n,y,x,X,o,a}=#2;MapAt[IntegerDigits[o,2,4][[-1-FromDigits[{#,a},2]]]&,#,{y+1,x+1;;X+1}])&,Array[0&,{20,20}],ToExpression/@MapAt["16^^"<>#&,StringTrim/@SortBy[i~StringSplit~"\n"~StringCases~RegularExpression@"^....|..(?!.?$)|.",{#[[1]]&}],{;;,5}]]]

And here with some whitespace:
ListAnimate[ArrayPlot /@ FoldList[(
     {n, y, x, X, o, a} = #2;
     MapAt[
      IntegerDigits[o, 2, 4][[-1 - FromDigits[{#, a}, 2]]] &,
      #,
      {y + 1, x + 1 ;; X + 1}
      ]
     ) &,
   Array[0 &, {20, 20}],
   ToExpression /@
    MapAt["16^^" <> # &,
     StringTrim /@
      SortBy[i~StringSplit~"\n"~StringCases~
        RegularExpression@"^....|..(?!.?$)|.", {#[[1]] &}], {;; , 5}]
   ]]

This got pretty damn long. This challenge contained a lot of fiddly details, and especially the input parsing takes a lot of code in Mathematica (almost half of it, 137 bytes, are just parsing the input). I ended up switching the language twice before settling on Mathematica (I thought I could save on the input parsing by using Ruby, but then I realised the result needs to be animated, so I went back to Mathematica).

Ungolfed Postscript example
This is a "protocol-prolog"-style program, so the data immediately follows in the same source file. Animated gif files can be produced with ImageMagick's convert utility (uses ghostscript): convert clack.ps clack.gif.
%%BoundingBox: 0 0 321 321

/t { token pop exch pop } def
/min { 2 copy gt { exch } if pop } def
/max { 2 copy lt { exch } if pop } def

/m [ 20 { 20 string }repeat ] def
/draw { change {
        m {} forall 20 20 8 [ .0625 0 0 .0625 0 0 ] {} image showpage
    } if } def

%insertion sort from https://groups.google.com/d/topic/comp.lang.postscript/5nDEslzC-vg/discussion
% array greater_function insertionsort array
/insertionsort
{ 1 1 3 index length 1 sub
    { 2 index 1 index get exch % v, j
        { dup 0 eq {exit} if
            3 index 1 index 1 sub get 2 index 4 index exec
            {3 index 1 index 2 copy 1 sub get put 1 sub}
            {exit} ifelse
        } loop
        exch 3 index 3 1 roll put
    } for
    pop
} def

/process {
    x X min 1 x X max { % change? x
        m y get exch  % row-str x_i
        2 copy get  % r x r_x
        dup         % r x r_x r_x
        0 eq { 0 }{ 1 } ifelse  % r x r_x b(x)
        2 mul a add f exch neg bitshift 1 and   % r x r_x f(x,a)
        0 eq { 0 }{ 255 } ifelse  % r x r_x c(f)
        exch 1 index % r x c(f) r_x c(f)
        ne { /change true def } if
        put
    } for
    draw
} def

{ [ {
     currentfile 15 string
         dup 2 13 getinterval exch 3 1 roll
         readline not{pop pop exit}if
    pop
    [ exch
     /b exch dup 0 1 getinterval exch
     /n exch dup 1 1 getinterval exch
     /seq exch dup 2 4 getinterval exch
     /y exch dup 6 2 getinterval t exch
     /x exch dup 8 2 getinterval t exch
     /X exch dup 10 2 getinterval dup (  ) ne { t exch }{pop 2 index exch} ifelse
     /f exch dup 12 get (16#?) dup 3 4 3 roll put t exch
     /a exch 13 get 48 sub
     /change false def
    >>
}loop ]
dup { /seq get exch /seq get exch gt } insertionsort
true exch
{ begin
    b(A)eq{
        { process } if
    }{
        b(O)eq{
            not { process } if
        }{
            pop
            process
        }ifelse
    }ifelse
    change
    end
} forall
    draw
} exec
   100 016F0
   101 016F0
   102 016F0
   103 016F0
   104 016F0
   105 016F0
   106 016F0
   107 016F0
   108 016F0
   109 016F0
   110 016F0
   111 016F0
   112 016F0
   113 016F0
   114 016F0
   115 016F0
   200020261
   2 0 6 661
   2 1 3 561
   2 2 3 461
   2 3 3 661
   2 4 4 461
   2 5 0 361
   2 5 5 861
   2 6 3 361
   2 6 5 561
   2 8 3 561
   2 9 3 361
   2 9 5 561
   210 3 361
   210 5 561
    00020261
     0 6 661
     1 3 561
     2 3 461
     3 3 661
     4 4 461
     5 0 361
     5 5 861
     6 3 361
     6 5 561
     8 3 561
     9 3 361
     9 5 561
    10 3 361
    10 5 561
   300020261
   3 0 6 661
   3 1 3 561
   3 2 3 461
   3 3 3 661
   3 4 4 461
   3 5 0 361
   3 5 5 861
   3 6 3 361
   3 6 5 561
   3 8 3 561
   3 9 3 361
   3 9 5 561
   310 3 361
   310 5 561
    00020261
     0 6 661
     1 3 561
     2 3 461
     3 3 661
     4 4 461
     5 0 361
     5 5 861
     6 3 361
     6 5 561
     8 3 561
     9 3 361
     9 5 561
    10 3 361
    10 5 561
0000 0 515F1
0000 1 11501
0000 1 115F1

The bounding box info was discovered by running gs -sDEVICE=bbox clack.ps.


text:
Code Golf: Create a string of 100 of the same character
The problem is to create a string of the same character repeated 100 times.
One potential solution in JavaScript is:
var i = 100,
    s = '';

while(i--) s += "Z";

Shortest code wins.

This site is intended for puzzles only, not for practical problems. This creates three issues: 1. The task is too trivial to be interesting as a puzzle. 2. The really short answers aren't in JavaScript, so they won't help you. 3. In code golf, O(n) algorithms will have O(n!) implementations, undefined behavior will be invoked and pretty much anything else that should never, ever be present in code that is actually going to be used will be done, if it saves just a single byte.

I edited the question to be on topic but still allow for the existing answers.

Some answers took “create a string” literally and only generate the value leaving it lost in the RAM, while other answers stick with the default of outputting/returning the result. For trivial tasks like this, outputting/returning the result in some languages doubles the code length. I am not sure if this question is ready to be reopened.

3-byte Jelly answer: ⁶×³. This is surely too trivial.

golflua: 109 15
w(S.t("a",100))

Which is more-or-less equivalent to Heiko's Lua answer

Python2.7 - 7 bytes
'a'*100

String manipulation using * pretty simple.

Lua, 24 bytes
This variant is based on Geobits' comment:
print(("").rep("a",100))

Older version, 38 bytes
a=""for i=0,99 do a=a.."a"end print(a)

Ungolfed:
a = ""              -- start with empty string
for i = 0, 99, 1 do -- 100 times
  a = a .. "a"      -- append "a" to variable a
end
print(a)            -- print result

print(string.rep("a",100)) ?

@Geobits: Very good, much shorter (26 bytes).

print(("a"):rep(100)), use the object implementation of string.rep, 21 Bytes ;)

GolfScript, 4 characters:
100*

The input should be on the stack. This program assumes a single-character input.
Test online.
If the character needs to be hardcoded, it's 7 characters:
'a'100*

If the character is a newline and it needs to be hardcoded, 5 characters (thanks to Jan Dvorak):
100n*

Umm... are you expecting a single-character input? Because 100 times nothing is still nothing.

@JanDvorak: Yes, I am. The OP gave an example where he appended a single character 100 times, so I assumed that the input will always be a single character.

In his case, the character was hard-coded in the statement. I that as that you are required to hard-code your own as well.

@JanDvorak: Ah, ok. I added an answer where the character is hardcoded, but I'll still keep the not-hardcoded part around if hardcoding the char is not necessary.

You can reduce the 7-character solution to 5 characters if said character can be a newline: 100n*.

also, n`25* is an interesting solution ;-)

I think the 7-character solution is the only valid one

JavaScript - 20 chars
At least, shorter than Bash ;)
Array(101).join("a")

An array of length 100 joined with letter a.
Perl - 12 chars
First Perl golf !
print"a"x100

Thanks to ace for shortening one character.

Array(100).join(a)  - 18 characters. An array of length 100 joined with a letter from variable a! :D

Is this a Ninja edit or did I not notice your Perl answer before I posted mine? And P.S. you can remove the space between print and "a"x100

The Javascript solution should be Array(101). Array(100).join("a").length == 99

@nderscore Thanks, fixing.

@ace I had just quickly applied my new Perl skills to my post, and noticed that we had posted the same answer at the same time. I was about to notify you, but the electricity went out. And thanks for the tip :)

QBasic : 22
PRINT STRING$(100,"A")

Why not?

Bash+tr, 20 bytes
$ printf %100s|tr \  Z
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ$

Pure Bash, 31 bytes
$ printf -vs %100s;echo ${s// /Z}
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
$

Pretty standard stuff.

GNU dc, 14 bytes
2 800^255/90*P

Output:
$ dc -e '2 800^255/90*P'
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ$

J (7)
Very similar to the Python one
100$'a'

100$'ab' would output 50 times ab, for 100 characters total.

Perl, 7 bytes
"a"x100

Almost completely the same as the Python one.

Brainfuck, 27 characters (or 26 25)
,>++++++++++[<..........>-]

This program requires input, because hardcoding a character is not possible in Brainfuck.
If it is allowed to always output 100 times the NUL character, there is a 25 char solution (thanks to Quincunx):
++++++++++[>..........<-]

Well actually it is possible... if you remove , you will be outputting 100 times of the NUL character.

@ace: Correct, but then you cannot specify the character.

The question never said the character has to be specified anyway...

@ace: The Z character is specified in the question, so a NUL character would probably be invalid.

This is how I interpret it: "...to create a string of the same character repeated 100 times in as short a statement as possible. One potential solution is:" If you interpret it as having to output the Z characters for 100 times then I think it is still possible in BF: you need to add 90 + in front.

@ace: Hmm... that could be indeed. I added it as an alternative solution. Thanks!

Actually, if you could output the NUL character, you could simply do ++++++++++[>..........<-], saving 2 chars from your 27

Haskell
replicate 100 'a'

GHCi output:
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

Code for GHC:
main = print $ replicate 100 'a'

No need for the space between 100 and 'a'.


text:
QR code decoder
Your mission is not so simple. You have to write a program that decodes QR-codes.
There are some things that are not permitted:

Making web requests (except https://i.stack.imgur.com/sCUJT.png or https://i.stack.imgur.com/mXUcd.jpg)
Using any QR code processing library (Or using any external library to do this)
Image processing libraries should not be be used to do anything other than loading image, determining its size and reading single pixels from it
Using built-in functions to read QR codes
Brute forcing

If you use any external files (except QR code file and language libraries), the byte count of those files will be added to your code.
Other rules:

Program must be able to read any valid QR code (No error correction is required). You can assume that the maximum size of QR-Code is 10000 pixels.
QR code colors are black and white. ((0, 0, 0) and (255, 255, 255) in RGB. Alpha channel is not used, so your program can ignore it.
Image file must be saved as PNG or loaded from https://i.stack.imgur.com/mXUcd.jpg or https://i.stack.imgur.com/sCUJT.png runtime. (And tricks like using raw txt file with .png file extension are prohibited)
QR code decoded content must be outputted to stdout. If your language does not allow this, you can save it to file named qrcode.txt.
QR-code format is normal qr-code (not any modification like micro QR code)

This is code-golf, so shortest code wins
An example file is here: http://api.qrserver.com/v1/create-qr-code/?color=000000&bgcolor=FFFFFF&data=http%3A%2F%2Fcodegolf.stackexchange.com&qzone=1&margin=0&size=400x400&ecc=L

Can we get the Imgur URL for free in our submissions? URL shorteners could be used, and it would be unfair if that would break ties.

http://imgur.com/JUQbo8M

Hmm... I forgot that other web requests are disallowed, so URL shorteners actually don't matter here.

"Using language that haves built-in functionality to read QR codes" so I can't even use the language if I omit all that built-in functionality?

No, I mean if yout language have something like decode_qr_code(image) you can not use that

Does it matter what input format we use?

What do you mean?

This question needs more information: Which QR code version do we use (all of them?)? Do we need to flip around the diagonal if we can't decode? Will we always have a nice QR-only picture, or will we need to search through a picture that contains a QR code? Which encodings should we support?  Will we need to support error handling/error handling modes?

"Program must be able to read any valid QR code ... You can assume that maximium size of qrcode is 10000 (100*100) pixels." No, you do not need to flip. qrcode is always as "nice" as example image. Binary (8-bit) encoding. No error handling needed.

This is going to be difficult af spec, iso or whatever is called

This may help somebody: https://www.youtube.com/watch?v=KA8hDldvfv0

Which QR code version/specification do we use? Can we assume that 1 pixel in image = 1 pixel in code or do we have to find out the scale first?

If version means size, then only size is limited. No, you have to scale.

This was helpful http://blog.qartis.com/decoding-small-qr-codes-by-hand/

Could you define "Brute-forcing"? I don't understand it in the context. Unless I check every pixel, I don't see how I could understand the qr code....

As it stands the challenge does not say what counts as a valid QR-Code, nor how they are decoded. As challenges should be self-contained, please add these informations.