text:
Check if three letters can form a "Godel-Escher-Bach cube"
This question is inspired by the cover of the book "Godel, Escher, Bach":

The challenge here is to write a function that tells if three given letters can produce a 3D sculpture that can be read from three sides.
For this exercise, the only letters you can use are 26 5px * 5px bitmaps:

Or in binary (A to Z):
01110  11110  01111  11110  11111  11111  11111  10001  11111  11111  10001  10000  10001  10001  01110  11110  01110  11110  01111  11111  10001  10001  10001  10001  10001  11111
10001  10001  10000  10001  10000  10000  10000  10001  00100  00100  10010  10000  11011  11001  10001  10001  10001  10001  10000  00100  10001  10001  10001  01010  01010  00010
10001  11110  10000  10001  11100  11110  10011  11111  00100  00100  11100  10000  10101  10101  10001  10001  10001  11111  01110  00100  10001  01010  10001  00100  00100  00100
11111  10001  10000  10001  10000  10000  10001  10001  00100  10100  10010  10000  10001  10011  10001  11110  10011  10010  00001  00100  10001  01010  10101  01010  00100  01000
10001  11110  01111  11110  11111  10000  11111  10001  11111  11100  10001  11111  10001  10001  01110  10000  01111  10001  11110  00100  01110  00100  01010  10001  00100  11111

The sculpture is formed by three letters in the following order:

letter one on top,
letter two on the left
letter three on the right
the bottom of letter one is bound to the top of the letter two.

Example:

Your function may accept as input three uppercase letters (three chars or three strings of one letter), and output a boolean (true/false or 0/1) telling if the corresponding sculpture can exist.
Example:
f("B","E","G") // true  (because if you "sculpt out" B on top + E on the left + G on the right, and watch the three sides of the sculpture, you'll see exactly B, E and G as they are defined)
f("B","G","E") // false (because if you "sculpt out" B on top + G on the left + E on the right, and watch the three sides of the sculpture, you won't see a complete G and a complete E. Their shapes bother each other)

NB: you may return true even if the sculpture contains "flying pixels" (cubes or group of cubes that are attached to nothing).
Standard loopholes apply.
More precisely, you can't use external input besides the three letters, and you can't hardcode the 17576 possible answers in your source code
Shortest answer in characters in any language wins!
Have fun :)

You guys gotta be kidding me.

Yep, it's the MU puzzle that made me discover the book, and it's the cover of the book that made me think of this challenge. Is there a problem? Was this a part of your 18 holes thing?

It would have been a good option to replace hole 1. ;) ... Never mind, if anything it's my fault for not getting something up sooner. It's a really decent challenge, +1!

Can we retrieve the data defining the shapes of letters from an external file, or does that need to be included in the source as well?

Your binary B has 0 in the top left corner, not 1.

@m.buettner thanks! I'll try to avoid asking other GEB questions until your 18-hole puzzle :p

@Calvin'sHobbies thanks, fixed it

@CesiumLifeJacket including the letters' data in your function is part of the challenge :) (you can use all Unicode characters)

The direction of letters on the cube is defined by the example and we cannot rotate any face, right?

that's right @Ray.

You may get more hits if you change the title to: "Make a Godel-Escher-Bach cube"

Mathematica 423
I added a section called "How blocking works".
Ungolfed
(*The binary data of the alphabet are stored as a single string in s. vars imports it and converts it into an array.)
vars=IntegerDigits[#,10,5]&/@Transpose[ImportString[s,"Table"]];
get[char_]:=(ToCharacterCode[char]-64)[[1]];
cube=Flatten[Table[{i,j,k},{i,5},{j,5},{k,5}],2];

(* character slice along axis *)
slice[char_,layer_,axis_,bit_]:=Insert[(Reverse@#),layer,axis]&/@Position[Reverse@vars[[get[char]]],bit]

(* cuboid assembly  *)
charBlocks[{char_,axis_,bit_}]:=Flatten[Table[slice[char,k,axis,bit],{k,5}],1]

(* letters are those whose HOLES should be sculped out of the full cube *)
sculpturePoints[letters_(*{char_,axis_,bit_}*)]:=Complement[cube,Union[Join@@(charBlocks/@letters(*{char,axis,bit}*))]];

collapse[letters_(*{char_,axis_,bit_}*),axis_]:=Union[Reverse/@(Delete[#,axis]&/@sculpturePoints[letters(*{char,axis,bit}*)])](*/.{x_,y_}\[RuleDelayed] {6-x,y}*)

vQ[l_]:=collapse[l,3]==collapse[{l[[1]]},3]\[And]collapse[l,2]==collapse[{l[[2]]},2]\[And]collapse[l,1]==collapse[{l[[3]]},1]

validQ@l_:= vQ[{{l[[1]],3,0},{l[[2]],2,0},{l[[3]],1,0}}]

perspective[letts_,view_:1]:=
Graphics3D[{AbsolutePointSize[10],Cuboid/@sculpturePoints[letts]},
ImageSize-> 120,
ViewPoint-> Switch[view,1,{0,0,\[Infinity]},2,{0,-\[Infinity],0},3,{\[Infinity],0,0},4,Top,5,Front,6,Right,True,{0,0,\[Infinity]}],
PlotLabel-> Switch[view,1,"top orthogonal view",2,"front orthogonal view",3,"right orthogonal view",4,"top close-up view",5,"front close-up view",6,"right close-up view"],
ImagePadding->10]

Example
Is the cube {"B", "G", "E"} valid? (i.e. Will the three letters project correctly onto the walls?)
validQ[{"B", "G", "E"}]

False

Illustrations
The figures below show how BGE is rendered. The upper row of figures takes orthogonal perspectives, as if the viewer were positioned at infinite distances from the cube.
The lower row shows how the blocks would look from close up.  The 3D figures can be manually rotated to inspect precisely where the individual unit cubes are positioned.
A problem occurs with the letter "G". There is nothing connecting the serif to the rest of the letter.
pts = {{"B", 3, 0}, {"G", 2, 0}, {"E", 1, 0}}
GraphicsGrid@Partition[Table[perspective[pts, view], {view, 1, 6}], 3]

BEG, however, should work fine.
 validQ[{"B", "E", "G"}]

True

pts2 = {{"B", 3, 0}, {"E", 2, 0}, {"G", 1, 0}}
GraphicsGrid@Partition[Table[perspective[pts2, view], {view, 1, 6}], 3]

How Does Blocking Work?
Please excuse me if this seems obvious, but perhaps some folks will want to visualize how
how letters interfere with each other, canceling their 3D pixels.
Let's follow what happens to the letter G, in the BGE cube rendering.
We'll be paying special attention to the voxel (3D pixel or unit cube) below. That is the pixel that disappears in the BGE cube.  It is the pixel corresponding to Row 4, Column 5 in the bit array and in the corresponding array plot.

In the x y plane, the pixel corresponds to the gray disk at point (5,2). But because we're going to work in 3D, we need to consider the 5 positions in the shaft from (5,1,2) to (5,5,2).  If any of those pixels survives sculpting by the letters B and E, we'll be able to see the pixel of interest in the 3D projection on the wall.

Letters interfere when pixels are removed from the solid block.  In the left, the black arrow represents the carving out of  pixels, corresponding to the bit at the bottom right; it has the value 0 for the letter B.  Carving out removes the pixel at (5,1,2), along with those directly above and below it. Four pixels remain to be accounted for.

But as the right pane shows, the letter E sculpts out the remaining pixels of interest, (5,2,2) (5,3,2), (5,4,2) and (5,5,2). (This is due to the fact that the letter E has bits equal to 0 in the fourth row, from column 2 through column 5.) As a result, not a single pixel remains among those that were needed to ensure shade at point (5,2) on the far wall (for the letter G).  Instead, there will be a bright spot corresponding to a hole in the letter G!  The cube BGE is no good because it incorrectly renders G.
Golfed  423 chars
The function h served the same role as validQ in the unGolfed code.
The rendering function, perspective, is not included because it does not contribute to, and is not required by, the challenge.
x=Reverse;q=Flatten;
g@c_:=(ToCharacterCode[c]-64)[[1]];
r[{c_,a_,b_}]:=q[Table[Insert[(x@#),k,a]&/@Position[x@(IntegerDigits[#,10,5]&/@
Transpose[ImportString[s,"Table"]])[[g[c]]],b],{k,5}],1]
p@l_:=Complement[q[Table[{i,j,k},{i,5},{j,5},{k,5}],2],Union[Join@@(r/@l)]];
w[l_,a_]:=Union[x/@(Delete[#,a]&/@p[l])]
v@l_:=w[l,3]==w[{l[[1]]},3]\[And]w[l,2]==w[{l[[2]]},2]\[And]w[l,1]==w[{l[[3]]},1]

h@l_:= v[{{l[[1]],3,0},{l[[2]],2,0},{l[[3]],1,0}}]

Woah, those 3D views are very neat! Are you sure the last code block is "UnGolfed"? It seems golfed to me. :)

You are correct. The final block is golfed. I corrected the heading.  One cool thing about the 3D views is that they are interactive: rotation and zooming can be done by mouse.

BTW, by my count, there are 564 valid cubes among the 15600 possible permutations.

That's a nice information. How long did it take you to compute that? also, 262626 = 17576, not 15600. Or am I missing something?

I used permutations, not tuples; i.e. no repeated letters. 26 2524 =15600.  It took 21 seconds to find the 564 cases.

Prolog, 440, 414
:- encoding(utf8).
i(I) :- between(0,4,I).
h(T,L,R,X,Y,Z) :- i(X),i(Y),i(Z),I is 4-X,c(T,Z,I),c(L,Z,Y),c(R,X,Y).
f(T,L,R) :- forall((i(U),i(V),I is 4-V),((\+c(T,U,V);h(T,L,R,I,Y,U)),(\+c(L,U,V);h(T,L,R,X,V,U)),(\+c(R,U,V);h(T,L,R,U,V,Z)))).
c(C,X,Y) :- char_code(C,N),i(X),i(Y),Z is X+5*Y+25*(N-65),I is floor(Z/15),O is (Z mod 15),string_code(I,"䙎㹟䘑߯硁䙏縑ԁࠟя摟䠑䠑ᐑ粤Ⴟ䔅┉ё籁垑䙑曓䗱㩑䙏㡏晑䘞䕟㡞縐Ⴄ䙄㩑⩑䒪噑⩊䕤ᅱ粤ࢨ?",V),1 is (V-32)>>O/\1.

The program is called like this:
?- f('B','E','G').
true.
?- f('B','G','E').
false.

Prolog seemed to be a good choice, since it's easy to represent the problem in first order logic. Also Prolog provides potent functionality for solving this kind of problem.
However, since the code is golfed, I guess I should add some explanation.
Mildly golfed version
:- encoding(utf8).
i(I) :- between(0,4,I).
t(C,X,Z) :- I is 4-X,c(C,Z,I).
l(C,Y,Z) :- c(C,Z,Y).
r(C,X,Y) :- c(C,X,Y).
h(T,L,R,X,Y,Z) :- i(X),i(Y),i(Z),t(T,X,Z),l(L,Y,Z),r(R,X,Y).
u(T,L,R) :- forall((i(U),i(V),I is 4-V,c(T,U,V)),h(T,L,R,I,Y,U)).
v(T,L,R) :- forall((i(U),i(V),c(L,U,V)),h(T,L,R,X,V,U)).
w(T,L,R) :- forall((i(U),i(V),c(R,U,V)),h(T,L,R,U,V,Z)).
f(T,L,R) :- u(T,L,R),v(T,L,R),w(T,L,R).
c(C,X,Y) :- char_code(C,N),i(X),i(Y),Z is X+5*Y+25*(N-65),I is floor(Z/15),O is (Z mod 15),string_code(I,"䙎㹟䘑߯硁䙏縑ԁࠟя摟䠑䠑ᐑ粤Ⴟ䔅┉ё籁垑䙑曓䗱㩑䙏㡏晑䘞䕟㡞縐Ⴄ䙄㩑⩑䒪噑⩊䕤ᅱ粤ࢨ?",V),1 is (V-32)>>O/\1.

The coordinates corresponding to the pixels on each side of the dice can be easily converted to a 3D coordinate system. I use T,L and R for top(1), left(2) and right(3) side. u and v are used for the coordinates in the images:

T: (u,v) -> (4-v, ?, u)
L: (u,v) -> (?, v, u)
R: (u,v) -> (u, v, ?)

The results for each active (i.e. black) pixel are combined to a set of "3D-pixels" that can be acitvated without changing the look of the object from this side. The intersection of the sets for each side are all 3D-pixels, that can be activated without adding pixels, that would obstruct the view (i.e. looking from at least one side there would be a pixel that shouldn't be there).
All that remains is to check for each side, if there is a pixel in the intersection that blocks the view, where it's necessary.
This leads to the predicates in the program:

f: does the final check; takes the letters at the top, the left side and the right side
u, v and w: do the checks, if for every pixel active on the side there is a 3D-pixel in the intersection, that blocks the view
h: checks, for the existence of a pixel in the intersection
t,l,r: checks, if a 3D-pixel can be blocked from top, left and right side.
c: checks for the pixel in the image of a letter. The string in there may look a bit strange, but it's only a compact way to store the image data. It's simply a character sequence with the following values(hex notation):
[464e,3e5f,4611,7ef,7841,464f,7e11,501,81f,44f,645f,4811,4811,1411,7ca4,10bf,4505,2509,451,7c41,5791,4651,66d3,45f1,3a51,464f,384f,6651,461e,455f,385e,7e10,10a4,4644,3a51,2a51,44aa,5651,2a4a,4564,1171,7ca4,8a8,3f]

Each of these characters stores the data for 3 pixel rows in letter image(s) (=15 pixel). The pixels are also reordered so that the data is stored at one location and not divided across multiple rows, like the data of the OP.

Mathematic formulation

Input data

Conversion from pixel in one char to set of 3D-pixels that obstruct the view for this pixel

Pixels that can be added safely(without obstructing the view in the wrong place)

Checks for each side, that the pixels that need to be obstructed can be obstructed safely

Combinatin of checks for each side

I.. Uh.. What? I find this incomprehensible. (+1)

Holy... I'm going to bed...

Impressive! Thanks for this answer

Nice. btw, I  think of the process as starting off with a solid cubic block. (You seem to think of it as adding pixels where none were before.) Each letter removes some 3D pixels from that block. So interference arises when a neighboring letter removes pixels that a letter "wanted to keep".  The interference stems from "missing pixels" rather than extra pixels.

J - 223 197 191 char
A function taking a three char list as argument.
(_5#:\".'1b',"#:'fiiifalllvhhhheehhhvhhllvgkkkvnlhhvv444vhhvhhggvhjha44v1111vv848vv248vehhheciiivfjhhedmkkvilll9ggvggu111uo616ou121uha4ahg878ghpljh')((-:0<+/"1,+/"2,:+/)*`(*"1/)/)@:{~_65+3&u:

This golf relies heavily on a powerful feature of J called rank, which gives us the "sculpt out" and "watch side of" operations almost for free. To oversimplify it a bit, rank refers to the dimensionality of a noun or of a verb's natural arguments.
J has multidimensional arrays, and it is obvious that, say, a 3D array can be interpreted as a single 3D array, or as a list of matrices, or a 2D array of vectors, or a 3D array of scalars. So every operation in J can have its application controlled w.r.t. how to be spread over the argument. Rank 0 means apply on the scalars, rank 1 means apply on the vectors, and so on.
   1 + 2 + 3 + 4  NB. add these things together
10
   +/ 1 2 3 4     NB. sum the list by adding its items together
10
   i. 3 4         NB. 2D array, with shape 3-by-4
0 1  2  3
4 5  6  7
8 9 10 11
   +/"2 i. 3 4    NB. add the items of the matrix together
12 15 18 21
   0 1 2 3 + 4 5 6 7 + 8 9 10 11    NB. equivalent
12 15 18 21
   +/"1 i. 3 4    NB. now sum each vector!
6 22 38
   +/"0 i. 3 4    NB. now sum each scalar!
0 1  2  3
4 5  6  7
8 9 10 11

This becomes very powerful when you introduce dyadic (two-argument) functions, because if the shapes of the two arguments (after accounting for rank) are agreeable, J will do some implicit looping:
   10 + 1             NB. scalar addition
11
   10 20 30 + 4 5 6   NB. vector addition, pointwise
14 25 36
   10 + 4 5 6         NB. looping!
14 15 16
   10 20 + 4 5 6      NB. shapes do not agree...
|length error
|   10 20    +4 5 6

When all your shapes are agreeable and you can specify the rank yourself, there are many ways to combine arguments. Here we show off some of the ways that you can multiply a 2D matrix and a 3D array.
   n =: i. 5 5
   n
 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
   <"2 n *"2 (5 5 5 $ 1)  NB. multiply by 2-cells
+--------------+--------------+--------------+--------------+--------------+
| 0  1  2  3  4| 0  1  2  3  4| 0  1  2  3  4| 0  1  2  3  4| 0  1  2  3  4|
| 5  6  7  8  9| 5  6  7  8  9| 5  6  7  8  9| 5  6  7  8  9| 5  6  7  8  9|
|10 11 12 13 14|10 11 12 13 14|10 11 12 13 14|10 11 12 13 14|10 11 12 13 14|
|15 16 17 18 19|15 16 17 18 19|15 16 17 18 19|15 16 17 18 19|15 16 17 18 19|
|20 21 22 23 24|20 21 22 23 24|20 21 22 23 24|20 21 22 23 24|20 21 22 23 24|
+--------------+--------------+--------------+--------------+--------------+
   <"2 n *"1 (5 5 5 $ 1)  NB. multiply by vectors
+---------+---------+--------------+--------------+--------------+
|0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24|
|0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24|
|0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24|
|0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24|
|0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24|
+---------+---------+--------------+--------------+--------------+
   <"2 n *"0 (5 5 5 $ 1)  NB. multiply by scalars
+---------+---------+--------------+--------------+--------------+
|0 0 0 0 0|5 5 5 5 5|10 10 10 10 10|15 15 15 15 15|20 20 20 20 20|
|1 1 1 1 1|6 6 6 6 6|11 11 11 11 11|16 16 16 16 16|21 21 21 21 21|
|2 2 2 2 2|7 7 7 7 7|12 12 12 12 12|17 17 17 17 17|22 22 22 22 22|
|3 3 3 3 3|8 8 8 8 8|13 13 13 13 13|18 18 18 18 18|23 23 23 23 23|
|4 4 4 4 4|9 9 9 9 9|14 14 14 14 14|19 19 19 19 19|24 24 24 24 24|
+---------+---------+--------------+--------------+--------------+

You'll notice that this doesn't actually carve in the letters in the orientation the question asks for, it just writes them in however is convenient for rank logic. Unless we reverse or rotate the letters before we apply them, it won't work right. But correcting things like that would take up precious characters, so instead we'll encode the letters such that, when J carves them in naturally, some triple of faces will be in the correct orientations and relative positions. It turns out the shortest solution is to rotate all the letterforms a quarter-turn counterclockwise. Considering J's third dimension to represent the front-to-back axis, the crude diagram below shows why this scheme works.
 Figure A: The three sides of the cube that J carves into. Figure B: The three sides which have the letters oriented like the question asks.
This choice in encoding saves 12 characters over the previous method, and makes the whole thing neater. The actual golf creates the cube out of the "1 and "2 carves with some funky logic, due to an unrelated optimization.
Then we have to check the faces. Since we encode the block as 1s and 0s, we can just sum along each axis in the way we want (these are the +/"1, +/"2, and +/ bits), adjust to booleans (0<), and then compare them all directly to the original 90°-turned-letters.
The compression scheme encodes each 5px row of each letter as the base 32 representation of a binary number. By exploiting a number of syntactic sugars and operator overloadings, ".'1b',"#: is the shortest way to turn the list of characters into base 36 numbers. Well, technically, base 32, but J thinks it's unary, so who's counting?
Usage is below. Note that strings are character arrays in J, so a three item list 'A','B','C' can be written 'ABC' for short. Also, booleans are 1/0.
   NB. can be used inline...
   (_5#:\".'1b',"#:'fiiifalllvhhhheehhhvhhllvgkkkvnlhhvv444vhhvhhggvhjha44v1111vv848vv248vehhheciiivfjhhedmkkvilll9ggvggu111uo616ou121uha4ahg878ghpljh')((-:0<+/"1,+/"2,:+/)*`(*"1/)/)@:{~_65+3&u:'BEG'
1
   NB. or assigned to a name
   geb=:(_5#:\".'1b',"#:'fiiifalllvhhhheehhhvhhllvgkkkvnlhhvv444vhhvhhggvhjha44v1111vv848vv248vehhheciiivfjhhedmkkvilll9ggvggu111uo616ou121uha4ahg878ghpljh')((-:0<+/"1,+/"2,:+/)*`(*"1/)/)@:{~_65+3&u:
   geb 'BGE'
0

Python, 687 682 671
import itertools as t,bz2
s=range(5)
c=dict([(i,1)for i in t.product(*3*[s])])
z=dict([(chr(i+65),[map(int,bz2.decompress('QlpoOTFBWSZTWXndUmsAATjYAGAQQABgADABGkAlPJU0GACEkjwP0TQlK9lxsG7aomrsbpyyosGdpR6HFVZM8bntihQctsSiOLrWKHHuO7ueAyiR6zRgxbMOLU2IQyhAEAdIJYB0ITlZwUqUlAzEylBsw41g9JyLx6RdFFDQEVJMBTQUcoH0DEPQ8hBhXBIYkXDmCF6E/F3JFOFCQed1Saw='.decode('base64')).split('\n')[j].split()[i])for j in s])for i in range(26)])
def m(a,g):
 for e in c:c[e]&=g[e[a]][e[a-2]]
def f(a):
 g=map(list,[[0]*5]*5)
 for e in c:g[e[a]][e[a-2]]|=c[e]
 return g
r=lambda g:map(list,zip(*g)[::-1])
def v(T,L,R):T,L,R=r(r(z[T])),r(z[L]),z[R];m(1,T);m(2,L);m(0,R);return(T,L,R)==(f(1),f(2),f(0))

Call with v:
v('B','E','G') => True
v('B','G','E') => False

Everything below is from my previous ungolfed version which includes helpful drawing functions. Feel free to use it as a jumping off point.
import string as s
import itertools as t

az = """01110  11110  01111  11110  11111  11111  11111  10001  11111  11111  10001  10000  10001  10001  01110  11110  01110  11110  01111  11111  10001  10001  10001  10001  10001  11111
10001  10001  10000  10001  10000  10000  10000  10001  00100  00100  10010  10000  11011  11001  10001  10001  10001  10001  10000  00100  10001  10001  10001  01010  01010  00010
10001  11110  10000  10001  11100  11110  10011  11111  00100  00100  11100  10000  10101  10101  10001  10001  10001  11111  01110  00100  10001  01010  10001  00100  00100  00100
11111  10001  10000  10001  10000  10000  10001  10001  00100  10100  10010  10000  10001  10011  10001  11110  10011  10010  00001  00100  10001  01010  10101  01010  00100  01000
10001  11110  01111  11110  11111  10000  11111  10001  11111  11100  10001  11111  10001  10001  01110  10000  01111  10001  11110  00100  01110  00100  01010  10001  00100  11111""".split('\n')

dim = range(len(az))
az = dict([(c, [map(int, az[j].split()[i]) for j in dim]) for i, c in enumerate(s.uppercase)])
cube = dict([(i, 1) for i in t.product(*3*[dim])])

def mask(axis, grid):
    for c in cube:
        if not grid[c[axis]][c[axis - 2]]:
            cube[c] = 0

def face(axis):
    grid = [[0 for j in dim] for i in dim]
    for c in cube:
        if cube[c]:
            grid[c[axis]][c[axis - 2]] = 1
    return grid

def rot(grid):
    return map(list, zip(*grid)[::-1])

def draw(grid, filled='X', empty=' '):
    s = ''
    for y in dim:
        for x in dim:
            s += filled if grid[y][x] else empty
        s += '\n'
    print s

def drawAll():
    print 'TOP:\n'
    draw(rot(rot(face(1))))
    print 'LEFT:\n'
    draw(rot(rot(rot(face(2)))))
    print 'RIGHT:\n'
    draw(face(0))

def valid(top, left, right):
    top, left, right = rot(rot(az[top])), rot(az[left]), az[right]
    mask(1, top)
    mask(2, left)
    mask(0, right)
    return top == face(1)and left == face(2) and right == face(0)

letters = 'BEG'

if valid(*letters):
    print letters, 'is valid.\n'
else:
    print letters, 'is not valid!\n'

drawAll()

Call valid to run it:
valid('B', 'E', 'G') #returns True
valid('B', 'G', 'E') #returns False

Right now the code is setup to test the validity of B E G and print out the resulting faces:
BEG is valid.

TOP:

XXXX
X   X
XXXX
X   X
XXXX

LEFT:

XXXXX
X
XXX
X
XXXXX

RIGHT:

XXXXX
X
X  XX
X   X
XXXXX

Running it on B G E we can see that the G is incorrect:
BGE is not valid!

TOP:

XXXX
X   X
XXXX
X   X
XXXX

LEFT:

XXXXX
X
X  XX
X
XXXXX

RIGHT:

XXXXX
X
XXX
X
XXXXX

wow, good job! +1 for drawAll and the completeness of the answer. +1 for using such a short algorithm. <3 it

@xem Thanks! I finally golfed it. Though I couldn't figure out how to get bz2 to decompress unicode characters.

+1. Nice answer. Hope more people will upvote golfs that comprise of smaller golfs, like this, cuz it really takes effort.

g=[[0 for j in s]for i in s] can be shortened to g=map(list,[[0]*5]*5). Also you can avoid indenting blocks if they are a single statement: if c[e]:g[e[a]][e[a-2]]=1.

@Bakuriu and bitpwner, thanks for the suggestions and edits :)

Why not use string.decode('base64')?

If I'm not horribly mistaken, you can use same function to decompress.

The function may not produce correct result after the first call. This might be a "feature", though...

APL (Dyalog Unicode), 150 bytes
x y z←(⎕A⍳⍞)⌷¨⊂26 5 5⍴(8⍴2)⊤⎕AV⍳'5∘⍉⍉c∨wÌþ∩⍀ýFó  â⍒⍪┤ÌÙÍ⊃?>áóU│yEå≥∧+├Û└KEÐ┐⌹;⍉ùigë/⋄⍪,ËwÙ4○$⊣7×c⍺þS¢|⍋îÜ⍀â:b⌷Î'
(x,y,z)≡(∨⌿,∨⌿⍤2,∨/)x×⍤2⊢z∘.×⍤1⊢y

Try it online!
A full program that takes three uppercase letters from stdin and prints 0 (false) or 1 (true) to stdout.
We already have an answer in J which has an excellent primer on multi-dimensional arrays and function rank. This answer uses the same concept. (Plus an obvious advantage that we can efficiently encode the binary arrays using the single-byte character encoding.)
How it works
⍝ Extract the three bit matrices
x y z←(⎕A⍳⍞)⌷¨⊂26 5 5⍴(8⍴2)⊤⎕AV⍳'5∘⍉⍉c∨wÌþ∩⍀ýFó  â⍒⍪┤ÌÙÍ⊃?>áóU│yEå≥∧+├Û└KEÐ┐⌹;⍉ùigë/⋄⍪,ËwÙ4○$⊣7×c⍺þS¢|⍋îÜ⍀â:b⌷Î'
                            ⎕AV⍳'...'  ⍝ Char value of each char w.r.t. the code page
                      (8⍴2)⊤  ⍝ Convert each number to 8 bits, making 8-row matrix
               26 5 5⍴  ⍝ Take the bits and form 26×5×5 brick
      (⎕A⍳⍞)⌷¨⊂  ⍝ Take 3-char input and extract the corresponding 5×5 matrices
x y z←  ⍝ Assign to three variables

(x,y,z)≡(∨⌿,∨⌿⍤2,∨/)x×⍤2⊢z∘.×⍤1⊢y
                         z∘.×⍤1⊢y  ⍝ Combine front and right faces
                                   ⍝ so that three dimensions are oriented naturally
                    x×⍤2⊢  ⍝ Combine the top face
        (∨⌿,∨⌿⍤2,∨/)  ⍝ Compute the top, front, and right views of the pixels
(x,y,z)≡  ⍝ Check if they all match the original faces

You might be able to pack the data even tighter, since this challenge is old enough to count in characters.

Python 3 + numpy, 327C
from numpy import*
B=hstack([ord(x)>>i&1for x in'옮弟ჹ羂옱쏷）ជ࿂︹缘龌ℿ쓥剴ℌᾄ起츱ꎚㆋឺ௣옮忬⧼ﯠႄ挒⺌ꕆ豈ꪱ袨冊䈑∾Ϣ'for i in range(16)])[:-6].reshape(26,5,5)
T=transpose
def f(*X):
 A=ones((5,5,5));F=list(zip([A,T(A,(1,0,2)),T(fliplr(A),(2,0,1))],[B[ord(x)-65]for x in X]))
 for r,f in F:r[array([f]*5)==0]=0
 return all([all(r.sum(0)>=f)for r,f in F])

This golf solution need an external library, numpy, which is quite popular so I think it's fine to use it.
The unicode string is in 41 chars, while the same thing in @fabian's prolog answer is 44.
The most interesting here is that the indexing of numpy array. In a[ix], ix can be an boolean array with the same shape as a. It's the same as saying a[i, j, k] where ix[i, j, k] == True.
Ungolfed Version
import numpy as np
table = '옮弟ჹ羂옱쏷）ជ࿂︹缘龌ℿ쓥剴ℌᾄ起츱ꎚㆋឺ௣옮忬⧼ﯠႄ挒⺌ꕆ豈ꪱ袨冊䈑∾Ϣ'

def expand_bits(x):
    return [ord(x) >> i & 1 for i in range(16)]

# B.shape = (26, 5, 5), B[i] is the letter image matrix of the i(th) char
B = np.hstack([expand_bits(x) for x in table])[:-6].reshape(26, 5, 5)

def f(*chars):
    """
    cube:    ----------   axis:
            /         /|      --------->2
           /   1     / |     /|
          /         /  |    / |
         /         /   |   /  |
        |---------|  3 |  v   |
        |         |    /  1   |
        |    2    |   /       v
        |         |  /        0
        |         | /
        -----------
    """
    cube = np.ones((5, 5, 5))
    cube_views = [
        cube,
        cube.transpose((1, 0, 2)),  # rotate to make face 2 as face 1
        np.fliplr(cube).transpose(2, 0, 1),  # rotate to make face 3 as face 1
    ]
    faces = [B[ord(char) - ord('A')] for char in chars]
    # mark all white pixels as 0 in cube
    for cube_view, face in zip(cube_views, faces):
        # extrude face to create extractor
        extractor = np.array([face] * 5)
        cube_view[extractor == 0] = 0

    return np.all([
        # cube_view.sum(0): sum along the first axis
        np.all(cube_view.sum(0) >= face)
        for cube_view, face in zip(cube_views, faces)
    ])

Script to compress table
import numpy as np

def make_chars():
    s = """
01110  11110  01111  11110  11111  11111  11111  10001  11111  11111  10001  10000  10001  10001  01110  11110  01110  11110  01111  11111  10001  10001  10001  10001  10001  11111
10001  10001  10000  10001  10000  10000  10000  10001  00100  00100  10010  10000  11011  11001  10001  10001  10001  10001  10000  00100  10001  10001  10001  01010  01010  00010
10001  11110  10000  10001  11100  11110  10011  11111  00100  00100  11100  10000  10101  10101  10001  10001  10001  11111  01110  00100  10001  01010  10001  00100  00100  00100
11111  10001  10000  10001  10000  10000  10001  10001  00100  10100  10010  10000  10001  10011  10001  11110  10011  10010  00001  00100  10001  01010  10101  01010  00100  01000
10001  11110  01111  11110  11111  10000  11111  10001  11111  11100  10001  11111  10001  10001  01110  10000  01111  10001  11110  00100  01110  00100  01010  10001  00100  11111
""".strip().split('\n')
    bits = np.zeros((26, 5, 5), dtype=np.bool)
    for c_id in range(26):
        for i in range(5):
            for j in range(5):
                bits[c_id, i, j] = s[i][j + c_id * 7] == '1'
    bits = np.hstack([bits.flat, [0] * 7])
    bytes_ = bytearray()
    for i in range(0, len(bits) - 8, 8):
        x = 0
        for j in range(8):
            x |= bits[i + j] << j
        bytes_.append(x)
    chars = bytes_.decode('utf16')
    return chars

authors: Андрій Мисака


text:
Implement map()...with bugs
EDIT: The behavior may be inconsistent. Also, associative arrays are permitted.
Make a function that iterates through an indexed array, mapping a function of a single argument to each member of the array. The catch: introduce a hidden bug where the function is not correctly applied to at least one index of the input array.
Example:
map(lambda a: a+1, [1, 2, 3, 4])
# Should be [2, 3, 4, 5]
# Could be: [2, 3, 5, 4] or [2, 4, 6, 5] or anything else

Rules:

Use either a static method with two arguments, function and array, or a non-static method with one, an array or function (this being of the other type). Examples:

std::vector<F> map(F (*fn)(E), std::vector<E> array); (C++)
def map(fn, array): ... (Python)
Array.prototype.map = function (fn) {...}; (JavaScript)

If your language features a method already to do this, re-implement it.
The ignored entry may be of any type desired.
Assume the arguments to actually be correct (if the language has dynamic type checking).
It may or may not be in place.
Hide your malice.
Highest vote count wins.

Here's an example of a correct, bug-free implementation in JavaScript (excluding type checking):
Array.prototype.map = function (fn) {
  var i   = this.length,
  ret = new Array(i);
  while (i--) { // decrements to 0 after evaluation
    ret[i] = fn(this[i]);
  }
  return ret;
};

I sense malice in OP ;)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill

@eithedog I meant correct in that it doesn't screw up the array returned. I wasn't worried about type checking when I typed it up. ;)

Does the function ALWAYS have to remove an element or can it be inconsistent in it's behavior?

It can be inconsistent.

Maybe a #define true ((int)(random()*15)-15) could "fix" a few problems...fails 1/15 of the time...

Does the result have to be mostly correct? If I implement a function that looks like it maps another function, but actually just returns an array of 0's, does that count?

@raptortech97 As long as the code itself looks correct. Doesn't matter how correct it really is. The objective is making something that looks correct, but really isn't.

ok thanks for clarifying

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

Perl
sub mymap (&@) {
  my $fn = shift;
  my @ret;
  while (my $val = shift) {
    local $_ = $_[0]; # map calling convention is element in $_
    push @ret, $fn->();
  }
  return @ret;
}

Looks plausible for at least a moment, until you have the sense to go "why isn't he using $val?"

Perl itself looks cryptic to me. Even correct code is hard for me to understand.

Javascript
Let's use Object.defineProperty to define a lazy map function that only evaluates its result the first time it is requested.
function map(arr, f) {
    var result = {};
    for (var i = 0; i < arr.length; i++) {
        var value = arr[i], evaluated;
        Object.defineProperty(result, i, {
            get: function () {
                if (!evaluated) {
                    evaluated = f(value);
                }
                return evaluated;
            }
        });
    }
    result.length = arr.length;
    return result;
}

// Used like this
var x = map([1, 2, 3], function (x) { return x + 1; });

 The code has a pretty common error that often occurs when defining functions inside loops - since JS does not introduce a new context in a for loop, the variables i, value, and evaluated are the same for all the 'get' functions. This means that all elements in the result will be the same, namely f(arr[arr.length - 1]). Not very sneaky, but an interesting quirk of JS.

Addition:

 Sneaky bug #2: if f(arr[arr.length - 1]) returns falsey, accessing an element in the array will apply f again! So sneaky I didn't realize it myself when writing up the sample.

I thought I'd try to take a stab at my own challenge here...please pardon my long spoilers.
JavaScript
It's a bit simplified compared to the spec (it requires type checking and this isn't necessarily an Array instance)
Array.prototype.map = function (fn) {
  var ret = [];
  for (var i in this) {
    ret.push(fn(i));
  }
  return ret;
};

Sounds great! Where's the problem?

 It is widely known in the JavaScript world that the for-in loop returns the indices of arrays, not the entries. The confusion still brings headaches, even to some more seasoned developers.

 Also, in past versions of IE, for-in loops also iterated over additional properties, such as Array.prototype.toString.

 The proper way to fix this bug would be to use this[i] instead of i and append `if (this.hasOwnProperty(i)), so that it looks like this:

 Array.prototype.map = function(fn) {
   var ret = [];
   for (var i in this) {
     if (this.hasOwnProperty(i)) {
       ret.push(fn(this[i]));
     }
   }
   return ret;
 };

This looks correct now?

 Try again. If there is any enumerable property ever assigned to the array, this loop will also see it and apply the function to it. That is relatively easy to do, considering the two standard means of setting properties default to being enumerable (which you can't change this way, either):

 object.prop = val;
 object['prop'] = val;

Keep in mind that you can assign a property to anything in JavaScript. If you were to try that "correct" implementation on a standards-comforming browser you would get this:

 var old = [1, 2, 3, 4, 5];
 old.foo = 'Hi!';
 var new = old.map(function (a) {return a + 1;});
 console.log('Old length: ' + old.length);
 console.log('New length: ' + new.length);
 console.log('Old contents: ' + old); // implicit toString
 console.log('New contents: ' + new);

 Output:
 Old length: 5
 New length: 6
 Old contents: 1,2,3,4,5
 New contents: 2,3,4,5,6,Hi!1

Also, there is no guarantee that the for-in loop iterates in order. The push() method implies the need to be in order. This could mean that the last line could very well print out the contents as 2,6,4,3,Hi!1,5.
The only way to define a non-enumerable property is through Object.defineProperty(), Object.defineProperties(), Object.create(), and the like.
Moral of the story, never use for-in loops to iterate through arrays. It's a code smell, and a terrible one at that. It leads to misunderstanding and bugs. It was clearly designed for associative arrays, not indexed ones. This should prove it. Always use the more standard for loop. Not only is it quicker, it is harder to screw up with. The for loop should have been:

 for (var i = this.length - 1; i > 0; i--) {
   ret[i] = this[i];
 }

Ironically, this could be done out of order.

Had similar idea (creating function nap on Array and iterating via for in, which would cause the length of output array to be increased by one)  - unfortunately the prerequisite of The catch: introduce a hidden bug where the function is not applied to one entry of the input array foiled my plan :D

I loosened it up to "not correctly applied", requiring "at least one" instead of just one to be off, and the behavior being inconsistent (sometimes works), because that was how everyone interpreted the rules. Now, I won't make an exception for just adding one. The first part, "not correctly applied" means either it isn't applied or the output at that index is wrong.

Cool! That opens up more possibilities to abuse JS! :x

@eithedog What do you think of mine?

@eithedog The length shouldn't be the only thing, but there are plenty of ways to abuse JS syntax (from automatic semicolon insertion to for-in returning indices to just plain minor, hard to catch slips with for loops and increments. I have learned to prefer while loops to for loops because of the similar, yet clearer functionality. Unless I'm using a for-in loop to iterate over keys, a generator, etc., I see them as more bug prone. Any sane minifier will convert most while loops, but they generally are somewhat risky if you aren't careful.

As a fan of JS I must say that extending primitives is always a bad idea, I like the approach though :D

@eithedog As the Underhanded C Contest once said, the best underhanded code is clear, straight-forward, obvious, and wrong.

Here's a nice broken recursive lisp function:
(defun xmap (l f) (when (cdr l) (cons (funcall f (car l)) (xmap (cdr l) f))))

 (cdr l) will be NIL when l has one element, so the base case is a single-element list (in which the return value is nothing).  Therefore, the output list is mapped from every element of the input list, except the last one.

This solution has the delightful property of being one letter different from a working function.  Happy debugging with 3AM tired eyeballs!

Lisp itself looks cryptic to me. Even correct code is hard for me to understand.

@JanDvorak Did you copy my Perl comment? ;)

@impinball I absolutely did. I hope you don't mind ;-)

@JanDvorak Nope.

So would (defun xmap (l f) (when (car l) ... work? (note the car in place of the cdr.)

This has a typo: the recursive call to x-map does not match the function name xmap.

You're right. I wonder how that got in there.

C-sharp
So since this function will ship with a large library (really!), we'll have to keep it as generic as possible - it even works for non-zero based arrays (first entry)!
public U[] Map<T, U>(T[] inArray, Func<T, U> fn)
{
    U[] outArray = new U[inArray.Length];

    for (int i = inArray.GetLowerBound(0); i < inArray.GetUpperBound(0); i++)
        outArray[i] = fn(inArray[i]);

    return outArray;
}

 So obviously the '<' in the for-loop should be '<='. An array with 2 elements has an upperbound of 1. The idea behind this trick is that everyone is used to writing 'i = 0; i < a.len', and will hopefully miss this detail at the first glance. The last entry in the outArray will remain zero.

This doesn't work for non-zero-based arrays, even if you fix the </<= bug, does it? outArray is a zero-based array, regardless of whether inArray is, and you use the same index i for both inArray and outArray.

C++
Let's have fun with some meta programming.
template <class ...Args>
struct Helper;

// base case for Helper
template <class F, class T>
struct Helper<F, T, std::tuple<>> {
    using type = std::tuple<T>;
};

template <class F, class T, class ...Args>
struct Helper<F, T, std::tuple<Args...>> {
    using t1 = typename F::template apply<T>;
    using type = std::tuple<t1, Args...>;
};

template <class F, class ...Args>
struct Map;

// base case for Map
template <class F>
struct Map<F, std::tuple<>> {
    using type = std::tuple<>;
};

template <class F, class T, class ...Args>
struct Map<F, std::tuple<T, Args...>> {
    using type = typename Helper<F, T, typename Map<F, typename std::tuple<Args...>>::type>::type;
};

Usage:
struct Func {
    template <class T>
    using apply = typename std::add_rvalue_reference<T>::type;
};

Map<Func, std::tuple<int, double , int const>>::type t;
// t suppose to have type std::tuple<int&&, double&&, int const&&>
// but it is std::tuple<int&&, double&&, int const>

The Map struct is a meta function that can apply another meta function to the types of a  tuple, except the last member...
in Coliru

 While the base case for Map is required to handle empty tuple, the base case for Helper isn't really helpful. Delete it will make everything working again.

PowerShell
I spent two hours trying to think of ways to be tricky with PowerShell, so I hope this isn't too easy to see through. Shouldn't be too hard to figure out what I did here.
function Map-Array($inArray, $functionName){
$outArray = $inArray.Clone()
$inArray.GetLowerBound(0)..($inArray.GetUpperBound($inArray.Rank-1)-1)|%{$outArray[$_-1] = & $functionName $([char]$inArray[$_-1])}
$outArray
}
function Black-Box($in){[char](([int]$in)-32)}
$x=@('a','b','c','d','e','f')

$y = Map-Array -inArray $x -functionName 'Black-Box'

Black-Box capitalizes all letters in the char array $x, anything else it just rolls back 32 spots on the ASCII table.
However...
-join $y
ABCDeF

 Went a little overboard with my array index checking heh.
 Mainly because I like the fact that an index of -1 automatically points to the last element in the array in Powershell.

JS
(after a little editing, because first was second and second was first but now first is more... interesting)
Let me borrow the OP's code, however due to our company's naming policy we need to change the name:
Array.prototype.array_map = function (fn) {
  var i   = this.length,
  ret = new Array(i);
  while (i--) { // decrements to 0 after evaluation
    ret[i] = fn(this[i]);
  }
  return ret;
};

var a = [1,2,3].array_map(function(x){ return x+1 });
console.log(a);

[2, 3, 4, array_map: function]
What's this rubbish?

 The problem lies with definition of properties on objects. Array is an
 object in JS (or  should I say Object). While map property is
 defined (or undefined if your browser is very old), JS has no problems
 with overwriting it and while the value of it will change (from one
 function to the other) the properties of this property won't (map
 isn't enumerable). Creating another method on Array.prototype by
 default defines this property as enumerable and as such is
 "accessible" (or - displays) like any other value of the array. Adding
 call to defineProperty solves this problem:

   var a = [1,2,3].array_map(function(x){ return x+1 }); console.log(a);
[2, 3, 4, array_map: function]
Object.defineProperty(Array.prototype, "array_map", {enumerable : false});
var b = [1,2,3].array_map(function(x){ return x+1 }); console.log(b);
[2, 3, 4]

I always felt that there should be map on objects (associative arrays for you non-JS folks). As there's no such method in JS this code golf gave me the opportunity to write one.
First, let's define method length, as there's no such method in JS on objects as well (sheesh, JS, c'mon):
Object.prototype.length = function() {
    var size = 0;
    for (var key in this)
       size++;
    return size;
}
Now, let's do this!
Object.prototype.map = function (f) {
    var r=this;
    for (var i=0; i<this.length(); i++)
        if (this[i])
            r[i] = f(this[i]);
    return r;
}

Seriously, I don't know why JS didn't have it before. Now, let's test it!
var a = {O: 1, 1: 2, 2: 3};
console.log(a, 1);
console.log(a.map(function(x){ return x+1 }), 2);

Object {1: 2, 2: 3, O: 1, length: function, map: function} 1
Object {1: 3, 2: 4, O: 1, length: function, map: function} 2

Perfect!

 I hope this didn't give too much headache to any of you JS developers out there. This code is riddled with problems - creating methods on Object (big no no), implementation of length (object doesn't actually have length, as methods on given object are part of the object - you can see that in the output itself; you can count the property indexes but this is not the way to do it), but the offending problem is actually a malice on my part - actually the O in the a objects isn't 0. While we're creating r as a copy of object, by iterating through it via for loop we're assigning values to all numeric elements, but r[0] isn't there.

The length method will never work in older IE, because the for-in loop.

Does it have to be cross-browser compliant? I'd say this code being an abomination that shouldn't have been brought to this word, it's another perk!

Nope...even more underhandedness

Could have been worse... A for-in loop with arrays are easy to screw up.

PHP
function map($arr, $func){
    foreach($arr as &$x)
        $x = $func($x);

    $result = array();
    foreach($arr as $x)
        $result[] = $x;
    return $result;
}

 This one is obvious to those who know PHP. $x is still a reference to the last item after the first loop.

Clojure
A simple, lazily evaluating map (basically a simplified version of Clojure's map).
(defn map' [f coll] (if (next coll) (lazy-seq (cons (f (first coll)) (map' f (rest coll))))))

(map' #(* % %) [0 1 2 3 4 5])
=> (0 1 4 9 16)

 You would probably want to check if the collection is empty, without dropping one element from it. (next coll) returns nil if the collection has one element in it. Correct behaviour could be gained by using (seq coll).

Python
Um, since the question says "at least one":
ma = lambda m:[1]*len(m)

Slightly foolproofed:
def ma(p, f):
    return [0] + ma(p[1:],f) if m[0]==1 else [1] * len(m)

I know, I know, bring on the downvotes.
Here's another:
ma = lambda m,f:[f(x) for x in range(len(p))]

source: Stack Exchange

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

sort: votes


text:
Maximum number of PEP8 violations in a single line
Your task is to write a file which contains a line with many pep8 violations.
The rules:

We use pep8 version 1.5.7 and the default settings.
Calling pep8 with other command line options or using a custom rc file is not allowed.
Maximum line length 120 characters.  You can violate E501, sure, but the line which your score is calculated on has to be <= 120 characters.
Your module can have other lines before or after, but only one line contributes to your score.
Your file can contain SyntaxErrors or any kind of garbage, it needn't import or run.

Example of scoring:
The following module thing.py has a score of 2, because it contains a line (line 1) with 2 pep8 violations.
 spam='potato'

To check a score:
~$ mktmpenv
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ pip install pep8==1.5.7
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ echo -n "spam='potato'" > thing.py
(tmp-ae3045bd2f629a8c)~/.virtualenvs/tmp-ae3045bd2f629a8c$ pep8 thing.py
thing.py:1:5: E225 missing whitespace around operator
thing.py:1:14: W292 no newline at end of file

Is this a... language-specific challenge? Because we don't really like these.

I guess it's not really language specific (because the file can contain any garbage) but obviously people familiar with python coding will have some advantage

241
if you want the most error, just go crazy with semicolon
$ cat test.py
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

$ cat test.py | wc -m
120

$ pep8 test.py | wc -l
241

most of the error are:
test.py:1:119: E231 missing whitespace after ';'
test.py:1:119: E702 multiple statements on one line (semicolon)

with those error at the end:
test.py:1:120: E703 statement ends with a semicolon
test.py:1:121: W292 no newline at end of file

@wim couldn't reply to your post so i just put it here. you were right about the advantage, i be surprise if someone figure out something else that cause more error then what i posted above

I think you are a semicolon short. wc counts the trailing newline, but we don't count that for character counts on this site. As you can see in your code quote, your last character is #119. You should get 240, 2 for each semicolon except the last one, 1 for the overly long line, and 1 for ending with a semicolon.

@isaacg ah, you are right, i thought it was weird that it gotten less error than number of character * 2, i blame gedit for adding the invisible newline :P

haha, kind of cheap .. but effective!  +1

123
Yes, more violations than characters!
$ curl -s http://pastebin.com/raw.php?i=RwLJfa0Q | cat
 (  =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =   =
$ curl -s http://pastebin.com/raw.php?i=RwLJfa0Q | wc -m
 120
$ curl -s http://pastebin.com/raw.php?i=RwLJfa0Q | pep8 - | wc -l
 123

The trick is that an = after a ( makes pep think you're doing a keyword in a function call (e.g. foo(bar=12)). In this context, doing [TAB]= triggers both
killpep.py:1:3: E223 tab before operator
killpep.py:1:3: E251 unexpected spaces around keyword / parameter equals

And doing =[TAB] triggers both
killpep.py:1:5: E224 tab after operator
killpep.py:1:5: E251 unexpected spaces around keyword / parameter equals

Gleefully enough, you can just chain these.
This gives a violation count of one per character. I need ( to set it up, but not providing the ) gives us:
killpep.py:2:1: E901 TokenError: EOF in multi-line statement

That's 120. No newline = 121. It managed to trigger the "line too long" error, so that's 122. Finally, using one character to start with a space (thanks eric_lagergren) gives 2 violations instead of 1:
killpep.py:1:2: E111 indentation is not a multiple of four
killpep.py:1:2: E113 unexpected indentation

Victory!

Add a leading whitespace and remove the last z and you'll end up with 103... but whenever I copy this code I get 83 instead of 102. I think the spacing is getting messed up.

@eric_lagergren: I'm using tabs instead of spaces and I guess they aren't copying properly. Will pastebin it I guess!

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


text:
Spiral in the grid
Write a program which enumerates points on a regular grid in the form of a spiral. The output should be the indices of the points (row-major) and the spiral should start at 0 and proceed anti-clockwise.
Here is an illustration of the problem:

Specifications:

Write a program which accepts two integers and writes the result to standard out.
Input: width and height of the grid (range is [1,1024])
Output: indices of grid points in the correct order

Goal:

Entry with fewest characters wins.
Would also be interested in elegant entries for "classic" programming languages.

Examples:

width=3, height=3 => 0 1 2 5 8 7 6 3 4
width=4, height=3 => 0 1 2 3 7 11 10 9 8 4 5 6

Why [popularity-contest]? This seems like it would be better suited for [code-golf].

Thank you for your comment. I was not sure about that and edited it accordingly.

related: http://codegolf.stackexchange.com/questions/769/print-nxn-spiral-of-ascending-numbers (my brain is too tired to figure out if this is only a trivial extension of the other one or not)

What should we write? A complete program? A function? Assume input as variables? Where should the input come from and output go to?

Change "Most elegant entry by popularity vote wins", since this is now [tag:code-golf] no longer [tag:popularity-contest]

Ok I did that. I am in awe for the CJam entry, but somehow it feels like cheating to use a language which is specifically designed for code-golf...

What is the max width/height?

CJam - 18
q~1$*,/{(S*S@zW%}h

Try it at http://cjam.aditsu.net/
The input should contain the 2 numbers separated by space.
Explanation:
q~ reads and evaluates the input
1$* copies the width and multiplies by height
,/ generates the array with all the numbers in order, and splits it in rows
{…}h repeats the block until the condition (at the end of the block) is false
(S*S takes the first row of the grid and adds spaces to separate the numbers
@zW% takes the rest of the grid and rotates it (z = transpose, W% = reverse)
The remaining grid becomes the loop condition; the loop terminates when the grid is empty.

Amazingly tiny. I would not have thought it possible.

Ruby — 96 81
@Ventero knocks off 15 characters with some splatting combined with a really clever default argument!
g=->a=p,*r{a ?a+g[*r.transpose.reverse]:[]}
f=->w,h{g[*[*0...w*h].each_slice(w)]}

Examples:
f[3,3]  # => [0, 1, 2, 5, 8, 7, 6, 3, 4]
f[4,3]  # => [0, 1, 2, 3, 7, 11, 10, 9, 8, 4, 5, 6]

Here's an ungolfed solution in Ruby using just one method for those who are interested:
def spiral(width, height, matrix = [*[*0...width * height].each_slice(width)])
  matrix.empty? ? [] : matrix.shift + spiral(0, 0, matrix.transpose.reverse)
end

Mathematica - 97 characters
w=4;h=3;Flatten@NestList[Reverse@Transpose@Rest@#&,Partition[Range[w h],w],2Min[w,h]-2][[;;,1]]-1

First generate the grid.
Iteratively drop the first row and rotate (transpose + reverse) the remaining matrix.
The number of iterations until we end with 1-dimensional matrix is 2*min(w,h)-2.
Collect the dropped first rows into an array.
Subtract 1 because Mathematica starts indices with 1.

+very clever use of NestList

My PHP version. 349 276 characters.
Same as below but I found out something surprising. In PHP, for loops can have multiple expressions in both pre and post iteration. I never knew that and suddenly they are far more powerful/complex than I thought they were. So could not resist rewriting my first attempt to make use of that.
Anyway, new and improved code here - 73 characters shorter than the first:
<?php $a=4;$b=3;$c=-1;$d=$a*$b;$e=$a;$f=($b-1);function c($g,$k){
global $c,$d;for($l=0;$l<$g;$c=$c+$k,++$l,--$d,print $c.' ');}while($d>0)
{$m=1;$g=$e;c($g,$m);--$e;if($f>0){$m=$a;$g=$f;c($g,$m);--$f;if($e>0)
{$m=-1;$g=$e;c($g,$m);--$e;if($f>0){$m=-$a;$g=$f;c($g,$m);--$f;}}}}?>

which can be seen here:
Original attempt below
No where near as cool as the 18 chars of CJam (which I shall be googling about in a minute) but this is the full php program that takes the width and height as the first two parameters.
<?php $a=4;$b=3;$c=-1;$d=$e=0;$f=($b*$a);function calc($g,$h,$j,$k){for($l=$g;
$l<$h;++$l){$k=$k+$j;echo' '.$k;}return($k);}while($f>0){if($d<$a){$c=calc($d,$a,1,$c);
$f=$f-($a-$d);++$e;if($e<$b){$c=calc($e,$b,$a,$c);$f=$f-($b-$e);++$d;
if($d<$a){$c=calc($d,$a,-1,$c);$f=$f-($a-$d);++$e;
if($e<$b){$j=0-$a;$c=calc($e,$b,$j,$c);$f=$f-($b-$e);}}}}++$d;}?>

You can see it in action here: http://codepad.org/qPUWwY2J (above paste has had extra line breaks so it all shows on the page without side scrolling.)
I think this puzzle was a great question and I must admit that starting on 0 caused some issues for me. I have checked lots of different grids and it seems to work well although takes a bit of time to work through large grids.
My answer simply recognizes that moving left and right is adding +1 or -1 to the start number used, and up or down just adds or subtracts the original width. It then simply steps down the height and width counters for each pass. All of the output is in a function that I just send the change, step count and start number to. I reckon I could get a few more characters off by not declaring variables, but not 300 or so.
Great puzzle, had some tricky bits but I enjoyed it, thank you.

Glad you like it!

This is one of the things I like best about code-golf - it exposes you to powerful features you don't know of languages you otherwise know well

JavaScript - 225 Characters
w=8,h=8
{for(a=[0],x=y=b=r=t=l=s=0;a.length<w*h;){if(s==0&&x+r+1==w&&++b+1||s==1&&y+t+1==h&&++r+1||s==2&&x==l&&++t+1||s==3&&y==b&&++l+1)s=(s+1)%4
s==0&&++x+1||s==1&&++y+1||s==2&&--x+1||--y
a.push(x+w*y)}alert(a.join(' '))}

And ungolfed:
w = 8 // width of grid
h = 8 // height of grid
for(a = [0], // array
    x =      // x pos
    y =      // y pos
    b =      // bottom rows done
    r =      // right rows done
    t =      // top rows done
    l =      // left rows done
    s = 0;    // current side 0: b, 1: r, 2: t, 3: l
  a.length < w*h;) {
    if (s==0 && x+r+1==w && ++b+1 ||
        s==1 && y+t+1==h && ++r+1 ||
        s==2 &&     x==l && ++t+1 ||
        s==3 &&     y==b && ++l+1 ){
        s=(s+1)%4
    }

    s==0 && ++x+1 ||
    s==1 && ++y+1 ||
    s==2 && --x+1 ||
            --y

    a.push(x+w*y)
}
alert(a.join(' '))

The code sets the grid size in w and h. It stores current coordinates in x and y. It navigates in direction s, and stores the number of rows already filled on the sides in b, r, t and l.
A demo is at http://jsfiddle.net/L2ReA/

You can easily save a few characters by writing x=y=b=r=t=l=s=0 instead of x=0,y=0,b=0,r=0,t=0,l=0,s=0.

for(x=y=b=r=t=l=s=0;a.length<w*h;) is even shorter, combining the loop with the assignment.

I don't think I see the function definition anywhere.

@TheRare The function encloses all the code, I did not include it in my code.

Usually you should include the function definition too, if one should be there.

@TheRare I've made it freestanding now, so it doesn't need to be in a function


text:
Difference of expressions when evaluated in different orders
We all know the standard order of operations for math functions
(PEMDAS),
but what if we instead evaluated expressions left-to-right?
The Challenge
Given a string through standard input or through command line args, find the difference between the traditional evaluation (PEMDAS) and the in-order (left-to-right) evaluation of that expression.
Details

You will be given a string in a format such as:
"1 + 2 * 3 ^ 2 - 11 / 2 + 16"

To simplify things, there will be:

a space between each number and operator
no leading or trailing spaces
no decimal numbers or negative numbers (non-negative integers only)
no operators beyond +(plus), -(minus), *(multiply), /(divide), ^(exponentiation)
no parens to worry about
you may remove the spaces if it's easier for you to handle, but no other modification of the input format will be allowed.

You must provide the absolute value of the difference between the two evaluations of the string
Your division can either be floating-point or integer division - both will be accepted
Your program can not use any sort of expression evaluation library.
To clarify - any sort of built-in eval function in which your language evaluates a string that is valid code for the same language IS acceptable
Explanations of your code are preferred
Shortest code by byte count wins
Winner will be chosen Saturday (July 19, 2014)

Examples:
A: 1 + 2 * 3 ^ 2 - 11 / 2 + 16 (using floating-point division)

In traditional order of operations:
1 + 2 * 3 ^ 2 - 11 / 2 + 16   -->   1 + 2 * 9 - 11 / 2 + 16   -->

1 + 18 - 5.5 + 16             -->   29.5

In-order traversal yields:
1 + 2 * 3 ^ 2 - 11 / 2 + 16   -->   3 * 3 ^ 2 - 11 / 2 + 16   -->

9 ^ 2 - 11 / 2 + 16           -->   81 - 11 / 2 + 16          -->

70 / 2 + 16                   -->   35 + 16                   -->

51

Resulting difference: 51 - 29.5 = 21.5

B: 7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2  (using integer division)

In traditional order of operations:
7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2   -->   7 - 1 * 9 + 41 / 3 + 2 * 9 * 2   -->

7 - 9 + 13 + 18 * 2                  -->   7 - 9 + 13 + 36                  -->

47

In-order traversal yields:
7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2   -->   6 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2   -->

18 ^ 2 + 41 / 3 + 2 * 9 * 2          -->   324 + 41 / 3 + 2 * 9 * 2         -->

365 / 3 + 2 * 9 * 2                  -->   121 + 2 * 9 * 2                  -->

123 * 9 * 2                          -->   1107 * 2                         -->

2214

Resulting difference: 2214 - 47 = 2167

Can we use parentheses if we want to...? or are they forbidden?

They're forbidden. I'll make that edit.

@KyleMcCormick Is eval forbidden? If so It appears that only the Haskell answer is valid.

Dosen't eval sort of vastly simplify the challenge? I mean for most langauges with eval, eval = the traditional order. (And surely you folks can do better than Haskell, even without eval...!)

@MtnViewMark There is still a challenge when allowing evals. The challenge comes with doing both orders of operations. Languages will not eval for both orders. Golfers will most likely end up with one easier(shorter) case akin to their language's syntax and one harder(longer) case that requires more manipulation.

GolfScript, 84 characters
' '/.{?}:^;(~\2/{~~\~}/\{\?}:^;-1%'^'{[`{2$?0<!{@~\~@~`}*}+/]}:C~-1%'*/'C'+-'C~~-abs

This version does integer division and therefore yields a different result for the first test case. You may try the code here.
> 1 + 2 * 3 ^ 2 - 11 / 2 + 16
21

> 7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2
2167

Code with comments:
' '/.            # split the input at spaces and save a copy for each evaluation

# LTR evaluation
{?}:^;           # define ^ to be the power operator
(~\              # convert the left most string (first operand) into a number
2/{              # loop over the rest in pairs of two
  ~              #   split pair
  ~              #   evaluate second item of tuple (i.e. numeric operand)
  \~             #   apply the operator to two items on stack
}/               # end loop

# standard evaluation
\{\?}:^;         # redefine ^ to be the rtl power operator
-1%              # -1%  .... -1% reverse the input in order to handle right associativity
'^'
{                # {...}:C~ define code-block C and apply it to the string '^'
  [`{            # stringify the argument in order to add it to the internal
                 # code-block. afterwards loop over the input array and collect
                 # the results in an array
    2$?0<!       # if the second top item on the stack is one of the provided operators
    {
      @~         #   take the first operand and convert to number
      \~         #   take the second operand and convert to number
      @~         #   apply the operator
      `          #   stringify result
    }*           # end if
  }+/]
}:C~
-1%

'*/'C            # afterwards apply the same code-block for operators * and /
'+-'C            # and then for operators + and -
~~               # flatten the resulting array and convert the result to a number

-abs             # take absolute difference between the two evaluation methods

Haskell, 281 256 characters
(x:o:y:z)%p|p o=(show(m o(read x)$read y::Float):z)%p|1<3=x:o:(y:z)%p;z%_=z
m"+"=(+);m"-"=(-);m"*"=(*);m"/"=(/);m"^"=(**);m _= \a->abs.(a-)
l=(%(\_->1<3))
t e=foldl(%)e$map(\w->(`elem`w).head)["^","*/","+-"]
d e=l$l e++"~":t e
main=interact$concat.d.words

Brief explaintaion:

% reduces an expression, so long as the operator meets some predicate p
show(m o(read x)$read y::Float) applies an operator to the two string arguments, producing a string result
m maps a string to an operator; note the string "~" is mapped to absolute difference
l computes left-to-right order by applying % once, with a predicate that is always true
t computes traditional order by repeatedly applying % with tests that match operators first of higher precedence, then lower
d computes the two values, then forms a new expression with operator ~ and computes that

Runs:
& echo "1 + 2 * 3 ^ 2 - 11 / 2 + 16" | runhaskell 34599-EvalOrder.hs
21.5

& echo "7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2" | runhaskell 34599-EvalOrder.hs
2178.3333

(Second result differs from example above because this code always computes in floating point.)

Perl 204 (203 + 1 for the -p flag)
LOL using eval got boring (s/\^/**/g;$_=eval"("x(()=/\d+/g).s/(\d+)/\1)/rg."-($_)") as I saw  Calvin's Hobbies's comment on the eric_lagergren's answer so here's an non-eval method:
$d='([-\d.]+)';$s=$t=$_;map{$o=$_;$s=~s|$d (.) $d|($1*$3,$1+$3,0,$1-$3,$1**$3,$1/$3)[ord($2)%6]|e,$t=~s|$d ([\\$o]) $d|($1*$3,$1+$3,'',$1-$3,$1**$3,$1/$3)[ord($2)%6]|eg for$t=~/./g}'^/*-+'=~/./g;$_=$s-$t

Ungolfed:
# shortcut
$d = '([-\d.]+)';

# initial values for the traditional and sequential evaluation
$s = $t = $_;

# split the list of operators and loop throught them
map {
    # store current operator in $o
    $o=$_;

    # repeatedly evaluate the input string until the calculations are done
    for($t=~/./g) {
        # Here is an array with calculated all operators and I pick the correct element
        # ord($2)%6 is never 2 so I put 0 in that position of the array
        $s=~s|$d (.) $d|($1*$3,$1+$3,0,$1-$3,$1**$3,$1/$3)[ord($2)%6]|e;
        $t=~s|$d ([\\$o]) $d|($1*$3,$1+$3,'',$1-$3,$1**$3,$1/$3)[ord($2)%6]|eg
    }
} ('^/*-+'=~/./g);

# subtract the traditional evaluation form the in-order one
$_ = $s - $t

This solution uses floating point calculations.
Output:
$ PS1='\n\$ '

$ ./order.pl <<<"1 + 2 * 3 ^ 2 - 11 / 2 + 16"
21.5
$ ./order.pl <<<"7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2"
2178.33333333333

Why not read the question before writing the answer? "Your program can not use any sort of expression evaluation library"

I literally meant a "library". Doing an "eval" procedure which treats a string as code from its own language is acceptable. Made this clarification yesterday.

Python 208
d=x=input();z=2;u='('*(((len(x)-len(x.replace(' ','')))/2)+1);d=x=d.replace(r'^','**');x=x.split();p=u+''.join(")".join(x[i:i+z]) for i in range(0,len(x),z))+")";m=eval(p)-eval(d);m=m*-1 if 0>m else m;print m;

Calvin'sHobbies comment::
import re;e=input().replace('^','**');print abs(eval(e)-eval(e.count(' ')/2*'('+re.sub('(\d) ',r'\1)',e)))

Explanation:
# variable d  =  x, and x  =  user input

d = x = input()

# variable z = 2

z = 2

# I take the length of the string 'x' (aka the equation we're solving) with
# *all* whitespaces removed (it's the 'len(x.replace(' ', '')...' part) and
# subtract that from 'len(x)' which is the vanilla length of our equation
# I divide the total by two and add one for reasons I'll explain in a minute
# the '(' * part means to make a string with as many '(' as I get from multiplying
# so '(' * 5 = '(((((', '(' * 3 = '((('

u = '(' * (((len(x) - len(x.replace(' ', ''))) / 2) + 1)

# Here I replace the caret with **, because in Python ^ == **
# I also split the string by whitespaces, but only for x;

d = x = d.replace(r'^','**'); x = x.split();

# I set the variable p = to the result of joining the list (aka array) that
# I just made with the .split() in the above section first with a ')' on every
# second character (e.g. [1,2,3,4,5,6] would be 1,2),3,4),... etc. I do it like
# this because in our math equation we'll (hopefully) follow the pattern of
# num op num op num op... etc. I insert parenthases because I'm using PEMDAS
# to my advantage by grouping each set of numbers in the order I want them
# to be completed. The initial ''.join simply rejoins all elements into a
# complete string (basically removes the commas that are left over from
# converting a list -> string). I add a '(' to the end because every 2nd
# character would skip the final one

p = u + ''.join(")".join(x[i:i + z]) for i in range(0, len(x), z)) + ")"

# I eval() both p and d. eval() will run arbitrary code, so you can pass it a
# string and it will act as if the string is code, so while print '1+1' would
# usually result in TypeError (or Value? I forget), print eval('1+1') would
# print '2', I have to do them separately because eval() thinks I wanna
# subtract two string for whatever reason

m = eval(p) - eval(d)

# Here I make use of Python's ternary operators by saying this:
# if 0 > m:
#   m = m * -1
# else:
#   m
# which means that if m is negative, multiply it by -1 to make it
# a positive number so we can get the absolute value. If it's not negative
# then we can just have m and not do anything with it

m = m * -1 if 0 > m else m

# Print m :)

print m

Wouldn't using eval not follow the rule "Your program can not use any sort of expression evaluation library"?

@Calvin'sHobbies I assumed OP meant something like a module that purposely ignored PEMDAS or something like this:http://stackoverflow.com/questions/12540306/z3python-converting-string-to-expression

If that's the case then here's a much shorter Python answer with 106 characters: import re;e=input().replace('^','**');print abs(eval(e)-eval(e.count(' ')/2*'('+re.sub('(\d) ',r'\1)',e)))

@Calvin'sHobbies fiiiiiiine I'll re-write it...


text:
Recover a bzip2 file
The popular .bz2 compression format is used to store all sorts of things. One of the more interesting features is that it consists of several independently decompressible blocks, allowing recovery of partial segments if the file is damaged. The bzip2recover program, included with bzip2, allows recovery of blocks from a bzip2 archive. In this challenge, you will implement a simple clone of bzip2recover.
The basic idea is to scan a bitstream for a particular magic number, and output blocks delimited by this magic number to separate files. Read on for gory details.

Technically, bzip2 files are a bitstream, with every group of 8 bits being stuffed into a byte. The first bit is placed in the most significant bit of a byte, with the eighth bit going in the least significant bit of a byte. Files begin with the header "BZh", and a digit "N" from 1 to 9 indicating the compression level (9 is the most common). Then the bitstream begins.
The bitstream is split up into blocks. Each block encodes N*100KB of uncompressed text (e.g. 900KB of text for compression level 9).
Blocks can begin basically anywhere in the bitstream, and do not necessarily begin on 8-bit boundaries. Blocks begin with a magic number, which is set to the 48-bit sequence 0x314159265359 (in ASCII, "1AY&SY"). For example, the sequence of bytes "73 14 15 92 65 35 90" contains the magic number, offset by 4 bits within the byte.
Your goal will be to take a bzip2 file on stdin, and output each detected BZip2 block to a separate decompressible file. Specifically, your program does the following:

Read and skip the bzip2 header ("BZh" + N)
Scan the bitstream for the magic sequence
Copy the bitstream between two consecutive magic sequences to a new file, with a new BZip2 header and block header. Note that this may require realigning the bitstream to start at a byte boundary, and padding the last byte.

You don't have to care about parsing the blocks, and you can assume that a magic sequence always starts a block (i.e. that it isn't in the middle of a block).
How you name the output files is up to you. The only requirement is that they be clearly sequential somehow (so, e.g. "a b c ... z aa ab" or "1 2 3 4 5 .. 9 10 11 12" are both acceptable).

For a test case, you may use this file from the IPSC 2014 problem-solving contest. The file is a bzip2 file with four blocks. The file as a whole actually decompresses to another bzip2 file with 162 complete blocks. Therefore, you may use these block counts to validate that your solution is getting all of the blocks. (Note that the file actually decompresses even further into more bzip2 files, but you probably don't want to decompress it all the way).

This is code golf, with a twist: your score is the number of bytes in the bz2-compressed version of your source code. (I'm aware this may make submissions larger, but these are the rules!). Since bzip2 compressors may differ in performance, provide a base64-encoded version of the compressed file to prove it's size. (You may therefore be able to obtain a better score by optimizing your program for bzip2, though I don't necessarily expect anyone to do this). Standard loopholes apply.

Python 3 -- 375(534 chars)
It can process the example file d2.in in about 10 seconds, using Pypy3. With CPython 3, it will cost 60 seconds.
It's interesting and weird that some old golf tricks would make the score worse! For example, replacing <space>+<space> by + would increase the score from 375 to 384; replacing all range by R will also increase the score to 384.
Golfed
import sys
from collections import deque
def T(B):
 for i in range(0,len(B),8):
  x=0
  for j in range(min(8,len(B)-i)): x |= B[i + j] << (7-j)
  yield x
V=sys.argv
C=F=0
B=bytearray()
I=open(V[1],'rb')
H=I.read(4)
P=deque([(x>>(7-j)) & 1 for x in b'1AY&SY' for j in range(8)])
Q=deque([0]*48)
for x in I.read():
 for j in range(8):
  b=(x>>(7-j)) & 1
  B.append(b)
  Q.popleft()
  Q.append(b)
  if Q!=P: continue
  C+=1
  M,B=B[:-48],B[-48:]
  if F:F.write(bytes(T(M)))
  F=open(V[2] + str(C),'wb')
  F.write(H)
F.write(bytes(T(B)))

Base64
QlpoOTFBWSZTWSoMWQ0AAMLfgAAQYf901zlibSo/t//kMAFaCIaCQANTTTKMnlGg8oeRpPaoNDDAAAAAaAAAAABKaSGmmpplD0jQaAABo00ZNqLfKsdHBd3QgkQ2wY3RfYpMMjPpsyit5Ee6+k6E6ObzlFT2vmgbSKPkni7ZgDkcwTRiLFBmNCuEX/HtOC8KJ+Rg51SkMCiAGXZpXbvaK+DzMLvaEhAM8reCB8HFAsNYfRghS9+i5/IpLrDzGZVhsbVOpQzHIIVZ7zCCgDkcElOMvTuvfw2bruKz2WQuvEg99gDa8T3Kw2GdyMNjEVFVVQj4sU1MaOTUcwQROwt86LfUZAOJE6HqnB60CFO38NJmpifx+trcQ8x5alqRiEGoKC2wJpPkCXpT7fbtFDbLCLQaplK23qMTC5gqGwCghjN3zEtwyKhCz3kixqBr7gya6yPG03rMOGY9hlmV3tS0W/SdC2taUpCoNSEaEnUXckU4UJAqDFkN

Obviously, I'm not sure these will help, but here's some standard golf tricks to try out: Use from collections import*. Use semicolon separation instead of newline within a for loop in any line that does not begin with a statement (if, for, etc.). You only use P once, so don't assign it to a variable. Remove spaces around all of your operators - particularly in the first for j in... line, but also around the & in the definition of P and in the definition of b.


text:
ASCII Waterworks
Intro
Consider a grid of the characters f A\/ such as
f  f  f
      A
   A / \
\ /     A
    A \/
   /
 \/

where:

f represents a faucet that pours a stream of water downward
A bifurcates the stream of water above so exactly half goes left and exactly half goes right
\ shifts the stream of water above to the right by one unit
/ shifts the stream of water above to the left by one unit
the combinations \/ creates a trough with infinite capacity that collects the water streams above it
[space] is empty space than the water can move through

From this we can imagine the path the water (*) would take as it comes out of the faucets and falls either into the troughs or out of the grid area:
f  f  f    <-- first second and third faucets
*  * *A*
* *A*/ \*
\*/ *  *A  <-- a '*' is not drawn to the right of this A because it would be out of the 9×7 bounds
 * *A*\/   <-- upper trough
 **/ *
 \/  *     <-- lower trough

Assuming the 3 faucets output the same amount of water one at a time we can see that

All of the first faucet's water goes to the lower trough.
One half of the second faucet's water goes to the lower trough and the other half is split between the lower trough and falling off the grid.
One quarter of the third faucet's water goes to the lower trough, one quarter falls off the bottom of the grid, one quarter goes into the upper trough, and one quarter falls off the grid to the right.

From this we can tell that (1 + 3/4 + 1/4 + 1/4) / 3 = 75% of the water is caught by the troughs and (1/4 + 1/4 + 1/4) / 3 = 25% falls off the grid.
Challenges
You may complete any or all of these challenges relating to this ASCII water flow setup. They are all code-golf, the shortest answer for each challenge is the winner. The accepted answer will be the person who completes the most challenges, with total code length as tie-breaker.
Challenge 1
Write a program that outputs the fraction of water that flows into troughs for a given grid. The output of the example above would simply be 0.75.
Challenge 2
Write a program that, given a grid, draws the *'s in the places water flows as I've done above. You should not overwrite anything besides space characters and the grid should not change size. So for something like
 f
/A

nothing needs to be done since, although water does flow on either side of the A, it can't be drawn to the left without removing the / and it can't be drawn to the right without making the 2×2 grid bigger.
Challenge 3 (Updated)
Write a program that takes in two non-negative integers, the total T and the amount to keep K (T >= K). Generate and draw a grid with exactly one f such that when that faucet pours out T units of water, exactly K will flow into troughs. If it is impossible to do this in a finite grid for a particular (T, K) pair then output 'Impossible'.
Clarifications (apply to all challenges)

Input can be via stdin, or a file, or even a function call on the string representation of the grid. Just make it obvious how to run different inputs.
Output must go to stdout.
\A and A/ and AA are also troughs as you'd expect.
A w by h grid will always be a well formatted rectangle of w*h characters not counting newlines. There will be no missing trailing spaces and no occurrences of *.
The grid dimensions can be as small as 1×1 and arbitrarily large. (Arbitrarily large within reason, int.maxValue or the like is an acceptable limit. Same goes for T and K.)
A stream above an f flows right through it.
The faucets can be anywhere, not just on the top row.
A always divides the amount of water poured on it exactly in half.

Note: Things like /A and // are perfectly valid. The water does freely flow between the characters (though for challenge 2 there's not enough room to draw it).
So, in the setup
ff

/A

The left f stream pours down, hits the / and shifts left. The right f stream pours down, hits the A, half goes right and half goes left between the A and the /.
e.g.
 ff
 **
*/A*
** *
** *

+1 Nice challenge. As for challenge 3, the grid at top would not be a valid answer because it has 3 fs

@edc65 Ah, good catch!

Very very similar: http://codegolf.stackexchange.com/questions/26059/where-will-the-ball-land

Regarding challenge 3, what about floating point inaccuracies in P? Also I'd recommend changing the overall winner to something like the person who solves most challenges, tie-breaker being overall byte count.

@m.buettner I suppose that might be an issue so I just revised challenge 3 to take ints rather than a float. I also updated how I'll select the winner to what you said. Hopefully it will encourage people to try all 3 challenges.

For the second challenge, you need to specify how to handle input like /A if water falls onto the A. For all challenges, it would be good to clarify whether \A is a trough. For the third challenge, should 3 units falling on an A be assumed to split 1.5 / 1.5 (so the input is really a single rational number) or is it 2 / 1, in which case which side receives the 2?

@PeterTaylor Thanks. I've clarified those points. I guess T and K could be floats but I'm keeping them integers for simplicity. (But if T=3 does hit an A then both sides do get 1.5. It's up to the coder to make sure float precision is not an issue.)

@Calvin'sHobbies I think you might want to browse through some of your earlier challenges and accept some answers. ;)

@MartinBüttner I have been meaning to. So much reassessing...

All Challenges C# 690bytes (416bytes + 274bytes)
Challenges 1&2 C# 579 446 416bytes
This is a complete program which should do Challenges 1 & 2, just about. It reads lines of input from stdin until it receives an empty line. It prints out the result for Challenge 2, and then the result for Challenge 1. Uses the .NET decimal class to hopefully avoid any rounding errors.
using C=System.Console;class P{static void Main(){decimal u,t=0,f=0;string c,z="";for(decimal[]n=null,o;(c=C.ReadLine())!="";z+='\n'){int s=c.Length,i=s,e;o=n;n=new decimal[s];for(o=o??n;i-->0;n[i]+=(e&2)*u/2){e=c[i]%13;u=o[i]/(e<1?2:1);if(e%8<1)if(i>0)if(c[i-1]%7<3)t+=u;else n[i-1]+=u;if(e<2)if(i<s-1)if(c[i+1]%2>0)t+=u;else n[i+1]+=u;if(e>9){u++;f++;}}for(;++i<s;)z+=c[i]<33&n[i]>0?'*':c[i];}C.WriteLine(z+t/f);}}

Less golfed:
using C=System.Console;
class P
{
    static void Main()
    {
        decimal u,t=0,f=0;
        string c,z="";

        for(decimal[]n=null,o;(c=C.ReadLine())!="";z+='\n')
        {
            int s=c.Length,i=s,e;
            o=n;
            n=new decimal[s];
            for(o=o??n;i-->0;n[i]+=(e&2)*u/2)
            {
                e=c[i]%13;
                u=o[i]/(e<1?2:1);

                if(e%8<1)
                    if(i>0)
                        if(c[i-1]%7<3)t+=u;
                        else n[i-1]+=u;
                if(e<2)
                    if(i<s-1)
                        if(c[i+1]%2>0)t+=u;
                        else n[i+1]+=u;
                if(e>9)
                {
                    u++;
                    f++;
                }
            }
            for(;++i<s;)
                z+=c[i]<33&n[i]>0?'*':c[i];
        }

        C.WriteLine(z+t/f);
    }
}

Test run (with a lack of trailing spaces which I promise are there):
f  f  f
      A
   A / \
\ /     A
    A \/
   /
 \/

f  f  f
*  * *A*
* *A*/ \*
\*/ *  *A
 * *A*\/
 **/ *
 \/  *
0.75

Challenge 3 C# 274bytes
This is a complete program which should complete Challenge 3. I a managed to save 6bytes by writing my own integer parser to read the input rather than Spliting a ReadLine and using long.Parse;
using C=System.Console;class P{static void Main(){long t=-1,f=t,k;for(;f<0;)for(f=t,t=0;(k=C.Read())>47;)t=t*10+k-48;var r="Impossible\n";for(k=t;k<t*f;)k*=2;if(f<1||(k/f)*f==k)for(r=" f \n";t>0&t<f;t-=(t/f)*f)r+=((t*=2)<f?" ":"A")+"A \n/ /\n";C.Write(r+(t<f?"":"AAA\n"));}}

Less golfed:
using C=System.Console;
class P
{
    static void Main()
    {
        long t=-1,f=t,k;
        for(;f<0;)
            for(f=t,t=0;(k=C.Read())>47;)
                t=t*10+k-48;

        var r="Impossible\n";
        for(k=t;k<t*f;)
            k*=2;
        if(f<1||(k/f)*f==k)
            for(r=" f \n";t>0&t<f;t-=(t/f)*f)
                r+=((t*=2)<f?" ":"A")+"A \n/ /\n";
        C.Write(r+(t<f?"":"AAA\n"));
    }
}

Test run (again with a lack of trailing spaces which I promise are there):
32 17
 f
AA
/ /
 A
/ /
 A
/ /
 A
/ /
AA
/ /

First of all, I have a question regarding the challenge. Since I do not have enough reputation to comment on the question, I'm writing it here:

What is the behavior of /A (water flowing on A), // (water flowing on the right side) and variations of this principle? Does the water flow to the first "free spot" on the side or does is flow "below" its neighbour?

Just a simple try, it can be waaaaay simplified (which I will do later by editing this post).
Edit: Second version, a little bit smaller. I went for a different approach: instead of looking for each cell to check what's comming from the top and sides, I start from the faucets and "flow" downwards with recursion.
Javascript, 226 bytes (Challenge 1)
function f(c){function h(b,a,d,e){b<c.length&&0<=a&&a<c[0].length&&("\\"==c[b][a]?"/"==e||"A"==e?g+=d:h(b,a+1,d,"\\"):"/"==c[b][a]?"\\"==e||"A"==e?g+=d:h(b,a-1,d,"/"):"A"==c[b][a]?"A"==e||"\\"==e||"/"==e?g+=d:(h(b,a-1,d/2,"A"),h(b,a+1,d/2,"A")):h(b+1,a,d,c[b][a]))}for(var g=0,m=0,k=0;k<c.length;k++)for(var l=0;l<c[k].length;l++)"f"==c[k][l]&&(h(k+1,l,1),m++);alert(g/m)};

Javascript, 204 bytes (Challenge 2)
function f(c){function e(b,a,d){b<c.length&&0<=a&&a<c[0].length&&("\\"==c[b][a]?"/"!=d&&"A"!=d&&e(b,a+1,"\\"):"/"==c[b][a]?"\\"!=d&&"A"!=d&&e(b,a-1,"/"):"A"==c[b][a]?"A"!=d&&"\\"!=d&&"/"!=d&&(e(b,a-1,"A"),e(b,a+1,"A")):(" "==c[b][a]&&(c[b][a]="*"),e(b+1,a,c[b][a])))}for(var g=0;g<c.length;g++)for(var h=0;h<c[g].length;h++)"f"==c[g][h]&&e(g+1,h)};

Javascript, 238 bytes (Challenge 1 + 2)
function f(c){function h(b,a,d,e){b<c.length&&0<=a&&a<c[0].length&&("\\"==c[b][a]?"/"==e||"A"==e?g+=d:h(b,a+1,d,"\\"):"/"==c[b][a]?"\\"==e||"A"==e?g+=d:h(b,a-1,d,"/"):"A"==c[b][a]?"A"==e||"\\"==e||"/"==e?g+=d:(h(b,a-1,d/2,"A"),h(b,a+1,d/2,"A")):(" "==c[b][a]&&(c[b][a]="*"),h(b+1,a,d,c[b][a])))}for(var g=0,m=0,k=0;k<c.length;k++)for(var l=0;l<c[k].length;l++)"f"==c[k][l]&&(h(k+1,l,1),m++);alert(g/m)};

How to use
Provide a two dimensionnal representation ofthe map. Here is the example provided in the question:
var input = [["f"," "," ","f"," "," ","f"," "," "],[" "," "," "," "," "," ","A"," "," "],[" "," "," ","A"," ","/"," ","\\"," "],["\\"," ","/"," "," "," "," "," ","A"],[" "," "," "," ","A"," ","\\","/"," "],[" "," "," ","/"," "," "," "," "," "],[" ","\\","/"," "," "," "," "," "," "]];
f(input);

Output
Challenge 1: It will simply create a dialog box (alert) with the result (0.75 for the example above).
Challenge 2: It will directly modify the map. Should I print it? If so, is console.log is accepted? as a valid output?
Challenge 1+2: Both of above combined, obviously...

The water keeps on flowing between the characters as if it is hugging the lines of the A or the slashes. I've clarified that in the question.

The question states Output must go to stdout.

You specified as input format that you haveyo give an array of one-character strings per row, but bear in mind you can index str[0] into strings. That would be an array of strings instead of an array of arrays of characters.

user80551 Thanks, I don't know why it slipped out of my mind. I will update my code as soon as possible.
@tomsmeding Yes, it works for my answer of the challenge 1. But for the challenge 2 I'm directly modifying the input and you cannot modify a character in a string using str[i], hence the use of an array of arrays.

Python 3, 186 bytes (Challenge 3)
I took the idea for the grid from VisualMelon's answer. The function should print a valid grid to stdout for arbitrarily large T and K, provided it is possible (finite size grid) of course.
from fractions import*
def c(T,K):
 p=print;g=gcd(T,K);K//=g;T//=g
 if T&(T-1):p('Impossible')
 else:
  p(' f ')
  while T-1:
   T//=2;p('A/'[K<T]+'A \n///')
   if K>=T:K-=T
  p('AAA'*K)

How to use
Call the c function with the total amount and amount to keep as arguments.
>>> c(24, 9)
 f
/A
///
AA
///
AA
///

>>> c(6, 2)
Impossible